2

I have an application where I want to implement the following system. In certain key places of code, I'll have lines such as

$event_handler->trigger('on_after_init');

This line will announce that initialization has just been finished. Then I want to have some random extensions/plugins listening to this and other events and execute whatever code they want to. For example something like a plugins/after_init/... where you can put a class that will get executed. Or may be I'll keep them in DB so that I could also adjust the order if needed.

While I can build something like that, I feel that this is a classical task and that there is a standard pattern for that. I don't want to invent bicycle so in case this is really so, please point me to the relevant information.

Thanks!

Eugene
  • 4,197
  • 7
  • 37
  • 54
  • 2
    I would avoid the Observer pattern for the reasons I listed in [this answer](http://stackoverflow.com/questions/9776364/whats-the-proper-way-to-use-symfonys-eventdispatcher-component/9790350#9790350). The Mediator pattern or Chain of Responsibility is generally much better for this sort of thing ... –  Mar 21 '12 at 20:29
  • 2
    Also, @ircmaxell recently posted [a blog surveying this entire topic](http://blog.ircmaxell.com/2012/03/handling-plugins-in-php.html) and he idles in the PHP chatroom if you need clarification. Further, at the risk of self-promotion, here's an [object oriented implementation of the mediator pattern](https://github.com/rdlowrey/Artax/blob/master/Core/src/Artax/Events/Mediator.php) I put together recently if you're interested in seeing a concrete example. –  Mar 21 '12 at 20:30

2 Answers2

1

Symfony provides a number of stand-alone components, one of which is an EventDispatcher component, take a look and see if it will fit your needs.

Mike Purcell
  • 19,847
  • 10
  • 52
  • 89
0

prggmr provides an event library for triggering events in your application, in essence you "subscribe" to and "fire" signals within your application.

subscribe(function($event){
    echo "Do something here"
}, 'on_after_init');

fire("on_after_init");

This can loosely be defined as the Observer pattern, although it is much less of a OOP design pattern and more of a programming paradigm of Event Driven Programming.

Nick
  • 763
  • 1
  • 11
  • 26