Laravel在自定义路由文件上路由缓存

Dee*_*ens 4 php caching laravel laravel-routing laravel-5

我正在Laravel 5.2中建立一个项目,它有一个很大的(很多行很大)routes.php.为了使眼睛的路线更清洁,我将所有路线组分开介绍分开的文件.在app\Http\Routes\.

我要求所有文件中的所有文件RouteServiceProvider(更正:工作..)对我来说完全没问题.毕竟,我想用缓存路由php artisan route:cache.然后,如果你去了一个页面,你得到的是404错误.

"漫长"的故事简短:新的路线逻辑在工匠路线缓存后崩溃.

这是我的地图功能RouteServiceProvider(灵感来自这个答案):

public function map(Router $router)
{
    $router->group(['namespace' => $this->namespace], function ($router) {
        // Dynamically include all files in the routes directory
        foreach (new \DirectoryIterator(app_path('Http/Routes')) as $file)
        {
            if (!$file->isDot() && !$file->isDir() && $file->getFilename() != '.gitignore')
            {
                require_once app_path('Http/Routes').DS.$file->getFilename();
            }
        }
    });
}
Run Code Online (Sandbox Code Playgroud)

有人知道问题是什么吗?或者,如果我想使用路由缓存,我只需要将所有内容放回routes.php中.提前致谢.

小智 6

TL; DR:使用require而不是require_once,你应该没问题.

所以,对于初学者,让我们来看看Illuminate\Foundation\Console\RouteCacheCommand.
您会注意到它使用了getFreshApplicationRoutes引导应用程序并从路由器获取路由的方法.

我已经使用这段代码来创建一个命令来执行路由计数:

$app = require $this->laravel->bootstrapPath().'/app.php';

$app->make('Illuminate\Contracts\Console\Kernel')->bootstrap();

$routesCnt = $app['router']->getRoutes()->count();

$this->info($routesCnt);
Run Code Online (Sandbox Code Playgroud)

这使我们可以更多地了解提取的路线数量.

使用您的代码,无论我在Http\Routes文件夹中添加了多少文件,都没有注册.所以我决定尝试使用"require"而不是"require_once".瞧!

路线数量适当增加.

至于为什么会发生这种情况,我猜这是因为作曲家自动加载(这只是一个有根据的猜测).看看composer.json:

    "psr-4": {
        "App\\": "app/"
    }
Run Code Online (Sandbox Code Playgroud)

这意味着app /文件夹中的文件是自动加载的.这意味着这些文件已经加载,只是没有你想要的文件.这意味着如果您使用*_once包含函数,它们将不会再次加载.

代码RouteServiceProvider.php,map对我有用的方法是:

$router->group(['namespace' => $this->namespace], function ($router) {
        // Dynamically include all files in the routes directory
        foreach (new \DirectoryIterator(app_path('Http/Routes')) as $file)
        {
            $path = app_path('Http/Routes').DIRECTORY_SEPARATOR.$file->getFilename();
            if ($file->isDot() || $file->isDir() || $file->getFilename() == '.gitignore')
                continue;

            require $path;
            $included[] = $path;
        }
    });
Run Code Online (Sandbox Code Playgroud)