Is there a consensus on how plugins should be implemented in a PHP application?
I've looked into the observer pattern which comes close, it's really just a notification system and doesn't allow code to extend the application directly. I'm currently using a simple hook systems that I came up with:
public function registerHook($hookName, array $params = array()) { $this->hooks[] = $hookName; foreach ( $this->plugins as $pluginName => $hooks ) { if ( in_array($hookName, $hooks) ) { $plugin = new $pluginName($this, $this->view, $this->controller); $plugin->{$hookName}($params); } } }
This works well for my purposes but I'm curious if there's a design pattern out there that has been tested and proven many times over and I'm just re-inventing the wheel.
PHP Design patterns is an Object-Oriented Programming (OOP) concept that is now also used in Drupal 9 projects. With Drupal's adoption of modern PHP and OOP concepts since version 8, design patterns can be leveraged for cleaner and more robust programming.
WP is built on an event-driven design pattern in which there is a publisher and a subscriber, hooks are an example of this. Discusses the Observer Pattern, also known as Publisher-Subscriber Pattern or Pub-Sub.
There is no consensus as in the Silver Bullet sense. For established patterns, you have multiple options like
to name a few.
Which you use is up to you, but you should make sure your system architecture supports the modularity. Have a look at these slides for some ideas
I think an Events Dispatcher is a nice and clean way to implement plugins, or any extension for that matter. An Events Dispatcher is an implementation of the Observer pattern, and is being used in symfony, Symfony2 and Zend Framework 2 (beta).
Looking through any of that source on github will make for some interesting reading. Though, an interesting bit of information can be found here:
http://components.symfony-project.org/event-dispatcher/trunk/book/02-Recipes
I wrote an Events and Hooks class a few years back for a project, I'll post that here if I can find it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With