laravel Route::controller 使用路由命名

我们知道,在 laravel 中使用 resource 的话,只需要绑定模型,在创建表单,链接时,直接可以拿来用,不需要单独的去给路由 as 别名


Route::resource('main','MainController'); // 创建链接 URL::route('main.index')

但是我们使用 Route::controller 时,在创建链接,尝试用以上方法访问时,就会报错


Route::controller('main','MainController'); // 创建链接 URL::route('main.index') // 抛出路由不存在的错误

那我们如何像使用 resource 一样方便的来使用 controller 呢?

很简单,我们打开 controller 的源码一看就知道了


// 源码路径:vendor/laravel/framework/src/Illuminate/Routing/Router.php :257 行 看到如下方法 /** * Route a controller to a URI with wildcard routing. * * @param string $uri * @param string $controller * @param array $names * @return void */ public function controller($uri, $controller, $names = array()) { $prepended = $controller; // First, we will check to see if a controller prefix has been registered in // the route group. If it has, we will need to prefix it before trying to // reflect into the class instance and pull out the method for routing. if ( ! empty($this->groupStack)) { $prepended = $this->prependGroupUses($controller); } $routable = $this->getInspector()->getRoutable($prepended, $uri); // When a controller is routed using this method, we use Reflection to parse // out all of the routable methods for the controller, then register each // route explicitly for the developers, so reverse routing is possible. foreach ($routable as $method => $routes) { foreach ($routes as $route) { $this->registerInspected($route, $controller, $method, $names); } } $this->addFallthroughRoute($controller, $uri); } // 我们看到可以传递第三个参数,是一个数组,那么数组的内容是什么呢?此方法里面没有处理 name,我们注意看这一行 $this->registerInspected($route, $controller, $method, $names); //好了,我们找到 registerInspected 这个方法,看他如何处理 name protected function registerInspected($route, $controller, $method, &$names) { $action = array('uses' => $controller.'@'.$method); // If a given controller method has been named, we will assign the name to the // controller action array, which provides for a short-cut to method naming // so you don't have to define an individual route for these controllers. $action['as'] = array_get($names, $method); $this->{$route['verb']}($route['uri'], $action); }

我们看到他以 . 去切割了 name ,然后加入了进去,这样我们就清楚很多啦

路由这样写

Route::controller(
    'options',
    'OptionsController',
    [
        'getSite'=>'options.site'
    ]
);

// 现在就可以使用创建链接啦

URL::route('options.site')

这些东西找了下 laravel 文档没找着,所以自己直接看的源码

本文发布源在:laravel Route::controller 使用路由命名
欢迎大家加入 laravel 交流群一起讨论:365969825

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值