我有几个常量的大型文件使用我在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行中遇到错误说&#34; ErrorException: 使用未定义的常量MY_CONSTANT - 假设&#39; MY_CONSTANT&#39;&#34;其中Course.php是我的模特之一。
在我的旧版Laravel 4版本中,我使用以下代码在global.php文件中定义了这些常量:
require app_path().'/constants2013andearlier.php';
require app_path().'/constants20142015.php';
require app_path().'/constants20152016.php';
有什么建议吗?谢谢。
答案 0 :(得分:1)
我仍然有兴趣听到我在下面发现的解决方案的任何其他想法或潜在问题:
我将我的所有常量文件放在app目录中的一个文件夹(名为“constants”)中。
在命令行中,我运行了:php artisan make:middleware AddConstantsFilesToAllRoutes
在AddConstantsFilesToAllRoutes文件中,我添加了所有这些常量文件,如下所示:
require_once app_path('constants')。 '/constants2013andearlier.php'; require_once app_path('constants')。 '/constants20142015.php'; require_once app_path('constants')。 '/constants20152016.php';
在Kernal.php中,我将上面的新中间件文件添加到$protected middleware = []
数组中,并将其添加到所有可能的路径中:
\应用\ HTTP \中间件\ AddConstantsFilesToAllRoutes ::类,
小心 NOT 将上述代码添加到protected $routeMiddleware = []
数组中,否则不会将常量文件添加到所有路由中。
当然,如果您只想将常量文件添加到选择性路径中,那么这将是一个很好的解决方案;但是,您需要手动将这些路由添加到每个控制器的构造函数中,您希望这些路径可以访问这些常量文件。
此外,请确保所有控制器都从BaseController扩展,以便中间件在该控制器的路由上运行。