CakePHP:全局重定向

时间:2013-05-11 23:41:05

标签: cakephp cakephp-2.0 cakephp-2.1

在应用程序的某些部分,用户可以通过更改URL来做一些不好的事情。例如,假设他们改变了编辑请求。

http://website.com/edit/4000

但是他们没有自己的帖子4000,他们可以通过URL操作获得的唯一方式就是。

在这些情况下,我想简单地将它们重定向到主页。但是,如果我触发其中一个捕获,我想向自己显示一条消息。 (所以这不仅仅是一个简单的重定向问题)

我把它放在引导程序中。

function security_redirect ($msg) {
    if ((not_an_admin) == 1) {
       $this->redirect(array('controller' => 'site', 'action' => 'index'));
    } else {
        die($msg);
    }
}

我收到错误消息:

Using $this when not in object context

当我表演时:

security_redirect("Tried to edit a post that isn't yours!");

我该怎么办?我究竟做错了什么?我不明白为什么它不被认为是在一个物体内...但也许它是显而易见的。

1 个答案:

答案 0 :(得分:4)

最好不要使用全局方法,但要在这些情况下抛出异常;阅读手册Built in Exceptions for CakePHP

的这一部分

例如;

class PostsController extends AppController {

    public function edit ($id)
    {
        if (user isn't allowed to edit this post) {
            throw new ForbiddenException('You are not allowed to edit this post');
        }
    }

}

这是比使用die()更好的方法,因为可以在单元测试中测试异常,它将由CakePHP错误处理程序处理,它将输出一个可以设置样式的错误页面

额外的例子

可以通过SessionComponent::setFlash()

在您的应用内设置反馈消息

要在控制器内执行重定向并输出消息,并让应用程序内的所有控制器都可以使用该功能(方法),请使用以下内容;

app / Controller / AppController.php

class AppController extends Controller
{    
    protected function security_redirect ($msg)
    {
        if ((not_an_admin) == 1) {
            // optionally, set 'flash' message
            $this->Session->setFlash($msg);
            return $this->redirect(array('controller' => 'site', 'action' => 'index'));
        } else {
            throw new ForbiddenException($msg);
        }
    }
}

在其他控制器中,您可以像这样访问此方法;

class PostsController extends AppController
{    
    public function edit ($id)
    {
        if (/* user isn't allowed to edit this post */) {
            return $this->security_redirect('You are not allowed to edit this post');
        }
    }    
}