PHP hook, building hooks in your application
Introduction
One of the real challenges in building any type of framework, core or application is making it possible for the developers to hook into the business logic at specific points. Since PHP is not event based, nor it works with interrupts you have to come up an alternative.
The test case
Lets assume we are the main developers of a webshop framework. Programmers can use our framework to build complete webshops. Programmers can manage the orders that are placed on the webshop with the order class. The order class is part of our framework and we don’t want it to be extended by any programmer. However we don’t want to limit to programmers in their possibilities to hook into the orders process.
For example programmers should be able to send an email to the webshopowner if an order changes from one specific delivery status to another. This functionality is not part of the default behavior in our framework and is custom for the progammers webshop implementation.
Like said before, PHP doesn’t provide interrupts or real events so we need to come up with another way to implement hooks into our application. Lets take a look at the observer pattern.
Implementing the Observer pattern
The observer pattern is a design-pattern that describes a way for objects to be notified to specific state-changes in objects of the application.
For the first implementation we can use SPL. The SPL provides in two simple objects:
SPLSubject
- attach (new observer to attach)
- detach (existing observer to detach)
- notify (notify all observers)
SPLObserver
- update (Called from the subject (i.e. when it’s value has changed).
iOrderRef = $iOrderRef;
// Get order information from the database or an other resources
$this->iStatus = Order::STATUS_SHIPPED;
}
/**
* Attach an observer
*
* @param SplObserver $oObserver
* @return void
*/
public function attach(SplObserver $oObserver)
{
$sHash = spl_object_hash($oObserver);
if (isset($this->aObservers[$sHash])) {
throw new Exception('Observer is already attached');
}
$this->aObservers[$sHash] = $oObserver;
}
/**
* Detach observer
*
* @param SplObserver $oObserver
* @return void
*/
public function detach(SplObserver $oObserver)
{
$sHash = spl_object_hash($oObserver);
if (!isset($this->aObservers[$sHash])) {
throw new Exception('Observer not attached');
}
unset($this->aObservers[$sHash]);
}
/**
* Notify the attached observers
*
* @param string $sEvent, name of the event
* @param mixed $mData, optional data that is not directly available for the observers
* @return void
*/
public function notify()
{
foreach ($this->aObservers as $oObserver) {
try {
$oObserver->update($this);
} catch(Exception $e) {
}
}
}
/**
* Add an order
*
* @param array $aOrder
* @return void
*/
public function delete()
{
$this->notify();
}
/**
* Return the order reference number
*
* @return int
*/
public function getRef()
{
return $this->iOrderRef;
}
/**
* Return the current order status
*
* @return int
*/
public function getStatus()
{
return $this->iStatus;
}
/**
* Update the order status
*/
public function updateStatus($iStatus)
{
$this->notify();
// ...
$this->iStatus = $iStatus;
// ...
$this->notify();
}
}
/**
* Order status handler, observer that sends an email to secretary
* if the status of an order changes from shipped to delivered, so the
* secratary can make a phone call to our customer to ask for his opinion about the service
*
* @package Shop
*/
class OrderStatusHandler implements SplObserver
{
/**
* Previous orderstatus
* @var int
*/
protected $iPreviousOrderStatus;
/**
* Current orderstatus
* @var int
*/
protected $iCurrentOrderStatus;
/**
* Update, called by the observable object order
*
* @param Observable_Interface $oSubject
* @param string $sEvent
* @param mixed $mData
* @return void
*/
public function update(SplSubject $oSubject)
{
if(!$oSubject instanceof Order) {
return;
}
if(is_null($this->iPreviousOrderStatus)) {
$this->iPreviousOrderStatus = $oSubject->getStatus();
} else {
$this->iCurrentOrderStatus = $oSubject->getStatus();
if($this->iPreviousOrderStatus === Order::STATUS_SHIPPED && $this->iCurrentOrderStatus === Order::STATUS_DELIVERED) {
$sSubject = sprintf('Order number %d is shipped', $oSubject->getRef());
//mail('secratary@example.com', 'Order number %d is shipped', 'Text');
echo 'Mail sended to the secratary to help her remember to call our customer for a survey.';
}
}
}
}
$oOrder = new Order(26012011);
$oOrder->attach(new OrderStatusHandler());
$oOrder->updateStatus(Order::STATUS_DELIVERED);
$oOrder->delete();
?>
There are several problems with the implementation above. To most important disadvantage is that we have only one update method in our observer. In this update method we don’t know when and why we are getting notified, just that something happened. We should keep track of everything that happens in the subject. (Or use debug_backtrace… just joking, don’t even think about using it that way ever!).
Taking it a step further, events
Lets take a look at the next example, we will extend the Observer implementation with some an additional parameter for the eventname that occured.
Finishing up, optional data
iOrderRef = $iOrderRef;
// Get order information from the database or something else...
$this->iStatus = Order::STATUS_SHIPPED;
}
/**
* Attach an observer
*
* @param Observer_Interface $oObserver
* @return void
*/
public function attachObserver(Observer_Interface $oObserver)
{
$sHash = spl_object_hash($oObserver);
if (isset($this->aObservers[$sHash])) {
throw new Exception('Observer is already attached');
}
$this->aObservers[$sHash] = $oObserver;
}
/**
* Detach observer
*
* @param Observer_Interface $oObserver
* @return void
*/
public function detachObserver(Observer_Interface $oObserver)
{
$sHash = spl_object_hash($oObserver);
if (!isset($this->aObservers[$sHash])) {
throw new Exception('Observer not attached');
}
unset($this->aObservers[$sHash]);
}
/**
* Notify the attached observers
*
* @param string $sEvent, name of the event
* @param mixed $mData, optional data that is not directly available for the observers
* @return void
*/
public function notifyObserver($sEvent, $mData=null)
{
foreach ($this->aObservers as $oObserver) {
try {
$oObserver->update($this, $sEvent, $mData);
} catch(Exception $e) {
}
}
}
/**
* Add an order
*
* @param array $aOrder
* @return void
*/
public function add($aOrder = array())
{
$this->notifyObserver('onAdd');
}
/**
* Return the order reference number
*
* @return int
*/
public function getRef()
{
return $this->iOrderRef;
}
/**
* Return the current order status
*
* @return int
*/
public function getStatus()
{
return $this->iStatus;
}
/**
* Update the order status
*/
public function updateStatus($iStatus)
{
$this->notifyObserver('onBeforeUpdateStatus');
// ...
$this->iStatus = $iStatus;
// ...
$this->notifyObserver('onAfterUpdateStatus');
}
}
/**
* Order status handler, observer that sends an email to secretary
* if the status of an order changes from shipped to delivered, so the
* secratary can make a phone call to our customer to ask for his opinion about the service
*
* @package Shop
*/
class OrderStatusHandler implements Observer_Interface
{
protected $iPreviousOrderStatus;
protected $iCurrentOrderStatus;
/**
* Update, called by the observable object order
*
* @param Observable_Interface $oObservable
* @param string $sEvent
* @param mixed $mData
* @return void
*/
public function update(Observable_Interface $oObservable, $sEvent, $mData=null)
{
if(!$oObservable instanceof Order) {
return;
}
switch($sEvent) {
case 'onBeforeUpdateStatus':
$this->iPreviousOrderStatus = $oObservable->getStatus();
return;
case 'onAfterUpdateStatus':
$this->iCurrentOrderStatus = $oObservable->getStatus();
if($this->iPreviousOrderStatus === Order::STATUS_SHIPPED && $this->iCurrentOrderStatus === Order::STATUS_DELIVERED) {
$sSubject = sprintf('Order number %d is shipped', $oObservable->getRef());
//mail('secratary@example.com', 'Order number %d is shipped', 'Text');
echo 'Mail sended to the secratary to help her remember to call our customer for a survey.';
}
}
}
}
$oOrder = new Order(26012011);
$oOrder->attachObserver(new OrderStatusHandler());
$oOrder->updateStatus(Order::STATUS_DELIVERED);
$oOrder->add();
?>
Now we are able to take action on different events that occur.
Disadvantages
Although this implementation works quite well there are some drawbacks. One of those drawbacks is that we need to dispatch an event in our framework, if we don’t programmers can’t hook into our application. Triggering events everywhere give us a small performance penalty however I do think this way of working gives the programmers a nice way to hook into your application on those spots that you want them to hook in.
Just for the record
Notice that this code is just an example and can still use some improvements, for example: each observer is initialized even it will maybe never be notified, therefore I suggest to make use of lazy in some cases for loading the objects. There are other systems to hook into an application, more to follow!
сео продвижение сайтов топ 10 [url=www.seo-prodvizhenie-reiting.ru/]сео продвижение сайтов топ 10[/url] .
seo prodvijenie reiting_qxEa
21 Oct 25 at 5:30 am
Вызов нарколога на дом сочетает медицинскую эффективность с удобством. Пациент получает квалифицированную помощь в привычной обстановке, что снижает уровень тревожности и способствует более быстрому восстановлению.
Узнать больше – [url=https://narkolog-na-dom-sankt-peterburg14.ru/]психиатр нарколог на дом санкт-петербург[/url]
RobertSak
21 Oct 25 at 5:31 am
We recommend you to invite your friends to have fun with our referral bonus. 100% bonus on first deposit up to half thousand Malaysian ringgit on [url=http://eltric.pl/2025/10/10/winning-strategies-for-plinko-game-online-tips-and/]http://eltric.pl/2025/10/10/winning-strategies-for-plinko-game-online-tips-and/[/url]!
RitaFumma
21 Oct 25 at 5:32 am
Le code promo est supprime : entrez-le dans le champ « Code promo » et reclamez un bonus de bienvenue de 100% jusqu’a 130€, pour vos paris sportifs. Inscrivez-vous sur 1xBet ou via l’application mobile. Apres votre premier depot, vous activerez le code bonus. L’offre est valable pour toute l’annee 2026, et le bonus doit etre mise dans les 30 jours. Decouvrez plus d’informations sur le code promo via ce lien — Meilleur Code Promo Pour 1xbet. Le code promo 1xBet casino offre des tours gratuits et un bonus de depot 1xBet pour les nouveaux joueurs. Avec le code promotionnel 1xBet pour nouveaux utilisateurs, recevez jusqu’a 130€ de bonus d’inscription 1xBet. Utilisez le code promo 1xBet aujourd’hui pour jouer au casino en ligne 1xBet et profiter de toutes les offres disponibles.
Marvinspaft
21 Oct 25 at 5:33 am
купить диплом в энгельсе [url=https://rudik-diplom3.ru]https://rudik-diplom3.ru[/url] .
Diplomi_eyei
21 Oct 25 at 5:34 am
Купить диплом колледжа в Луганск [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .
Diplomi_afea
21 Oct 25 at 5:35 am
Someone essentially assist to make critically
articles I’d state. This is the first time I frequented your web page and to this point?
I surprised with the research you made to create this particular
submit amazing. Wonderful task!
Voxigenai
21 Oct 25 at 5:36 am
Appreciating the dedication you put into your blog and detailed information you provide.
It’s nice to come across a blog every once in a while that isn’t the same outdated rehashed information. Great read!
I’ve saved your site and I’m including your RSS
feeds to my Google account.
relevant {material
21 Oct 25 at 5:36 am
pin up app uz [url=https://www.pinup5008.ru]pin up app uz[/url]
pin_up_uz_tzSt
21 Oct 25 at 5:38 am
диплом купить с занесением в реестр москва [url=http://www.frei-diplom6.ru]диплом купить с занесением в реестр москва[/url] .
Diplomi_mdOl
21 Oct 25 at 5:38 am
http://pilloleverdi.com/# farmacia online italiana Cialis
MickeySum
21 Oct 25 at 5:42 am
купить диплом в канске [url=https://www.rudik-diplom3.ru]купить диплом в канске[/url] .
Diplomi_nmei
21 Oct 25 at 5:42 am
купить диплом в люберцах [url=http://www.rudik-diplom4.ru]купить диплом в люберцах[/url] .
Diplomi_tnOr
21 Oct 25 at 5:43 am
купить диплом в белогорске [url=www.rudik-diplom1.ru/]www.rudik-diplom1.ru/[/url] .
Diplomi_raer
21 Oct 25 at 5:43 am
Как купить Фенибут в Заволжье?Что думаете, есть смысл брать на https://xozmarket24.ru
? Цены привлекательные, доставка работает. Интересует про качество на практике.
Stevenref
21 Oct 25 at 5:43 am
Цифровая штаб-квартира – Ваш онлайн-портал к бренду.
Jeremyjoync
21 Oct 25 at 5:43 am
pin up demo aviator o‘ynash [url=http://pinup5008.ru/]http://pinup5008.ru/[/url]
pin_up_uz_uqSt
21 Oct 25 at 5:44 am
рейтинг рунета seo [url=http://luchshie-digital-agencstva.ru]http://luchshie-digital-agencstva.ru[/url] .
lychshie digital agentstva_jooi
21 Oct 25 at 5:44 am
как купить диплом с занесением в реестр в екатеринбурге [url=https://www.frei-diplom4.ru]https://www.frei-diplom4.ru[/url] .
Diplomi_ajOl
21 Oct 25 at 5:45 am
купить диплом в кстово [url=www.rudik-diplom10.ru]www.rudik-diplom10.ru[/url] .
Diplomi_hiSa
21 Oct 25 at 5:46 am
купить диплом в воткинске [url=rudik-diplom8.ru]купить диплом в воткинске[/url] .
Diplomi_uzMt
21 Oct 25 at 5:46 am
купить диплом в феодосии [url=https://www.rudik-diplom4.ru]https://www.rudik-diplom4.ru[/url] .
Diplomi_izOr
21 Oct 25 at 5:50 am
купить диплом в перми [url=www.rudik-diplom1.ru/]купить диплом в перми[/url] .
Diplomi_zser
21 Oct 25 at 5:51 am
купить диплом занесенный в реестр [url=www.frei-diplom4.ru/]купить диплом занесенный в реестр[/url] .
Diplomi_iqOl
21 Oct 25 at 5:52 am
топ сео компаний [url=http://seo-prodvizhenie-reiting.ru]http://seo-prodvizhenie-reiting.ru[/url] .
seo prodvijenie reiting_rgEa
21 Oct 25 at 5:53 am
купить диплом в химках [url=www.rudik-diplom8.ru/]купить диплом в химках[/url] .
Diplomi_zjMt
21 Oct 25 at 5:54 am
My brother recommended I would possibly like this web site.
He was once totally right. This publish actually
made my day. You can not consider just how a lot time I had spent for this information! Thank you!
homepage
21 Oct 25 at 5:55 am
купить диплом в махачкале [url=http://rudik-diplom3.ru/]купить диплом в махачкале[/url] .
Diplomi_kiei
21 Oct 25 at 5:55 am
можно ли купить диплом медсестры [url=www.frei-diplom13.ru]можно ли купить диплом медсестры[/url] .
Diplomi_idkt
21 Oct 25 at 5:55 am
кракен официальный сайт
кракен vpn
JamesDaync
21 Oct 25 at 5:56 am
купить диплом в ишимбае [url=http://rudik-diplom1.ru]http://rudik-diplom1.ru[/url] .
Diplomi_wmer
21 Oct 25 at 5:56 am
купить диплом в северодвинске [url=rudik-diplom4.ru]купить диплом в северодвинске[/url] .
Diplomi_edOr
21 Oct 25 at 5:56 am
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Не упусти шанс – https://www.hesgarsazan.com/products/chemisorption
CarltonOvert
21 Oct 25 at 5:56 am
рейтинг компаний по продвижению сайтов [url=https://reiting-seo-kompanii.ru/]рейтинг компаний по продвижению сайтов[/url] .
reiting seo kompanii_tpsn
21 Oct 25 at 5:56 am
Unquestionably imagine that that you said. Your favourite justification seemed
to be at the internet the easiest factor to take into account of.
I say to you, I definitely get annoyed even as other people think about issues that they just do not understand about.
You controlled to hit the nail upon the highest and defined out the entire thing without
having side-effects , other folks could take a signal.
Will likely be again to get more. Thanks
how many puffs in a geek bar
21 Oct 25 at 5:57 am
купить диплом в белово [url=www.rudik-diplom11.ru/]www.rudik-diplom11.ru/[/url] .
Diplomi_kcMi
21 Oct 25 at 5:57 am
купить диплом с занесением в реестр пенза [url=http://frei-diplom5.ru]купить диплом с занесением в реестр пенза[/url] .
Diplomi_twPa
21 Oct 25 at 5:58 am
раскрутка сайта seo [url=www.reiting-runeta-seo.ru]раскрутка сайта seo[/url] .
reiting ryneta seo_zima
21 Oct 25 at 5:58 am
https://choice4profitads.com/index.php?page=item&id=45692
DerekCer
21 Oct 25 at 5:59 am
купить диплом врача [url=https://rudik-diplom8.ru]купить диплом врача[/url] .
Diplomi_xxMt
21 Oct 25 at 6:00 am
When someone write an piece of writing he/she maintains the
image of a user in his/her mind that how a user can know it.
So that’s why this article is amazing. Thanks!
child nudity
21 Oct 25 at 6:03 am
Hi there! I could have sworn I’ve visited your blog
before but after looking at a few of the articles I
realized it’s new to me. Nonetheless, I’m definitely pleased I discovered it and I’ll be bookmarking it and checking back frequently!
realistic product reviews
21 Oct 25 at 6:04 am
купить диплом москва с занесением в реестр [url=https://www.frei-diplom4.ru]купить диплом москва с занесением в реестр[/url] .
Diplomi_fpOl
21 Oct 25 at 6:04 am
куплю диплом младшей медсестры [url=www.frei-diplom13.ru]www.frei-diplom13.ru[/url] .
Diplomi_xqkt
21 Oct 25 at 6:05 am
купить диплом в саратове [url=https://rudik-diplom10.ru/]купить диплом в саратове[/url] .
Diplomi_atSa
21 Oct 25 at 6:05 am
диплом техникума ссср купить [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_wiea
21 Oct 25 at 6:06 am
[url=https://svarog-lestnic.ru/]изготовление лестниц для дома[/url]
WilburnPiple
21 Oct 25 at 6:06 am
купить диплом в красноярске [url=www.rudik-diplom11.ru/]купить диплом в красноярске[/url] .
Diplomi_reMi
21 Oct 25 at 6:06 am
купить диплом с занесением в реестр отзывы [url=https://www.frei-diplom5.ru]купить диплом с занесением в реестр отзывы[/url] .
Diplomi_dzPa
21 Oct 25 at 6:06 am
топ digital компаний россии [url=http://luchshie-digital-agencstva.ru]http://luchshie-digital-agencstva.ru[/url] .
lychshie digital agentstva_xgoi
21 Oct 25 at 6:10 am