2017-01-12 70 views
0

我正在使用Laravel 5.3。我有一堆我想用一条路线处理多个控制器的网址。Laravel 5.3动态路由到多个控制器

例如

GET /admin/foo => [email protected] 
GET /admin/foo/edit/1 => [email protected]($id) 
GET /admin/bar => [email protected] 
GET /admin/bar/edit/1 => [email protected]($id) 
GET /admin/baz => [email protected] 
GET /admin/baz/edit/1 => [email protected]($id) 
etc. 

我希望能够检测如果控制器存在,如果不是抛出一个404或路由到一个默认的控制器(这可能抛出404)。

以下是我到目前为止,但我不知道我在做什么。我不应该使用服务容器实例化控制器吗?我认为我不应该像这样硬编码命名空间。而我对id参数的处理是粗略的。也许我应该为这两种模式有两条路线呢?

Route::get('/admin/{entityType}/{action?}/{id?}', function ($entityType, $action = 'index', $id = null) { 

    $controllerClass = 'App\Http\Controllers\\' . ucfirst($entityType) . 'Controller'; 
    $controller = new $controllerClass; 

    $route = app(\Illuminate\Routing\Route::class); 
    $container = app(\Illuminate\Container\Container::class); 
    return (new Illuminate\Routing\ControllerDispatcher($container))->dispatch($route, $controller, $action); 

    abort(404); 
}); 

回答

0

我建议你明确地为每个控制器定义一个路由。这是构建可维护应用程序的最佳方式。

此外,如果使用一个路线,一种方法是一个选项(右木构建筑,它是)使用一个路线:

Route::get('/admin/{entityType}/{action?}/{id?}', '[email protected]'); 

而且一个切入点:

public function method($entity, $action = null, $id = null) 
{ 
    // Handle request here. 

https://laravel.com/docs/5.3/routing#parameters-optional-parameters