How to Use the Symfony Event Dispatcher for PHP

by:

Web Development

These days, we are heading to discover how to use the Symfony party dispatcher part, which lets you to make situations and listeners in your PHP apps. Thus, diverse components of your application can discuss to each and every other with loosely coupled code.

What Is the Symfony Occasion Dispatcher Component?

You may possibly be acquainted with the celebration-observer pattern, which enables you to outline listeners for method-generated occasions so that they are executed when the event is activated. In the same way, the Symfony EventDispatcher element allows you to established up a process in which you could create personalized events and listeners. In that way, you let elements in your software to respond if a little something takes place in a technique.

In point, the function dispatcher component supplies 3 factors that you could develop your app architecture about: function, listener, and dispatcher. The total procedure is orchestrated by the dispatcher class, which raises functions at suitable points in an software and calls listeners connected with those people activities.

Let us presume that you want to allow for other factors in your software to respond when the cache is cleared. In that case, you will need to determine the obvious cache occasion in the to start with spot. Following the cache is cleared, you can use the dispatcher to elevate the clear cache event, and that notifies all listeners that are listening to this celebration. This presents listeners the option to purge ingredient-specific caches.

In this short article, we are going to discover the basic principles of the celebration dispatcher ingredient. We’ll commence with installation and configuration, and we are going to also develop a number of real-environment examples to demonstrate all the ideas stated higher than.

Installing and Configuring the Party Dispatcher

In this area, we’re heading to put in the occasion dispatcher element. I presume that you’ve now installed Composer on your technique, because we are going to have to have it to put in the EventDispatcher element.

Once you’ve put in Composer, go forward and put in the EventDispatcher component employing the adhering to command.

That should have created the composer.json file, which need to search like this:

Let’s more edit the composer.json file to seem like the next:

As we have included a new classmap entry, go ahead and update the Composer autoloader by running the subsequent command.

Now, you can use the EventDispatchers namespace to autoload courses underneath the src listing.

So that’s the installation portion, but how are you intended to use it? In reality, it is just a subject of which include the autoload.php file established by Composer in your application, as proven in the following snippet.

How to Produce, Dispatch, and Hear to Activities

In this area, we are going to go through an instance which demonstrates how you could generate a custom made occasion and set up a listener for that celebration.

The Party Course

To start out with, go forward and build the src/Events/DemoEvent.php file with the next contents.

Our custom DemoEvent course extends the core Celebration class of the EventDispatcher ingredient. The Title continuous holds the name of our customized functiondemo.celebration. It can be employed when you want to set up a listener for this celebration.

The Listener Course

Upcoming, let us make the listener course src/Listeners/DemoListener.php with the following contents.

The DemoListener course implements the onDemoEvent system which is triggered when the method dispatches the DemoEvent party. Of course, it is not going to transpire mechanically still, as we have to have to sign-up the DemoListener listener to pay attention the demo.party function applying the EventDispatcher class.

So far, we’ve produced event and listener lessons. Subsequent, we are going to see how to tie all these parts collectively.

An Example File

Let’s make the standard_example.php file with the following contents.

The EventDispatcher course is the most essential aspect in the EventDispatcher component—it will allow you to bind listeners to functions they want to listen to. We have applied the addListener technique of the EventDispatcher course to hear to the demo.event function.

The to start with argument of the addListener technique is an occasion identify, and the next argument is the PHP callable which is brought on when the registered event is dispatched. In our case, we’ve presented the DemoListener item as a listener along with the onDemoEvent process.

Last but not least, we’ve used the dispatch system of the EventDispatcher course to dispatch the demo.function occasion.

When you operate the primary_instance.php file, it need to generate the pursuing output.

As expected, the onDemoEvent process of the DemoListener course is termed, and that in change phone calls the getFoo strategy of the DemoEvent class to fetch the function-relevant data.

What Is an Occasion Subscriber?

In the earlier portion, we created an illustration which demonstrated how to build a custom made celebration and a personalized listener. We also talked over how to bind a listener to the unique party utilizing the EventDispatcher class.

That was a straightforward illustration, as we only needed to established up a listener for a solitary function. On the other hand, if you want to established up listeners for various gatherings or you want to logically group party dealing with logic in a single class, you ought to contemplate utilizing celebration subscribers because they permit you to continue to keep all the things in one location.

In this part, we will revise the illustration which was produced in the preceding section.

The Subscriber Course

The initially matter that we have to have to do is to produce a subscriber class which implements the EventSubscriberInterface interface. Go in advance and develop the src/Subsribers/DemoSubscriber.php class as revealed in the adhering to snippet.

Considering the fact that the class DemoSubscriber implements the EventSubscriberInterface interface, it need to implement the getSubscribedEvents strategy. The getSubscribedEvents process ought to return an array of occasions that you want to subscribe to. You need to have to deliver the celebration name in an array vital and the approach identify in an array worth which is identified as when the function is triggered.

The final issue is to apply the listener method in the exact class. In our case, we want to carry out the onDemoEvent approach, and we have now carried out that.

An Illustration File

It really is time to exam our subscriber! Let’s quickly build the subscriber_illustration.php file with the pursuing contents.

You require to use the addSubscriber system of the EventDispatcher class to subscribe your tailor made subscriber, and the EventDispatcher course handles the rest. It fetches activities to be subscribed from the getSubscribedEvents process and sets up listeners for those events. Aside from that, everything is the same, and it must perform as expected with no surprises.

Let’s examination it!

And that was an event subscriber at your disposal! That also delivers us to the conclusion of this write-up.

Conclusion

These days, we explored the Symfony occasion dispatcher part, which allows you to set up situations and listeners in your PHP apps. By utilizing this library, you can generate a loosely coupled method which permits components of your software to connect with each other easily.

Experience free to share your feelings and queries applying the variety below!

Leave a Reply

Your email address will not be published. Required fields are marked *