【发布时间】:2015-12-29 00:15:12
【问题描述】:
一些上下文:我已经将我的 Laravel 5 应用程序设置为拆分为模块。我的 AppServiceProvider 中的 boot() 函数如下所示:
public function boot()
{
// We want to register the modules in the Modules folder
$modulesPath = app_path() . '/Modules';
$handle = opendir($modulesPath);
// Loop through the module directory and register each module
while (($module = readdir($handle)) !== false) {
if ($module != "." && $module != ".." && is_dir("{$modulesPath}/{$module}")) {
// Check if there are routes for that module, if so include
if (file_exists($modulesPath . '/' . $module . '/routes.php')) {
include $modulesPath . '/' . $module . '/routes.php';
}
// Check if there are views for that module, if so set a namespace for those views
if (is_dir($modulesPath . '/' . $module . '/Views')) {
$this->loadViewsFrom($modulesPath . '/' . $module . '/Views', strtolower($module));
}
}
}
}
这个想法是能够在模块中保持分离,但也有全局路由和全局控制器。因此,每个模块都有自己的 routes.php 文件,如下所示:
<?php
Route::group(array('module'=>'MyModule','namespace' => 'NexusHub\Modules\MyModule\Controllers'), function() {
Route::resource('mymodule', 'MyModuleController');
});
然后我有一个看起来像这样的全局 routes.php 文件:
<?php
Route::any('{catchall}', 'GlobalController@myAction')->where('catchall', '(.*)');
Route::group(array('module'=>'Global'), function() {
Route::resource('', 'GlobalController');
});
我遇到的问题是,我的包罗万象的路线似乎没有为模块选择。模块运行它们自己的路由,但包罗万象的路由被忽略。
至于我为什么要这样做,目前的目的是所有模块都使用相同的布局,并且该布局需要始终检索一些数据,因此全局控制器会抓取所需的内容并制作它可用于布局。但我想未来可能会有其他一些事情,拥有一个可以根据任意规则捕获多个不同路由并运行附加代码的全局路由文件会派上用场。
更新:删除了包含全局路由的行,因为我意识到它们已经默认包含在内。
【问题讨论】:
-
在包含模块路由后,您是否尝试过包含全局路由?
-
刚试过,没关系。我也意识到,我什至不需要那行,全局路由文件都会被加载,无论是 include app_path() 。 '/Http/routes.php';线实际上是不需要的。如果我删除它,全局路由仍然会包含在模块路由之后。
-
根据您的描述,如果您只是想向所有路由/视图注入一些数据,那么听起来视图作曲家是更合适的解决方案。
-
将查看作曲家。我在 Laravel 文档中看到了基本描述,但不确定我会在哪里声明这些以及如何将它们用于布局。我能够使用 MiddleWare 让事情正常工作,但不确定这是最好的解决方案。
标签: laravel