大家都知道,laravel框架的路由放置在routes文件夹下的api.php文件中,当我们开发一个超大型项目时,那么api.php文件中的路由也会越来越多,在后期维护的时候相当不方便,那么怎么才能解决这个问题呢?
我们可以使用路由分割:
首先我们找到App\Providers\RouteServiceProvider.php文件:
然后,我们开始进行分割,添加以下代码:
/**
* admin 路由分割
*/
protected function mapAdminRoutes()
{
Route::prefix('admin')
->middleware('api')
->namespace($this->namespace)
->group(base_path('routes/admin.php'));
}
相信大家看到这个方法,以为就真正的能分组了吗?错,接下来还需要添加以下代码:
/**
* Define the routes for the application.
* 添加路由分组方法
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
$this->mapAdminRoutes();
}
当然,这种还不是最好的办法,因为当你的模块超多的时候怎么办?难道每一个文件都这么来?那就太麻烦啦!不妨试试下面的代码:
/**
* Define the routes for the application.
* 添加路由分组方法
* @return void
*/
public function map()
{
$this->mapApiRoutes();
$this->mapWebRoutes();
//
}
/**
* Define the "web" routes for the application.
*
* These routes all receive session state, CSRF protection, etc.
*
* @return void
*/
protected function mapWebRoutes()
{
Route::middleware('web')
->namespace($this->namespace)
->group(base_path('routes/web.php'));
}
/**
* Define the "api" routes for the application.
*
* These routes are typically stateless.
*
* @return void
*/
protected function mapApiRoutes()
{
/**
* 路由分割
*/
foreach(glob(base_path("routes/api/")."*.php")as $file){
Route::prefix('api')
->middleware('api')
->namespace($this->namespace)
->group($file);
}
}
希望能帮到大家!!!