Cannot attach EVENT_ROUTE in Controller - php

I do not understand why the following code does not work. Perhaps I do not understand something with the EventManger/SharedEventManager ind Zend Framework 2.
For now I could not find anything about this on the internet.
Could it be that the instance of the IndexContoller is already destroyed at EVENT_RENDER and not constructed at EVENT_ROUTE? Perhaps this is the case or am I missing something here?
class IndexController extends AbstractActionController
{
public function routeEventOccured() {
echo 'test';
}
public function renderEventOccured() {
echo 'test';
}
public function __construct()
{
$this->getEventManager()->attach(MvcEvent::EVENT_ROUTE, array($this,
'routeEventOccured'));
$this->getEventManager()->attach(MvcEvent::EVENT_RENDER, array($this,
'renderEventOccured'));
}
}

Zend Framework 2 uses the concept of event. One class can trigger an event,
and other classes may listen to events. Technically, triggering an event means just calling another class' "callback" method. The event management is implemented inside of
the Zend\Mvc\EventManager component.
The application's "life" consists of several stages. Each application life stage is initiated by the application by triggering an event. Other classes (either belonging to Zend Framework or specific to your application) may listen
to events and react accordingly.
Below, the four main events (life stages) are presented:
Bootstrap. When this event is triggered by the application, a module has a chance to
register itself as a listener of further application events in its onBootstrap()
callback method.
Route. When this event is triggered, the request's URL is analyzed using a router class (typically, with
Zend\Mvc\Router\Http\TreeRouteStack class. If an exact match between the URL and a route
is found, the request is passed to the site-specific controller class assigned to the route.
Dispatch. The controller class "dispatches" the request using the corresponding action method
and produces the data that can be displayed on the web page.
Render. On this event, the data produced by the controller's action method are passed for rendering to
Zend\View\Renderer\PhpRenderer class. The renderer class uses a
view template file for producing an HTML page.

Related

Phalcon fire event from controller

I am using the Phalcon micro application as my REST web service. I want to add an event to the application and fire this event from different places like controllers.
For example; if a user registers, the controller should fire a userRegistered event, and userRegistered should do some stuff.
How can I implement this?
interface IUsers
{
function onUserRegistered();
}
Event class
class UsersActivities implements IUsers
{
function onUserRegistered()
{
// TODO: Implement onUserRegistered() method.
}
}
Just check docs. It's pretty simple, create manager, creat listener(UsersActivities in your case i guess) and fire events in manager.
https://docs.phalconphp.com/pl/latest/reference/events.html

ZF2: How to attach module specific listener for dispatch.error

