Skip to content

Instantly share code, notes, and snippets.

@hmic
Created August 31, 2017 09:28
Show Gist options
  • Save hmic/84452fc5752aae8f74ff7b5dfea50d57 to your computer and use it in GitHub Desktop.
Save hmic/84452fc5752aae8f74ff7b5dfea50d57 to your computer and use it in GitHub Desktop.
Events and Inheritance in cakephp3
<?php
namespace App\Controller;
class AppController extends \Cake\Controller\Controller
{
public function initialize()
{
parent::initialize();
/*
* Can't listen on the "initialize" event here obviously, "startup" and all later ones do work though.
* If "initialize" is needed, overwrite the constructor and attach the the global EventManager class instead.
* Make sure to use a unique function name, as a generic _beforeRender would likely be overwritten by
* a subclasses implementation without beeing, further on, easyly, noticeable...
*/
$this->eventManager()->on('beforeRender', [$this, '_globalBeforeRender']);
}
public function _globalBeforeRender(\Cake\Event\Event $event)
{
$this->set('global', true);
}
}
<?php
namespace App\Controller;
class AppController extends \Cake\Controller\Controller
{
public function _globalBeforeRender(\Cake\Event\Event $event)
{
$this->set('global', true);
}
public function implementedEvents()
{
return parent::implementedEvents() + ['beforeRender' => '_globalBeforeRender'];
}
}
<?php
debug([$global, $users]);
/*
* [
* null,
* true
* ]
*
* I want both to run, like:
* [
* true,
* true
* ]
*
* Clearly the UsersController::implementedEvents overwrites the beforeRender key from the parent class...
* The desired result can be achieved by adding parent::_globalBeforeRender($event); to line 10 of UsersController.php
* which would need insights into what events are bound where, which i not desireable, how to do it correctly?
* Use the EventManager directly to add another event? - Maybe rather in the AppController though,
* not to confuse others using the App?
*/
<?php
namespace App\Controller;
class UsersController extends AppController
{
public function testEvents() {
}
public function _beforeRender(\Cake\Event\Event $event) {
$this->set('users', true);
}
public function implementedEvents()
{
return parent::implementedEvents() + ['beforeRender' => '_beforeRender'];
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment