建议路由器加个反射路由取得 url 的功能
visamz opened this issue · comments
胖虎 commented
现在的路由必须是这样配置的:
return array(
'/' => 'Quotation\Action\Index',
'/s' => 'Quotation\Action\Search',
'/brand' => 'Quotation\Action\Brand',
'/brand/:cateId' => 'Quotation\Action\Brand',
'/car' => 'Quotation\Action\Car',
'/car/:quoId' => 'Quotation\Action\Car'
);
但是无法通过路由反射成获取 url,感觉不便。
比如可以这样,对路由取个别名:
return array(
'index' => array('/' => 'Quotation\Action\Index'),
'search' => array('/s' => 'Quotation\Action\Search'),
'brands' => array('/brands' => 'Quotation\Action\Brands'),
'brand' => array('/brand/:cateId' => 'Quotation\Action\Brand'),
'cars' => array('/cars/:cateId' => 'Quotation\Action\Cars'),
'car' => array('/car/:quoId' => 'Quotation\Action\Car')
);
胖虎 commented
挖掘到一个功能,发现路由可以介样写:
return array(
'/' => array(
'action' => 'Quotation\Action\Index',
'params' => array('routeName' => 'index')
),
'/s' => array(
'action' => 'Quotation\Action\Search',
'params' => array('routeName' => 'search')
),
'/brands' => array(
'action' => 'Quotation\Action\Brands',
'params' => array('routeName' => 'brands')
)
);
然后,利用 params 这个参数,就可以根据 routeName 获取对应的 url:
/**
* toUrl
* @return mixed
*/
public static function toUrl()
{
if (!self::$format) {
$routes = self::get('routes', ''); // 先取得路由配置,这个是我自己写的方法。
foreach ($routes as $k => $v) {
self::$format[$v['params']['routeName']] = asset(preg_replace('/:([_a-z]+)/i', '%s', $k));//asset 也是我自己的方法,用来组建 url
}
}
$args = func_get_args();
if (count($args) > 0) {
$name = $args[0];
$args = array_slice($args, 1);
return vsprintf(self::$format[$name], $args);
}
return self::$format;
}
胖虎 commented
当然了,除此之外,你的action里相应也可以利用 params参数。
在你指定了 params 后,比如 'params' => array('routeName' => 'index')
,
action 里也会自动搜索是否存在 setRourteName
这个方法,如果存在,将自动执行。
执行顺序如下:init()
,你定义的 setRourteName
方法,最后是execute()
。
最后,还有一个好玩,除了定义'params'
外,还有一个参数可选,那就是拦截器,interceptors
,慢慢折腾吧...