【问题标题】:Kohana 3.2 - Routing questionsKohana 3.2 - 路由问题
【发布时间】:2012-05-13 10:52:56
【问题描述】:

首先,Kohana 的文档很糟糕,在人们去“阅读文档”之前,我已经阅读了文档,它们似乎没有多大意义,即使复制和粘贴一些代码也不适用于某些东西文档。

考虑到这一点,我有这样一条路线:

//(enables the user to view the  profile / photos / blog, default is profile)
Route::set('profile', '<userid>(/<action>)(/)', array( // (/) for trailing slash
    "userid" => "[a-zA-Z0-9_]+",
    "action" => "(photos|blog)"
))->defaults(array(
    'controller' => 'profile',
    'action' => 'view'
))

这使我可以转到http://example.com/username 并被带到用户个人资料,http://example.com/username/photos 被带到查看用户照片,http://example.com/username/blog 被带到查看博客。

如果有人去http://example.com/username/something_else,我希望它默认为&lt;userid&gt; 中指定的用户的操作view,但我似乎找不到任何方法。

我可以这样做:

Route::set('profile', '<userid>(/<useraction>)(/)', array(
    "userid" => "[a-zA-Z0-9_]+",
    "useraction" => "(photos|blog)"
))->defaults(array(
    'controller' => 'profile',
    'action' => 'index'
))

然后在控制器中执行以下操作:

public function action_index(){
    $method = $this->request->param('useraction');
    if ($method && method_exists($this, "action_{$method}")) {
        $this->{"action_{$method}"}();
    } else if ($method) {
    // redirect to remove erroneous method from url
    } else {
        $this->action_view(); // view profile
    }
}

(在__construct() 函数中可能会更好,但你明白了它的要点。)

如果有更好的方法可用(确实应该有),我宁愿不这样做

我认为答案可能在正则表达式中,但以下不起作用:

$profile_functions = "blog|images";
//(enables the user to view the images / blog)
Route::set('profile', '<id>/<action>(/)', array( 
            "id" => "[a-zA-Z0-9_]+",
            "action" => "($profile_functions)",
))->defaults(array(
    'controller' => 'profile'
));
Route::set('profile_2', '<id>(<useraction>)', array(
            "id" => "[a-zA-Z0-9_]+",
            "useraction" => "(?!({$profile_functions}))",
))->defaults(array(
    'controller' => 'profile',
    'action'     => 'view'
));

虽然当 ID 后面没有任何内容时它确实匹配。

【问题讨论】:

    标签: php regex routes kohana kohana-3


    【解决方案1】:

    我会这样设置路线:

    Route::set('profile', '<userid>(/<action>)(/)', array(
        "userid" => "[a-zA-Z0-9_]+",
        "action" => "[a-zA-Z]+"
    ))->defaults(array(
        'controller' => 'profile',
        'action' => 'index'
    ))
    

    然后在控制器的 before() 方法中:

    if(!in_array($this->request->_action, array('photos', 'blog', 'index')){
        $this->request->_action = 'view';
    }
    

    或类似的东西,只需验证控制器中的操作...

    编辑:

    这也可以:

    if(!is_callable(array($this, 'action_' . $this->request->_action))){
        $this->request->_action = 'view';
    }
    

    【讨论】:

    • 对不起,我不明白。返回什么?
    • 而不是使用数组,但忽略我...in_array("action_{$request-&gt;_action}", get_class_methods($this))
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多