laravel5 路由分割

       大家都知道,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);
    }
}

希望能帮到大家!!!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值