试图找出一种使用全局变量的方法,而不是实际创建全局变量。
我正在工作的框架,我将用于所有未来的项目,并希望有一个数据库表包含网站的变化功能(网站名称,颜色,标志链接等)
如果我没有使用Laravel,我会在头文件include中包含一个函数文件,它设置了一个包含所有这些值的数组,这样我就可以直接调用它了。
<?= $constants['business_name] ?>在Laravel中,我可以创建一个函数来获取一个名称,然后返回值,但这似乎是对db调用的过度浪费。
我发现:
View::share但是我得到了变量未定义的错误。
我试过了:
public function __construct()
{
$constants = DB::table('constants')->get();
return $constants;
View::share('constants', $constants);
}在我的BaseController中,但是错误显示出来了,你知道吗?
发布于 2015-03-06 17:04:43
您甚至在调用View::share()之前就从构造函数返回
public function __construct()
{
$constants = DB::table('constants')->get();
return $constants; // <<<<<<
View::share('constants', $constants);
}实际上,构造函数不应该返回任何东西,所以删除该行就可以了:
public function __construct()
{
$constants = DB::table('constants')->get();
View::share('constants', $constants);
}您可能还希望查看视图编写器,以便在不需要构造函数的情况下使数据全局可用:
View composers - Laravel docs
https://stackoverflow.com/questions/28895305
复制相似问题