php Laravel:在哪里存储全局数组数据和常量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26854030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel: Where to store global arrays data and constants?
提问by Marco Madue?o Mejía
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
我刚开始使用 Laravel。我需要重写我几年前制作的整个系统,使用 Laravel 4 作为基础框架。在我的旧系统中,我曾经有一个constant.php
声明了一些常量的globals.php
文件,以及一个包含大量数组集(例如,类别状态、事件类型、语言等)的文件。通过这样做,我可以使用类似的东西
foreach ( $langs as $code => $domain ) {
// Some stuff
}
anywhere in my app.
在我的应用程序中的任何地方。
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:
我的问题是,如何以所谓的“laravel 方式”存储该信息。我尝试使用某种对象来存储此信息,将其设置为服务并为其创建外观:
app/libraries/Project/Constants.php
应用程序/库/项目/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
应用程序/库/项目/ConstantsServiceProvider.php
namespace PJ;
use Illuminate\Support\ServiceProvider;
class ConstantsServiceProvider extends ServiceProvider {
public function register() {
$this->app->singleton('PJConstants', function() {
return new Constants;
});
}
}
app/libraries/Project/ConstantsFacade.php
应用程序/库/项目/ConstantsFacade.php
namespace PJ;
use Illuminate\Support\Facades\Facade;
class ConstantsFacade extends Facade {
protected static function getFacadeAccessor() {
return 'PJConstants';
}
}
composer.json
作曲家.json
"psr-4": {
"PJ\": "app/libraries/Project"
},
and so I access that property as PJ\Constants::$langs
.
所以我访问该属性为PJ\Constants::$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?
这有效,但我怀疑这是最有效或最正确的方法。我的意思是,通过创建整个服务提供者和外观以及所有这些东西来“传播”变量是正确的方法吗?或者我应该把这些数据放在哪里?
Thanks for any advice.
感谢您的任何建议。
EDIT # 01
编辑#01
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, butit 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).
我想传递给所有控制器和视图的数据可以直接在脚本中设置,就像我文章开头的例子一样,但它也可以动态生成,例如从数据库中生成。该数据可以是类别列表。我需要在所有视图中使用它们来生成导航栏,但我还需要它们来定义一些路由模式(例如/category/subcategory/product
),以及解析多个控制器中的一些信息(例如从包含 X 产品的类别中获取信息)。
My array is something like:
我的数组是这样的:
$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...']
]
Just as an example. Index is the id of the category, and the Value is info associated with the category.
举个例子。Index 是类别的 id,Value 是与类别相关的信息。
I need this array, also, available in all Controllers and Views.
我也需要这个数组,在所有控制器和视图中都可用。
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?
那么,我应该将其保存为 Config 变量吗?我还能如何存储这些数据;什么是最好的和语义正确的方法?
回答by lukasgeiter
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
在app/config
目录中创建一个新文件。让我们称之为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 Modellike:
配置可能不是存储从数据库生成的信息的正确位置。您可以只使用Eloquent 模型,例如:
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.
如果由于某种原因整个 Model 事情没有解决,您可以开始考虑创建自己的类和外观。或者您可以创建一个包含所有静态变量和方法的类,然后在没有外观的情况下使用它。
回答by Gagandeep Gambhir
For Constants
对于常量
Create constants.php file in the config directory:-
在 config 目录中创建 constants.php 文件:-
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:-
在 config 目录中创建 static_arrays.php 文件:-
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 :)
注意:Laravel 会自动包含所有配置文件,因此无需手动包含 :)
回答by Parth kharecha
Create common constants file in Laravel
在 Laravel 中创建通用常量文件
app/constants.php
应用程序/常量.php
define('YOUR_CONSTANT_VAR', 'VALUE');
//EX
define('COLOR_TWO', 'red');
composer.json add file location at autoload in composer.json
composer.json 在 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:
在此更改生效之前,您必须在终端中运行以下命令以重新生成 Laravel 的自动加载文件:
composer dump-autoload
回答by Mladen Janjetovic
For global constants in Laravel 5, I don't like calling Config for them. I define them in Route group like this:
对于 Laravel 5 中的全局常量,我不喜欢为它们调用 Config。我在 Route 组中这样定义它们:
// global contants for all requests
Route::group(['prefix' => ''], function() {
define('USER_ROLE_ADMIN','1');
define('USER_ROLE_ACCOUNT','2');
});
回答by Bill Stephen
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
创建一个新的文件messages.php
中resources/lang/en
(en
因为这是在我的设置config/app
'locale'=>'en'
)返回所有值的数组
return [
'welcome' => 'Welcome to our application'
];
to retrieve for laravel 5.3 and below
检索laravel 5.3及以下
echo trans('messages.welcome');
or
或者
echo Lang::get('messages.welcome');
for 5.4 use
5.4 使用
echo __('messages.welcome')
or
或者
回答by Jignesh Rawal
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
只是为了添加到上面的答案中,您必须先包含配置类,然后才能在 Laravel 5.3 中开始使用它
use Illuminate\Support\Facades\Config;
回答by blamb
Atleast in Laravel 5.4, in your constructor you can create them;
至少在 Laravel 5.4 中,您可以在构造函数中创建它们;
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
Laracasts.com 上的参考https://laracasts.com/discuss/channels/general-discussion/class-apphttpcontrollersconfig-not-found