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

我刚开始和 Laravel 一起工作。我需要用 Laravel4作为基本框架,重写几年前开发的整个系统。在我以前的系统中,我使用一个声明了一些常量的 constant.php文件和一个包含大量数组集的 globals.php文件(例如,类别状态、事件类型、 lang 等)。通过这样做,我可以使用

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

在我的应用程序的任何地方。

我的问题是,我怎样才能存储所谓的“幼虫的方式”的信息。我尝试使用某种对象来存储这些信息,将其设置为一个服务,并为其创建一个 facade:

App/library/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/library/Project/ConstantsServiceProvider.php

namespace PJ;


use Illuminate\Support\ServiceProvider;


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

App/library/Project/ConstantsFacade.php

namespace PJ;


use Illuminate\Support\Facades\Facade;


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

作曲家 Json

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

所以我以 PJ\Constants::$langs的形式访问这个属性。

这种方法是有效的,但我怀疑它是否是最有效或正确的方法。我的意思是,通过创建一个完整的服务提供者和 facade 等等来“传播”变量是正确的方法吗?或者我应该把这些数据放在哪里?

谢谢你的建议。

编辑 # 01

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

我的数组是这样的:

$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 是与类别相关联的信息。

我需要这个数组,也可在所有控制器和视图。

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

112606 次浏览

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

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');

And you can set them as well

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

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

Update

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
}

And query all categories

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.

For global constants in Laravel 5, I don't like calling Config for them. I define them in Route group like this:

// global contants for all requests
Route::group(['prefix' => ''], function() {
define('USER_ROLE_ADMIN','1');
define('USER_ROLE_ACCOUNT','2');
});

For Constants

Create constants.php file in the config directory:-

define('YOUR_DEFINED_CONST', 'Your defined constant value!');


return [


'your-returned-const' => 'Your returned constant value!'


];

You can use them like:-

echo YOUR_DEFINED_CONST . '<br>';


echo config('constants.your-returned-const');

For Static Arrays

Create static_arrays.php file in the config directory:-

class StaticArray
{


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'
];


}

You can use it like:-

echo StaticArray::$langs['en'];

Note: Laravel includes all config files automatically, so no need of manual include :)

Just to add to the above answer you will have to include the config class before you could start using it in Laravel 5.3

use Illuminate\Support\Facades\Config;

I think the best way is to use localization.

Create a new file messages.php in resources/lang/en (en because that is what is set in my config/app 'locale'=>'en') return an array of all your values

return [
'welcome' => 'Welcome to our application'
];

to retrieve for laravel 5.3 and below

echo trans('messages.welcome');

or

echo Lang::get('messages.welcome');

for 5.4 use

echo __('messages.welcome')

laravel 5.0 localization

or

laravel 5.4 localization

Atleast in Laravel 5.4, in your constructor you can create them;

public function __construct()
{
\Config::set('privileged', array('user1','user2');
\Config::set('SomeOtherConstant', 'my constant');
}

Then you can call them like this in your methods;

\Config::get('privileged');

Especially useful for static methods in the Model, etc...

Reference on Laracasts.com https://laracasts.com/discuss/channels/general-discussion/class-apphttpcontrollersconfig-not-found

Create common constants file in Laravel

app/constants.php

    define('YOUR_CONSTANT_VAR', 'VALUE');


//EX
define('COLOR_TWO', 'red');

composer.json add file location at autoload in composer.json

"autoload": {
"files": [
"app/constants.php"
]
}

Before this change can take effect, you must run the following command in Terminal to regenerate Laravel’s autoload files:

composer dump-autoload

Just put a file constants.php file into the config directory and define your constants in that file, that file will be auto loaded, Tested in Laravel 6+

Create a constants class:

<?php
    

namespace App\Support;
    

class Constants {
/* UNITS */
public const UNIT_METRIC = 0;
public const UNIT_IMPERIAL = 1;
public const UNIT_DEFAULT = UNIT_METRIC;
    

}

Then use it in your model, controller, whatever:

<?php


namespace App\Models;


use App\Support\Constants;


class Model
{
public function units()
{
return Constants::UNIT_DEFAULT;
}
}