CakePHP 2.0 - beforeFilter () not starting on cakeErrorController?

I worked with CakePHP 1.3, but this is my first foray into CakePHP 2.0 and PHP exceptions, so bear with me if my question seems verbose.

In my AppController beforeFilter() I set a couple of variables via $this->set() for use in my view template.

In my UsersController , I have some code that looks something like this:

 public function beforeFilter() { parent::beforeFilter(); if (userDeniedAccess()) { throw new ForbiddenException(); } } 

where the hypothetical userDeniedAccess() function encapsulates my authorization checks.

It all works fine, and I get 403 error when I expect this. However, when an exception is thrown, the view variables that were set in AppController::beforeFilter() are no longer set, which leads to errors from my view template. When an exception is not thrown, the variables are set correctly.

I can code the missing variables if necessary, but I really would like to know what causes this behavior. Both my UsersController and CakeErrorController extend the AppController . Naturally, I expect that when an exception is thrown and an instance of CakeErrorController is created, it will generate the same view variables for me.

However, it seems that the Controller::startupProcess() method (which includes a call to beforeFilter() ) is never called on CakeErrorController . As far as I understand, this is done by the dispatcher for regular requests, but the life cycle of the error controller is different.

I saw descriptions ( like this one ) of similar behavior in CakePHP 1.3, but of course CakePHP error handling code was completely redesigned in 2.0.

So either:

  • This is a bug in CakePHP's default exception handling,
  • The behavior is as intended, and I just don’t understand it, or
  • I'm going crazy.

I know that you cannot help with case 3, but if either of the first two applies, I will be grateful for the contribution from someone who knows more than me.

Thanks!

EDIT: Setting view variables to beforeRender() really solves my problem. However, I am still wondering if it is intentional that beforeFilter() should never be called on CakeErrorController .

+8
exception-handling cakephp
source share
2 answers

Put the calls on $this->set() in the beforeRender() . That way, they will always be installed, even if you throw an exception.

I had the same problem with some custom layout variables, as in DebugKit my page was populated with undeclared variable warnings whenever there was any error. Using beforeRender() , fixed it instead.

+4
source share

you can overwrite CakeErrorController.php by copying it to App / Controller / and then add parent: beforeFilter () to the constructor.

+3
source share

All Articles