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);
});