Is there a way I can attach an event listener for the event dispatch.error in Zend Framework 2, where that listener will only be attached to an EventManager related to the Module.php?
I have achieved this by attaching listener for dispatch to the global SharedManager and passing the current Module.php's namespace as first param. It works beautifully, but does NOT work, when I try the same for dispatch.error.
Here's an example in Module.php:
public function init(ModuleManager $moduleManager)
{
$sharedManager = $moduleManager->getEventManager()->getSharedManager();
$sharedManager->attach(__NAMESPACE__, 'dispatch', function($e) {
exit('IT WORKS');
});
$sharedManager->attach(__NAMESPACE__, 'dispatch.error', function($e) {
exit('IT DOES NOT WORK');
});
}
The reason it is working for dispatch but not dispatch.error is that the dispatch event gets triggered from within in the controller (see Zend\Mvc\Controller\AbstractController::dispatch)
Because you extend this class with your own namespaced controller, it is possible to associate the event with that namespace.
However, the dispatch.error event may be triggered before a controller (and with it the context of your namespace) is ever loaded. This happens according to more than one condition in Zend\Mvc\DispatchListener.
In order to customize the way dispatch.error is handled, you will likely need to write a custom listener for that event, or even write your own DispatchListener (though I'd recommend against that). You can then perhaps look at the routeMatch to figure out what you'd like to do next. If you're using the ModuleRouteListener this could be pretty easy.

Where to register event listeners

I'm trying to use the Event System in CakePHP v2.1+
It appears to be quite powerful, but the documentation is somewhat vague. Triggering the event seems pretty straight-forward, but I'm not sure how to register the corresponding listener(s) to listen for the event. The relevant section is here and it offers the following example code:
App::uses('CakeEventListener', 'Event');
class UserStatistic implements CakeEventListener {
public function implementedEvents() {
return array(
'Model.Order.afterPlace' => 'updateBuyStatistic',
);
}
public function updateBuyStatistic($event) {
// Code to update statistics
}
}
// Attach the UserStatistic object to the Order's event manager
$statistics = new UserStatistic();
$this->Order->getEventManager()->attach($statistics);
But it does not say where this code should reside. Inside a specific controller? Inside the app controller?
In case it's relevant, the listener will be part of a plugin which I am writing.
Update:
It sounds like a popular way to do this is by placing the listener registration code in the plugin's bootstrap.php file. However, I can't figure out how to call getEventManager() from there because the app's controller classes, etc aren't available.
Update 2:
I'm also told that listeners can live inside Models.
Update 3:
Finally some traction! The following code will successfully log an event when inside of my MyPlugin/Config/bootstrap.php
App::uses('CakeEventManager', 'Event');
App::uses('CakeEventListener', 'Event');
class LegacyWsatListener implements CakeEventListener {
public function implementedEvents() {
return array(
'Controller.Attempt.complete' => 'handleLegacyWsat',
);
}
public static function handleLegacyWsat($event) { //method must be static if used by global EventManager
// Code to update statistics
error_log('event from bootstrap');
}
}
CakeEventManager::instance()->attach(array('LegacyWsatListener', 'handleLegacyWsat'), 'Controller.Attempt.complete');
I'm not sure why, but I can't get errors when I try to combine the two App::uses() into a single line.
Events
Events are callbacks that are associated to a string. An object, like a Model will trigger an event using a string even if nothing is listening for that event.
CakePHP comes pre-built with internal events for things like Models. You can attach an event listener to a Model and respond to a Model.beforeSave event.
The EventManager
Every Model in Cake has it's own EventManager, plus there is a gobal singleton EventManager. These are not all the same instance of EventManager, and they work slightly differently.
When a Model fires an event it does so using the EventManager reference it has. This means, you can attach an event listener to a specific Model. The advantages are that your listener will only receive events from that Model.
Global listeners are ones attached to the singleton instance of EventManager. Which can be accessed anywhere in your code. When you attach a listener there it's called for every event that happens no matter who triggers it.
When you attach event listener in the bootstrap.php of an app or plugin, then you can use the global manager, else you have to get a reference to the Model you need using ClassRegistry.
What EventManager To Use?
If the event you want to handle is for a specific Model, then attach the listener to that Model's EventManager. To get a reference of the model you can call the ClassRegistry::init(...).
If the event you want to handle could be triggered anywhere, then attach the listener to the global EventManager.
Only you know how your listener should be used.
Inside A Listener
Generally, you put your business logic into models. You shouldn't need to access a Controller from an event listener. Model's are much easier to access and use in Cake.
Here is a template for creating a CakeEventListener. The listener is responsible for monitoring when something happens, and then passing that information along to another Model. You should place your business logic for processing the event in Models.
<?php
App::uses('CakeEventListener', 'Event');
class MyListener implements CakeEventListener
{
/**
*
* #var Document The model.
*/
protected $Document;
/**
* Constructor
*/
public function __construct()
{
// get a reference to a Model that we'll use
$this->Document = ClassRegistry::init('Agg.Document');
}
/**
* Register the handlers.
*
* #see CakeEventListener::implementedEvents()
*/
public function implementedEvents()
{
return array(
'Model.User.afterSave'=>'UserChanged'
);
}
/**
* Use the Event to dispatch the work to a Model.
*
* #param CakeEvent $event
* The event object and data.
*/
public function UserChanged(CakeEvent $event)
{
$data = $event->data;
$subject = $event->subject();
$this->Document->SomethingImportantHappened($data,$subject);
}
}
What I like to do is place all my Events into the Lib folder. This makes it very easy to access from anywhere in the source code. The above code would go into App/Lib/Event/MyListener.php.
Attaching The EventListeners
Again, it depends on what events you need to listen for. The first thing you have to understand is that an object must be created in order to fire the event.
For example;
It's not possible for the Document model to fire Model.beforeSave event when the Calendar controller is displaying an index, because the Calendar controller never uses the Document model. Do you need to add a listener to Document in the bootstrap.php to catch when it saves? No, if Document model is only used from the Documents controller, then you only need to attach the listener there.
On the other hand, the User model is used by the Auth component almost every. If you want to handle a User being deleted. You might have to attach an event listener in the bootstrap.php to ensure no deletes sneak by you.
In the above example we can attach directly to the User model like so.
App::uses('MyListener','Lib');
$user = ClassRegistry::init('App.User');
$user->getEventManager()->attach(new MyListener());
This line will import your listener class.
App::uses('MyListener','Lib');
This line will get an instance of the User Model.
$user = ClassRegistry::init('App.User');
This line creates a listener, and attaches it to the User model.
$user->getEventManager()->attach(new MyListener());
If the User Model is used in many different places. You might have to do this in the bootstrap.php, but if it's only used by one controller. You can place that code in the beforeFilter or at the top of the PHP file.
What About Global EventManager?
Assuming we need to listen for general events. Like when ever any thing is saved. We would want to attach to the global EventManager. It would go something like this, and be placed in the bootstrap.php.
App::uses('MyListener','Lib');
CakeEventManager::instance()->attach(new MyListener());
If you want to attach an event listener inside bootstrap.php file of your plugin, everything should work fine using the hints posted in the answers. Here is my code (which works properly):
MyPlugin/Config/bootstrap.php:
App::uses('CakeEventManager', 'Event');
App::uses('MyEventListener', 'MyPlugin.Lib/Event');
CakeEventManager::instance()->attach(new MyEventListener());
MyPlugin/Lib/Event/MyEventListener.php:
App::uses('CakeEventListener', 'Event');
class MyEventListener implements CakeEventListener {
...
}
Event listeners related to MyPlugin are being registered only when the plugin is loaded. If I don't want to use the plugin, event listeners are not attached. I think this is a clean solution when you want to add some functionality in various places in your app using a plugin.
Its' not important, where the code resides. Just make sure its being executed and your events are properly registered & attached.
We're using a single file where all events are attached and include it from bootstrap.php, this ensures that all events are available from all locations in the app.
The magic happens when you dispatch an event, like from an controller action.
$event = new CakeEvent('Model.Order.afterPlace', $this, array('some'=>'data') ));
$this->getEventManager()->dispatch($event);
However, you can dispatch events from anywhere you can reach the EventManager (in Models, Controller and Views by default)

