laravel框架中使用命名空間和路由可以簡單的實現模塊化開發;
如下,添加一個後臺模塊Backend,使用routes_backend.php,
1、首先在路由服務中綁定對應的命名空間:
Providers\RouteServiceProvider
namespace App\Providers;
use Illuminate\Routing\Router;
use Illuminate\Foundation\Support\Providers\RouteServiceProvider as ServiceProvider;
class RouteServiceProvider extends ServiceProvider
{
/**
* This namespace is applied to the controller routes in your routes file.
*
* In addition, it is set as the URL generator's root namespace.
*
* @var string
*/
protected $namespace = 'App\Http\Controllers';
//後臺命名空間定義
protected $backendNamespace = 'App\Http\Controllers\Backend';
/**
* Define your route model bindings, pattern filters, etc.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function boot(Router $router)
{
parent::boot($router);
}
/**
* Define the routes for the application.
*
* @param \Illuminate\Routing\Router $router
* @return void
*/
public function map(Router $router)
{
$router->group(['namespace' => $this->namespace], function ($router) {
require app_path('Http/routes.php');
});
//後臺路由綁定
$router->group(['namespace' => $this->backendNamespace], function ($router) {
require app_path('Http/routes_backend.php');
});
}
}
2、新建路由文件 routes_backend.php
<?php
/*
|--------------------------------------------------------------------------
| Application Routes
|--------------------------------------------------------------------------
|
| Here is where you can register all of the routes for an application.
| It's a breeze. Simply tell Laravel the URIs it should respond to
| and give it the controller to call when that URI is requested.
|
*/
Route::get('/admin','IndexController@index')->name('admin');
3、建立 App\Http\Controllers\Backend 目錄,在其中寫後臺的相關控制器如:
至此就可以分離訪問了