Laravel:在哪里存储全局数组数据和常量?

2022-01-08 00:00:00 php laravel laravel-4 global-state

我刚开始使用 Laravel.我需要重写我几年前制作的整个系统,使用 Laravel 4 作为基础框架.在我的旧系统中,我曾经有一个声明了一些常量的 constant.php 文件,以及一个包含许多数组集(例如,类别状态、事件类型、语言等).通过这样做,我可以使用类似的东西

I just started working with Laravel. I need to rewrite a whole system I made some years ago, using Laravel 4 as base framework. In my old system, I used to have a constant.php file with some constants declared, and a globals.php file which contained lots of array sets (for example, categories statuses, type of events, langs, etc.). By doing so, I could use something like

foreach ( $langs as $code => $domain ) {
    // Some stuff
}

在我的应用中的任何位置.

anywhere in my app.

我的问题是,我怎样才能以所谓的laravel 方式"存储这些信息.我尝试使用某种对象来存储此信息,将其设置为服务并为其创建外观:

My question is, how can I store that info in the so called "laravel way". I tried using some sort of object to store this info, setting this as a service and creating for it a facade:

app/libraries/Project/Constants.php

namespace PJ;

class Constants {

    public static $langs = [
            'es' => 'www.domain.es',
            'en' => 'www.domain.us',
            'uk' => 'www.domain.uk',
            'br' => 'www.domain.br',
            'it' => 'www.domain.it',
            'de' => 'www.domain.de',
            'fr' => 'www.domain.fr'
        ];
}

app/libraries/Project/ConstantsServiceProvider.php

namespace PJ;

use IlluminateSupportServiceProvider;

class ConstantsServiceProvider extends ServiceProvider {
    public function register() {
        $this->app->singleton('PJConstants', function() {
            return new Constants;
        });
    }
}

app/libraries/Project/ConstantsFacade.php

namespace PJ;

use IlluminateSupportFacadesFacade;

class ConstantsFacade extends Facade {
    protected static function getFacadeAccessor() { 
        return 'PJConstants';
    }
}

composer.json

"psr-4": {
     "PJ\": "app/libraries/Project"
},

所以我以 PJConstants::$langs 的形式访问该属性.

and so I access that property as PJConstants::$langs.

这行得通,但我怀疑这是最有效或最正确的方法.我的意思是,通过创建一个完整的服务提供者和外观以及所有这些东西来传播"一个变量是正确的方法吗?或者我应该把这些数据放在哪里?

This works, but I doubt it is the most efficient or correct way of doing it. I mean, is it the right way to "propagate" a variable by creating a whole Service Provider and facades and all such stuff? Or where should I put this data?

感谢您的建议.

编辑#01

我想传递给所有控制器和视图的数据可以直接在脚本中设置,就像我帖子开头的示例一样,但是它也可以从数据库动态生成例子.该数据可以是类别列表.我需要它们在所有视图中生成导航栏,但我还需要它们来定义一些路由模式(如 /category/subcategory/product),还需要在多个控制器中解析一些信息(如从持有 X 产品的类别中获取信息).

Data I want to pass to all controllers and views can be directly set in script, like in the example at the beginning of my post, but it can also be generated dynamically, from a database for example. This data could be a list of categories. I need them in all views to generate a navigation bar, but I also need them to define some routing patterns (like /category/subcategory/product), and also to parse some info in several controllers (Like get info from the category that holds X product).

我的数组是这样的:

$categories = [
    1 => ['name' => 'General', 'parent' => 0, 'description' => 'Lorem ipsum...'],
    2 => ['name' => 'Nature', 'parent' => 0, 'description' => 'Lorem ipsum...'],
    3 => ['name' => 'World', 'parent' => 0, 'description' => 'Lorem ipsum...'],
    4 => ['name' => 'Animals', 'parent' => 2, 'description' => 'Lorem ipsum...']
]

仅作为示例.Index是分类的id,Value是分类关联的信息.

Just as an example. Index is the id of the category, and the Value is info associated with the category.

我需要这个数组,也可以在所有控制器和视图中使用.

I need this array, also, available in all Controllers and Views.

那么,我应该将它保存为 Config 变量吗?我还能如何存储这些数据;最好的和语义正确的方法是什么?

So, should I save it as a Config variable? How else could I store these data; what would be the best and semantically correct way?

推荐答案

对于在应用程序中全局使用的大多数常量,将它们存储在配置文件中就足够了.也很简单

For most constants used globally across the application, storing them in config files is sufficient. It is also pretty simple

app/config 目录中创建一个新文件.我们称之为 constants.php

Create a new file in the app/config directory. Let's call it constants.php

在那里你必须返回一个配置值数组.

In there you have to return an array of config values.

return [
    'langs' => [
        'es' => 'www.domain.es',
        'en' => 'www.domain.us'
        // etc
    ]
];

您可以按如下方式访问它们

And you can access them as follows

Config::get('constants.langs');
// or if you want a specific one
Config::get('constants.langs.en');

你也可以设置它们

Config::set('foo.bar', 'test');

请注意,您设置的值不会保留.它们仅适用于当前请求.

Note that the values you set will not persist. They are only available for the current request.

配置可能不是存储从数据库生成的信息的正确位置.您可以只使用 Eloquent 模型,例如:

The config is probably not the right place to store information generated from the database. You could just use an Eloquent Model like:

class Category extends Eloquent {
    // db table 'categories' will be assumed
}

并查询所有类别

Category::all();

如果由于某种原因整个模型的事情没有解决,您可以开始考虑创建自己的类和外观.或者你可以创建一个包含所有静态变量和方法的类,然后在没有外观的情况下使用它.

If the whole Model thing for some reason isn't working out you can start thinking about creating your own class and a facade. Or you could just create a class with all static variables and methods and then use it without the facade stuff.

相关文章