Registering a model as an event listener

I'd like to know if this is a good idea to register a Model class as an CakeEventListener inside the Model's PHP file.
For example, if I created a Model called Document that implements the listener, and at the bottom of the Document.php there I register it as a listener.
class Document extends AppModel implements CakeEventListener
{
.....
}
CakeEventManager::instance()->attach(ClassRegistery::init('Document'));
My question is about nexted calls to ClassRegistery::init('Document') and if the above would cause two instances of Document to be created.
For example, let's say I have the following in my controller.
class DocumentsController extends AppController
{
public function index()
{
$model = ClassRegistery::init('Document');
.....
How many times is Document instantiated?
The first call to ClassRegistery::init('Document') from the controller loads the Document.php file.
Wouldn't there be a second call to ClassRegistery::init('Document') from the bottom of Document.php befoe the first call has finished?
Would this somehow strew up the registry in CakePHP?
It shouldn't be a problem. ClassRegistry::init() only instantiates the object once. Subsequent calls to init() return the existing object.
I would, however, suggest registering the listener in Document's __construct function. This feels cleaner because we aren't mixing self-executing PHP with the class file. It also allows possible injection later on which would be useful for unit tests.

Zend Framework Widget Tutorial question

I try to follow this tutorial, but I can't get it to work:
http://weierophinney.net/matthew/archives/246-Using-Action-Helpers-To-Implement-Re-Usable-Widgets.html
I did everything as described, but I don't know how to make it available in my controllers. My filesystem looks like this:
- application
- controllers
- IndexController.php
- modules
- user
- configs
user.ini
- controllers
- forms
Login.php
- helpers
HandleLogin.php
- views
- scripts
login.phmtl
profile.phtml
Bootstrap.php
- views
How do I use the HandleLogin Helper in my IndexController? I really have no idea and I'm looking an trying for more then a day and I almost want to throw my PC out of the window ;). So any help would be appreciated!
Looks like the widget plugin is not called anywhere.
Few things to check:
Do you have a Bootstrap.php file for the module?
Does this bootstrap file has _initWidgets() method?
Does this method call:
$widget = new Module_Widget_Name; // is it callable?
Zend_Controller_Action_HelperBroker::addHelper($widget);
Have you registered widget resource?
public function _initResourceLoader()
{
$loader = $this->getResourceLoader();
$loader->addResourceType('helper', 'helpers', 'Helper');
$loader->addResourceType('widget', 'widgets', 'Widget');
return $loader;
}
Does application.ini contains resources.modules[] = line?
You dont. The point of the tutorial is to create a reusable widget that runs independent from any specific controllers. When the application receives a request, it will run through it's dispatch cycle and trigger the action helper on preDispatch automatically:
Now, let's look at the action helper itself. As a reminder, action helpers can define hooks for init() (invoked by the helper broker each time it is passed to a new controller), preDispatch() (invoked prior to executing the controller's preDispatch() hook and executing the action itself), and postDispatch() (executed after the action and the controller's postDispatch() routine).
The helper will fetch the current controller (whichever that may be for that request) to get the View instance and configure it with the form

Categories