问题
In my AppController, I define a variable that must be used in every views (including error400.ctp, error500.ctp) of my app:
// /src/Controller/AppController.php
public function beforeFilter(Event $event)
{
parent::beforeFilter($event);
$foo = 'bar';
$this->set(compact('foo'));
}
It works well, except when an exception is thrown (like NotFoundException): I get the following error:
Undefined variable: foo in /src/Template/Error/error400.ctp
Is this a normal behavior of cakephp? How could I fix this?
回答1:
Yes, this is normal behaviour, what is basically happening:
Exception is thrown (
beforeFilter
was called depending on where was it thrown, e.g. it is called for MissingAction or MissingTemplate, but not for MissingController).Request handling is aborted and
ErrorHandler
steps in to catch and handle that Exception.To render the Exception,
ErroHandler
usesExceptionRenderer
, which in turn creates specialErrorController
, that kind of replaces original controller. This also means, that now you have completely different controller handling the request (new instance of Controller class), so even ifbeforeFilter
was called and$foo
was set, it is not longer valid.ExceptionRenderer
will use its ownrender()
method to create output for error page.
To customize this, you can extend that default ExceptionRenderer
, so you will be able to set variables to ErrorController
<?php
// goes in src/Error/AppExceptionRenderer
namespace App\Error;
use Cake\Error\ExceptionRenderer;
class AppExceptionRenderer extends ExceptionRenderer
{
public function render()
{
$this->controller->set('foo', 'bar');
return parent::render();
}
}
Set this class as default ExceptionRenderer in app.php
//...
'Error' => [
// ...
'exceptionRenderer' => 'App\Error\AppExceptionRenderer',
// ...
],
So you need to set that global view variable in two places. Use some common method from models, Configure
class to read global variables or whatever is suitable for your requirements.
More on custom error handling: Extending and Implementing your own Exception Handlers
来源:https://stackoverflow.com/questions/30315153/cakephp-3-var-not-transmitted-to-view-when-exception-thrown