Last active
November 6, 2015 11:03
-
-
Save hmic/d09788322c86f3ec0fa9 to your computer and use it in GitHub Desktop.
Using beforeFilter Event with custom eventListener class
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Controller; | |
use App\Controller\AppController; | |
use App\Controller\MyEventListener; | |
class MyController extends AppController { | |
public function initialize() { | |
// this sets up the eventManager, loads Components and the like. | |
parent::initialize(); | |
$this->eventManager()->on(new MyEventListener($this->Auth)); | |
} | |
public function index() { | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Controller; | |
use Cake\Event\EventListenerInterface; | |
use Cake\Controller\Component\AuthComponent; | |
class MyEventListener implements EventListenerInterface { | |
private $auth = null; | |
public function __construct(AuthComponent $auth) { | |
$this->auth = $auth; | |
} | |
public function implementedEvents() { | |
return [ | |
// THIS SHOULD RATHER READ: | |
// 'Controller.beforeFilter' => 'beforeFilter', | |
'Controller.initialize' => 'beforeFilter', | |
]; | |
} | |
public function beforeFilter(\Cake\Event\Event $event) { | |
// you can use $this-auth now | |
debug([$this->auth, $event]); | |
throw new Exception(); | |
} | |
} |
Compare this implementation to
https://github.com/cakephp/cakephp/blob/master/src/Controller/Controller.php#L452-L460
You would think that the beforeFilter event is called "beforeFilter", NOT "initialize".
Especially as initialize is used in the same scope and even needed to setup the "beforeFilter" event at all!
This is very confusing!
I see.
The document not mention this one and i don't know Controller.beforeFilter event does not exists.
Thank you.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thank you bro.
I got your idea.