欢迎光临
我们一直在努力

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’)

赞(0)
版权归原作者所有,如有侵权请告知。达维营-前端网 » laravel Route::controller 使用路由命名

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址