在 Laravel 中定义常量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26062715/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 10:11:11  来源:igfitidea点击:

Defining constants in laravel

laravelconstants

提问by Marfat

In laravel, there is no constant file defined, so I went on and searched for a way to implement the use of constants. The method below is what I managed to put together:

在laravel中,并没有定义常量文件,于是继续寻找实现常量使用的方法。下面的方法是我设法组合在一起的:

// app/config/constants.php
return['CONSTANT_NAME' => 'value'];

// index.blade.php
{{ Config::get('constants.CONSTANT_NAME') }}

Now, my question is; is there a cleaner way of retrieving my constants in my view? Something like:

现在,我的问题是;在我看来,有没有一种更简洁的方法来检索我的常量?就像是:

{{ Constant::get('CONSTANT_NAME') }}

This is in order to keep my view nice, short and clean.

这是为了保持我的观点好看、简短和干净。

Appreciate the input!

欣赏输入!

采纳答案by msturdy

One thing you can do is to share pieces of data acrossyour views:

您可以做的一件事是您的视图中共享数据片段

View::share('my_constant', Config::get('constants.CONSTANT_NAME'));

Put that at the top of your routes.phpand the constant will then be accessible in all your blade views as:

把它放在你的顶部,routes.php然后在你的所有刀片视图中都可以访问常量,如下所示:

{{ $my_constant }}

回答by ceejayoz

The Configclass is intended to replace the need for constants and serves the same role.

Config班旨在替换为常数的需求,并提供相同的作用。

Have app/config/constants.phpreturn an array of key/value pairs, then just use Config::get('constants.key')to access them.

app/config/constants.php返回一组键/值对,然后仅用于Config::get('constants.key')访问它们。

You could conceivably create a Constantclass that has a getfunction as a shortcut:

您可以想象创建一个Constant具有get快捷方式功能的类:

class Constant {
  public function get($key) {
    return Config::get('constants.' . $key);
  }
}

but using the standard Laravel handling is likely to be nicer to other Laravel developers trying to familiarize themselves with your code.

但是使用标准的 Laravel 处理对于试图熟悉您的代码的其他 Laravel 开发人员来说可能会更好。

回答by Joshua Fricke

In v5 you can do like @msturdy suggests except you store the constant in the .env file or in production as actual $_ENVIRONMENT variables on your server for your environment.

在 v5 中,您可以像 @msturdy 建议的那样做,除非您将常量存储在 .env 文件中或在生产中作为实际 $_ENVIRONMENT 变量存储在您的服务器上以用于您的环境。

Example .env entry:

示例 .env 条目:

CONSTANT=value

Then call like so:

然后像这样调用:

View::share('bladeConstant', env('CONSTANT'));

Then load it with:

然后加载它:

{{ bladeConstant }}