如何在Kohana中的控制器名称之间添加短划线?

时间:2011-06-04 19:13:26

标签: routing routes kohana kohana-3 hyphen

我正在为Kohana 3.1开发授权模块。在我的模块的 init.php ...

Route::set(

    'a11n',
    '<controller>',
    array(
        'controller' => 'signIn|signOut|signUp'
    )

);

我不是100%肯定如何使用Kohana的路由机制,但是我试图实现用户可以键入“signIn”,“signOut”或“signUp”来运行我的模块中的控制器。你看,我想拥有“便携式”授权系统......所以我可以简单地“复制粘贴”正确的目录,启用模块,我的网站也有授权。

请记住,使用此路由我不想以任何方式更改默认路由的行为。我不知道我的代码是多么正确......但是它有效!我测试了,我也可以在不使用第三个参数的情况下获得相同的效果。我现在用它做到了什么?

现在的问题是......如何通过输入“登录”用户运行模块“Controller_SignIn”以某种方式从模块设置路由?

3 个答案:

答案 0 :(得分:4)

你应该使用路线来做到这一点,如下所示:

Route::set('SignIn', '/sign-in(/<action>)',
        array(
            'action' => 'index|action1',
            )
        )
        ->defaults(
                array(
                    'controller' => 'SignIn',
                    'action' => 'index',
                    )
                );

Route::set('SignOut', '/sign-out(/<action>)',
        array(
            'action' => 'index|action1',
            )
        )->defaults(
                array(
                    'controller' => 'SignOut',
                    'action' => 'index',
                    )
                );

Route::set('SignIn', '/sign-in/',
        array()
        )
        ->defaults(
                array(
                    'controller' => 'user',
                    'action' => 'login',
                    )
                );

Route::set('SignOut', '/sign-out/)',
        array()
        )->defaults(
                array(
                    'controller' => 'user',
                    'action' => 'logout',
                    )
                );

答案 1 :(得分:3)

我知道这个问题已经有一个标记为解决方案的答案,但有更清洁/另一种方式:

在您的应用程序中创建一个新文件:application/classes/request.php并将以下代码放在该文件中:

<?php defined('SYSPATH') or die('No direct script access.');
class Request extends Kohana_Request
{
    public function execute()
    {
        $this->action(str_replace('-', '', $this->action()));
        $this->controller(str_replace('-', '', $this->controller()));
        return parent::execute();
    }
}

现在您不必为每个虚线/带连字符的网址修改/污染您的bootstrap.php!

答案 2 :(得分:1)

为什么要为帐户操作创建独立的控制器?使用您需要的操作创建一个控制器(Controller_Account或其他):

class Controller_Account extends Controller_Template {

    public function action_signin() {...}

    public function action_signout() {...}

    public function action_signup() {...}

}

如您所见,动作名称没有破折号。你不能在方法名称中使用它们。但这是一个黑客攻击:

public function before()
{
    parent::before(); // dont forget this call!
    // remove dashes from current method name
    $this->request->action(str_replace('-', '', $this->request->action()));
}

路线:

Route::set(
       'a11n', 
       '<action>', 
       array('action' => array('sign-in|sign-up|sign-out'))
    )
    ->defaults(array('controller' => 'account'));

当然,您可以使用登录名和登录名,只需在路由正则表达式参数中添加非虚线名称:

Route::set(
       'a11n', 
       '<action>', 
       array('action' => array('sign-in|sign-up|sign-out|signin|signup|signout'))
    )
    ->defaults(array('controller' => 'account'));