php - Laravel 为所有自定义助手、 Controller 和模型设置全局变量

标签 php codeigniter global-variables laravel-5.4

我以前在 codeigniter 中问过这个问题,现在我想在 laravel 中问这个问题。

我想为自定义助手、模型和 Controller 设置一个全局变量 该变量是从数据库结果中获取的..

例子如下:

不知道把变量放在哪里

 $data= DB::table('categories')->where('id', '2')->first();
 $this->product_var = $data->product;  **//main global variable**

自定义助手

function test() {
    if($this->product_var=="product name") {

    }
}

我的 Controller

function index() {
    echo $this->product_var;
}

我的模型

function get_data() {
     echo $this->product_var;
}

正如您在上面看到的我的脚本,$this->product_var 几乎用于custom helpermy controller我的模型。 在 codeigniter 中,我们在库文件夹中创建 Globals.php,或者只是将变量放在核心 Controller 中。 我应该在哪里设置全局变量?

最佳答案

就像@Mozammil 提到的:

这个想法是使用“Laravel 配置”。这允许您在一个请求周期内将值保留在全局范围内。

您可以使用 Laravel 的 config() 帮助程序在整个应用程序中访问这些值。

你只需要像这样设置一次:

config(['app.product_data' => $data]);

而且,这将在应用程序中全局可用,只需使用 config('app.product_data') 访问数据即可。

喜欢:

在自定义助手中

function test() {
    if(config('app.product_data')->product_var=="product name") {
         //do something
    }

}

您的 Controller

function index() {
    echo config('app.product_data')->product_var;
}

您的模型

function get_data() {
     return config('app.product_data')->product_var;
}

希望这会有所帮助。

关于php - Laravel 为所有自定义助手、 Controller 和模型设置全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44107225/

相关文章:

php - 带有查询的数组对象

C - 静态变量屏蔽全局变量

PHP 正则表达式 - 使用元字符作为分隔符

PHP - 如果两个条件有更多结果,则仅获取一行

php - 尝试通过php输出我的数据库中最富有的用户

php - 如何从数据库中检查Checkbox Codeigniter?

javascript - Jquery + Ajax,Params有数据但响应说没有数据

php - 如何将图片路径和名称上传到数据库 - Codeigniter

javascript - QUnit 一页中有多个脚本,但它们之间没有交互

global-variables - 使用 Hugo,如何从基本文件中定义的部分文件访问变量?