【发布时间】:2015-10-26 06:40:49
【问题描述】:
我有几个大型常量文件,使用我在 Laravel 4 中运行良好的 PHP define() 函数,但现在我正在将应用程序升级到 Laravel 5,我不确定如何最好地携带这些文件。
我有多个常量文件的原因是因为它们基于过去、现在和未来的年份(而且它们是包含许多常量的大文件)。以下是其中一个常量文件的示例:
<?php
//Check to see if the user is logged in.
// If no user, we can't know what catalog we should use
if (Auth::check()) {
//The most recent catalog year will serve as the default for anyone
//who signs up for a catalog year that is newer than the most recent
//catalog year.
if (Auth::user()->strg_4 == "2015 - 2016" ||
intval(substr(Auth::user()->strg_4, 0, 4)) > date("Y")) {
//Constants for Create course/Edit course pages
define('MY_CONSTANT', 'This is an example of a constant');
}
}
我已尝试执行以下操作:将以下代码块添加到我的 composer.json 文件:
"autoload": {
"classmap": [
"database",
"app/Http/Controllers",
"app/Models",
"app/myclasses"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/constants2013andearlier.php",
"app/constants20142015.php",
"app/constants20152016.php"
]
},
但是,这似乎不起作用,可能是因为我的常量文件中有 PHP 条件语句。
我还尝试将其放入我的所有视图的基本刀片文件中:
@include('constants.constants2013andearlier')
@include('constants.constants20142015')
@include('constants.constants20152016')
但是,这也不起作用,因为文件似乎没有被读取(我收到错误说“Course.php 第 752 行中的 ErrorException: 使用未定义的常量 MY_CONSTANT - 假定为“MY_CONSTANT””,其中 Course.php 是我的模型之一。
在我的旧 Laravel 4 版本的项目中,我使用以下代码在 global.php 文件中定义这些常量:
require app_path().'/constants2013andearlier.php';
require app_path().'/constants20142015.php';
require app_path().'/constants20152016.php';
有什么建议吗?谢谢。
【问题讨论】:
-
您定义的常量的真实示例是什么?这里肯定有一点代码味道
-
我举了一个常数的例子,因为我有很多相似的常数,重复更多相同的没有意义。它们都看起来像这样:define('MY_CONSTANT', 'This is an example of a constant');不用说,我的常量文件本身没有任何问题,因为它们在我的旧 Laravel 4 版本的应用程序中完美运行。
-
我更感兴趣的是你在常量中存储了什么样的值。如果它是简单的文本字符串,您可能会更好地使用 laravel 中的 Lang 构造
-
只有字符串、整数和小数存储为常量。
标签: php laravel laravel-5 blade laravel-5.1