Skip to content

Instantly share code, notes, and snippets.

@hmic
Last active November 6, 2015 11:03
Show Gist options
  • Save hmic/d09788322c86f3ec0fa9 to your computer and use it in GitHub Desktop.
Save hmic/d09788322c86f3ec0fa9 to your computer and use it in GitHub Desktop.
Using beforeFilter Event with custom eventListener class
<?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() {
}
}
<?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();
}
}
@anhtuank7c
Copy link

Thank you bro.
I got your idea.

@hmic
Copy link
Author

hmic commented Nov 6, 2015

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!

@anhtuank7c
Copy link

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