我希望每个视图中都有关于系统区域设置的信息,这样我就可以突出显示用户当前选择的任何语言。经过一番谷歌搜索,我发现了官方文档中解决的价值共享问题。但是,在将代码放入boot()
后,如下所示:
class AppServiceProvider extends ServiceProvider{
public function boot(){
view()->share('locale', 'Lang::getLocale());
}
}
在视图中访问 $locale
变量时,始终保存默认的系统区域设置,而不是当前选定的区域设置。为什么?
我通常使用View Composers,所以它更清晰易读。
例如,如果我想与我所有视图的主导航栏共享一个变量,我遵循以下规则:
1. 创建新的服务提供商
您可以使用工匠 CLI 创建服务提供商:
php artisan make:provider ViewComposerServiceProvider
在 ViewComposerServiceProvider 文件中,创建 composeNavigation 方法,其中具有表示具有共享变量的导航菜单的刀片模板 main.nav-menu。
ViewComposerServiceProvider 如下所示:
<?php
namespace App'Providers;
use Illuminate'Support'ServiceProvider;
class ViewComposerServiceProvider extends ServiceProvider
{
/**
* Bootstrap the application services.
*
* @return void
*/
public function boot()
{
$this->composeNavigation();
}
/**
* Register the application services.
*
* @return void
*/
public function register()
{
//
}
private function composeNavigation()
{
view()->composer('main.nav-menu', 'App'Http'ViewComposers'NavComposer');
}
}
2. 创建作曲家
正如您在上面的文件中所看到的,我们有 App''Http''ViewComposers''NavComposer.php所以让我们创建该文件。在 App''Http 中创建文件夹 ViewComposers,然后在 中创建 NavComposer.php 文件。
导航编辑器.php文件:
<?php
namespace App'Http'ViewComposers;
use App'Repositories'NavMenuRepository;
use Illuminate'View'View;
class NavComposer
{
protected $menu;
public function __construct(NavMenuRepository $menu)
{
$this->menu = $menu;
}
public function compose(View $view)
{
$thing= $this->menu->thing();
$somethingElse = $this->menu->somethingElseForMyDatabase();
$view->with(compact('thing', 'somethingElse'));
}
}
3. 创建仓库
正如您在上面看到的 NavComposer.php 文件中,我们有存储库。通常,我在应用程序目录中创建一个存储库,因此在应用程序中创建存储库目录,然后在 NavMenuRepository.php 文件中创建。
此文件是该设计模式的核心。在该文件中,我们必须获取要与所有视图共享的变量的值。
看看下面的文件:
<?php
namespace App'Repositories;
use App'Thing;
use DB;
class NavMenuRepository
{
public function thing()
{
$getVarForShareWithAllViews = Thing::where('name','something')->firstOrFail();
return $getVarForShareWithAllViews;
}
public function somethingElseForMyDatabase()
{
$getSomethingToMyViews = DB::table('table')->select('name', 'something')->get();
return $getSomethingToMyViews;
}
}
对于有小项目的人:
首先,接受的答案很棒!
对于Laravel 5.2用户:
只需在视图中使用新的刀片指令@inject
,如下所示
@inject('shared','App'Utilities'SharedWithView')
然后你可以使用它: {{ $shared->functionName() }}
SharedWithView是一个简单的类,如下所示:
namespace App'Utilities;
use App'Repositories'SomeRepositoryLikeArticlesRepository;
class SharedWithView {
public function functionName() {
$properNameHere = new SomeRepositoryLikeArticlesRepository();
return $properNameHere->forEaxmpleGetMostViewedArticles( 10 );
}
}