cakephp - 如何在Component中重定向

Jcb*_*cbo 1 components cakephp

我创建了一个组件,在这个组件中我尝试重定向到不同的控制器/操作,但是我收到错误:" Error: Call to undefined method SessionRestComponent::redirect()"

我的组件代码:

function iniciaSessao($username=''){
                 $_SESSION['username'] = $username;
                                //  debug(isset($_SESSION['username']));
                                if (isset($_SESSION['username'])) {
                                    $this->redirect(array('controller' => 'registos', 'action' => 'indexUser'));
                                }
            }
Run Code Online (Sandbox Code Playgroud)

有人可以帮帮我吗?

mar*_*ark 7

您需要获取控制器 - 例如在initialize()或startup()中然后使用此控制器重定向.

public function startup(Controller $controller) {
    $this->Controller = $controller;
}

public function iniciaSessao() {
    ...
    $this->Controller->redirect($url);
}
Run Code Online (Sandbox Code Playgroud)

并且不要直接使用$ _SESSION,使用$ this-> Session组件,如文档所示.您只需将组件添加到自定义组件:

public $components = array('Session');
Run Code Online (Sandbox Code Playgroud)