Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Design pattern for implementing plugins in PHP applications

Tags:

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.

like image 445
Elbert Alias Avatar asked Feb 11 '12 21:02

Elbert Alias


People also ask

What is the design pattern in PHP?

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.

Which design pattern is used in Wordpress?

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.


2 Answers

There is no consensus as in the Silver Bullet sense. For established patterns, you have multiple options like

  • Subject/Observer,
  • Signal Slot,
  • Event Dispatcher or
  • Pipes and Filters

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

  • http://qafoo.com/talks/11_06_ipc_spring_modular_application_architecture.pdf
like image 184
Gordon Avatar answered Sep 19 '22 13:09

Gordon


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.

like image 37
lshepstone Avatar answered Sep 16 '22 13:09

lshepstone