freezemage0
Freezemage
1 post
Don't wanna be here? Send us removal request.
freezemage0 · 5 years ago
Text
[PHP] Event Management
Let’s say that you have this method:
Tumblr media
But you want to make variables $a and $b editable by other developers. Sure, other devs can just edit your code and do whatever they want with the variables. But what if this code is essential to application’s work?
Here is where the Events come into play.
At first, let’s describe the Event class itself.
Tumblr media
So what is this class for?
You can instantiate an object of this class inside any of your methods (thus making the Extension Point in your method), transfer the parameters that you think should be accessible to other devs and call all handlers which are subscribed to this event.
You may have noticed the class EventManager. Whenever you call Event::send() (fire event), this class calls all registered handlers.
Here is the EventManager:
Tumblr media
The connection between EventManager and Event implements “Subscriber” Design Pattern. The EventManager itself implements Design Pattern “Singleton”.
You can access EventManager instance at any point of program execution and it is guaranteed that this instance will be the one and only.
Keeping the EventManager registry pool in the Database is a good practice, since the constructor of EventManager is called only once, therefore you don’t need to fetch data from database everytime the EventManager::getInstance() is called.
Let’s create an Extension Point inside our Main::sum() method and register an Event Handler!
Updated Main::sum():
Tumblr media
The error handling should be still performed inside the main method.
An example of Event handler:
Tumblr media
We can operate the passed variables $a and $b using Event::getParameters() and Event::setParameters() methods. If the parameters don’t meet some conditions that are required for modification, we can inform the user about it via Event::addError().
The handler should return false if the method from where the Event was fired should stop execution.
The ouput will be 12.
Of course, this code is not ideal, can be improved in many ways and does not bring something entirely new to the programing.
The whole point of this modification: the developers can influence the execution of your method without making changes to it. If you ever release a new update where you change your method, no third party modifications will be erased. But only if you don’t remove the event, of course.
GitHub: https://github.com/freezemage0/event.manager
1 note · View note