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 目录,在其中写后台的相关控制器如:
至此就可以分离访问了