CakePHP从视图重定向到另一个URL

时间:2011-09-01 07:54:53

标签: php cakephp cakephp-1.3

我想从view.ctp重定向到其他视图。

假设像这样=>

if($val == 0 ) {
  redirec to 'posts/index'
}

我该怎么做?

1 个答案:

答案 0 :(得分:1)

您在控制器中进行重定向,而不是在视图中进行重定向。期。
您可以轻松地在控制器的视图中执行相同的检查。

我不知道你的具体情况,但我通常使用这种模式:

public function view($id) {
    $post = $this->Post->find('first', array(
        'conditions' => array('Post.id' => $id, 'Post.mark' => 1)
    ));
    if (!$post) {
        $this->cakeError('error404');
        // or redirect, or show a more specific error page, or do something else
    }

    $this->set(compact('post'));
}

这样,您需要执行的检查是在数据库级别处理的,如果它属于,并且重定向/错误在控制器中处理,如果它属于。在请求周期中查看业务逻辑的时间太迟了,比如“用户实际上是否允许看到这个?”,视图的工作只是输出信息。