Dispatching and listening for events in the Ding container

Easy Event Oriented Programming in your PHP Application

Events in the ding container are strings. This is not a great level of abstraction but still provides a powerful tool to work with. Events also have associated data, sent to the listeners as an argument when firing the event. This simple workflow will allow you to extend your system with autonomous components that react to events, totally decoupled from the rest of the code.

The events section of the manual will also be handy.

Firing an event from your PHP Code

To fire an event, you need an instance of the container. You can get it by implementing the interface IContainerAware in your beans, like:

When the container creates a bean that implements the IContainerAware interface it will automatically inject a container instance through the setContainer() method. So now you have a container instance.

Notice in the createUser() method how we do our thing, and then dispatch the "userCreated" event throughout the container. The listeners will then receive this event and associated data, in this case a User entity. Let's see how to create the listeners.

Listening and Reacting to the Application Events in your PHP Code

A very simple listener code for the above scenario can be:

That's it. The container will call (by convention) the method onUserCreated() when the "userCreated" event is dispatched. The general rule is to upper camel case the event name, and prepend the "on" to it, so "userCreated" becomes "onUserCreated".

This will make the container able to dispatch the event, but we still need to register the bean as a listener for the event. Let's now see how to do it programatically, and then with the XML, YAML, and Annotations drivers.

Register an event listener programmatically in PHP

The container has the method eventListen() used to register a component as an event listener. Thus, by using a container instance, you could do:

Registering event listeners with PHP Annotations

Registering event listeners with XML

Registering event listeners with YAML

Ready to start writing your own event driven application in PHP?

Some things are still missing, for example listening or catching all the events or all events of a certain type. However, this simple schema can also do some good in decoupling your code and separating your concerns in different components throughout your application.