所有控制器和视图的全局变量 [英] global variable for all controller and views

查看:125
本文介绍了所有控制器和视图的全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Laravel中,我有一个表设置,我从BaseController的表中获取了完整的数据,如下所示:

  public函数__construct()
{
//获取站点设置对象
$ site_settings =设置:: all();
查看:: share('site_settings',$ site_settings);
}

现在我想访问$ site_settings。在所有其他控制器和视图中,我不需要一次又一次地写相同的代码,所以任何人都可以告诉我解决方案或任何其他方式,这样我就可以从表中获取数据并在所有控制器中使用它,首先,一个配置文件适合这种事情,但你也可以使用另一种方法,它是(Laravel - 4):

  //你可以保存在你的filters.php文件中
App :: before(function($ request){
App :: singleton('site_settings',function(){
return Setting :: all();
});

//如果你使用这行代码,那么它可以在任何视图
//作为$ site_settings使用,但你也可以使用app('site_settings')以及
View: :share('site_settings',app('site_settings'));
});

要获取任何控制器中的相同数据,您可以使用:

  $ site_settings = app('site_settings'); 

有很多方法,只需使用其中一种,您更喜欢哪种方式,但我使用容器


In Laravel I have a table settings and i have fetched complete data from the table in the BaseController, as following

public function __construct() 
{
    // Fetch the Site Settings object
    $site_settings = Setting::all();
    View::share('site_settings', $site_settings);
}

Now i want to access $site_settings. in all other controllers and views so that i don't need to write the same code again and again, so anybody please tell me the solution or any other way so i can fetch the data from the table once and use it in all controllers and view.

解决方案

At first, a config file is appropriate for this kind of things but you may also use another approach, which is as given bellow (Laravel - 4):

// You can keep this in your filters.php file
App::before(function($request) {
    App::singleton('site_settings', function(){
        return Setting::all();
    });

    // If you use this line of code then it'll be available in any view
    // as $site_settings but you may also use app('site_settings') as well
    View::share('site_settings', app('site_settings'));
});

To get the same data in any controller you may use:

$site_settings = app('site_settings');

There are many ways, just use one or another, which one you prefer but I'm using the Container.

这篇关于所有控制器和视图的全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