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!
дивитися фільми без реклами безкоштовне кіно Full HD
uakino-817
30 Jul 25 at 2:22 pm
Трубы квадратные купить
Трубы круглые купить
30 Jul 25 at 2:22 pm
where can i get doxycycline without insurance
buy doxycycline uk boots
30 Jul 25 at 2:22 pm
ставки на спорт прогнозы хоккей [url=http://luchshie-prognozy-na-khokkej6.ru]http://luchshie-prognozy-na-khokkej6.ru[/url] .
lychshie prognozi na hokkei_owMi
30 Jul 25 at 2:31 pm
I don’t know if it’s just me or if perhaps everybody else experiencing issues with your website.
It looks like some of the written text within your content are running off the screen. Can somebody else
please provide feedback and let me know if this is happening
to them too? This could be a issue with my web browser because I’ve had this happen before.
Cheers
مشاهده برنامه کلاسی گلستان ۱۴۰۴-۱۴۰۵
30 Jul 25 at 2:35 pm
Кейсы кс го
Lucianowhess
30 Jul 25 at 2:40 pm
прогнозы на периоды в хоккее [url=https://luchshie-prognozy-na-khokkej6.ru]https://luchshie-prognozy-na-khokkej6.ru[/url] .
lychshie prognozi na hokkei_feMi
30 Jul 25 at 2:41 pm
аренда яхты сайт [url=yacht-rental-oae.com]yacht-rental-oae.com[/url] .
arenda yaht dybai_rkPt
30 Jul 25 at 2:42 pm
Затяжной запой опасен для жизни. Врачи наркологической клиники в Ростове-На-Дону проводят срочный вывод из запоя — на дому или в стационаре. Анонимно, безопасно, круглосуточно.
Слушай внимательно — тут важно – [url=https://vyvod-iz-zapoya-rostov12.ru/]vyvod-iz-zapoya-rostov12.ru[/url]
GeraldNuh
30 Jul 25 at 2:44 pm
прогнозы на хоккей от профессионалов бесплатно [url=www.luchshie-prognozy-na-khokkej6.ru]www.luchshie-prognozy-na-khokkej6.ru[/url] .
lychshie prognozi na hokkei_brMi
30 Jul 25 at 2:44 pm
Компоненты капельницы
Получить дополнительную информацию – [url=https://kapelnica-ot-zapoya-krasnoyarsk6.ru/]сколько стоит капельница от запоя красноярск[/url]
Miguelodora
30 Jul 25 at 2:44 pm
Когда организм на пределе, важна срочная помощь в Ростове-На-Дону — это команда опытных наркологов, которые помогут быстро и мягко выйти из запоя без вреда для здоровья.
Это ещё не всё… – [url=https://vyvod-iz-zapoya-rostov16.ru/]нарколог вывод из запоя[/url]
KeithJab
30 Jul 25 at 2:46 pm
кайтинг “Одеяние Посейдона”: гидрокостюм, защита от “ледяных объятий”
RamonLiata
30 Jul 25 at 2:55 pm
Чем дольше и интенсивнее продолжается запой, тем выше становится риск возникновения широкого спектра серьезных и потенциально смертельных осложнений, начиная от тяжелых нарушений работы сердечно-сосудистой системы и заканчивая необратимым повреждением жизненно важных внутренних органов, что требует немедленной и комплексной медицинской помощи
Подробнее тут – [url=https://vyvod-iz-zapoya-arkhangelsk66.ru/]вывод из запоя недорого архангельск[/url]
TamikaNounc
30 Jul 25 at 2:56 pm
прогноз на теннис на сегодня от профессионалов [url=https://www.prognoz-na-segodnya-na-sport9.ru]https://www.prognoz-na-segodnya-na-sport9.ru[/url] .
prognoz na segodnya na sport_bipl
30 Jul 25 at 2:56 pm
аренда яхты на сутки [url=http://yacht-rental-oae.com/]http://yacht-rental-oae.com/[/url] .
arenda yaht dybai_anPt
30 Jul 25 at 2:57 pm
Наши специалисты работают круглосуточно, помогая пациентам справиться с абстинентным синдромом, восстановить здоровье и снизить риски осложнений.
Получить больше информации – https://vyvod-iz-zapoya-novokuznetsk6.ru/vyvod-iz-zapoya-na-domu-novokuzneczk
Eduardoflamn
30 Jul 25 at 2:59 pm
Стоимость услуг по установке капельницы определяется индивидуально и зависит от нескольких факторов. В первую очередь, цена обусловлена тяжестью состояния пациента: при более сильной интоксикации и выраженных симптомах абстинентного синдрома может потребоваться расширенная терапия. Кроме того, итоговая сумма зависит от продолжительности запоя, так как длительное употребление спиртного ведет к более серьезному накоплению токсинов, требующему дополнительных лечебных мероприятий.
Получить больше информации – [url=https://kapelnica-ot-zapoya-nizhniy-novgorod000.ru/]капельница от запоя на дому цена в нижний новгороде[/url]
EugeneSow
30 Jul 25 at 3:00 pm
прогнозы на периоды в хоккее [url=luchshie-prognozy-na-khokkej6.ru]luchshie-prognozy-na-khokkej6.ru[/url] .
lychshie prognozi na hokkei_bcMi
30 Jul 25 at 3:01 pm
лучшие прогнозы на спорт [url=https://prognoz-na-segodnya-na-sport10.ru/]лучшие прогнозы на спорт[/url] .
prognoz na segodnya na sport_ikEn
30 Jul 25 at 3:02 pm
дивлячись фільми онлайн HD фільми українською онлайн
ua-bay-563
30 Jul 25 at 3:03 pm
I am not sure where you’re getting your info, but good topic.
I needs to spend some time learning much more or
understanding more. Thanks for wonderful information I was looking for this information for my mission.
automatic engagement
30 Jul 25 at 3:03 pm
Услуга “Нарколог на дом” в Уфе охватывает широкий спектр лечебных мероприятий, направленных как на устранение токсической нагрузки, так и на работу с психоэмоциональным состоянием пациента. Комплексная терапия включает в себя медикаментозную детоксикацию, корректировку обменных процессов, а также психотерапевтическую поддержку, что позволяет не только вывести пациента из состояния запоя, но и помочь ему справиться с наркотической зависимостью.
Изучить вопрос глубже – [url=https://narcolog-na-dom-ufa000.ru/]narkolog na dom ufa[/url]
Bruceprort
30 Jul 25 at 3:04 pm
Введение препаратов осуществляется внутривенно, что обеспечивает оперативное действие медикаментов. В состав лечебного раствора входят средства для детоксикации организма, нормализации водно-электролитного и кислотно-щелочного баланса. При необходимости врач дополнительно вводит препараты, защищающие печень, стабилизирующие работу сердца и успокаивающие нервную систему. Вся процедура проводится под строгим контролем нарколога, который следит за состоянием пациента и корректирует терапию при необходимости. По завершении процедуры врач дает пациенту и его родственникам подробные рекомендации по дальнейшему восстановлению и профилактике повторных запоев.
Ознакомиться с деталями – [url=https://kapelnica-ot-zapoya-nizhniy-novgorod0.ru/]капельница от запоя нижний новгород[/url]
RobertFum
30 Jul 25 at 3:05 pm
мастер класс по нейросетям [url=www.sites.google.com/view/neyroseti-obuchenie-s-nulya//]www.sites.google.com/view/neyroseti-obuchenie-s-nulya//[/url] .
888starz_wupa
30 Jul 25 at 3:06 pm
кайтсёрфинг Кайтсёрфинг – это не только спорт, но и образ жизни. Он привлекает людей, любящих приключения, природу и свободу. Многие кайтсёрферы путешествуют по миру в поисках лучших ветровых условий и красивых спотов.
RamonLiata
30 Jul 25 at 3:06 pm
Pretty element of content. I just stumbled upon your web site and in accession capital to claim that
I acquire in fact enjoyed account your blog posts.
Any way I’ll be subscribing in your feeds or even I fulfillment you get
admission to consistently quickly.
Feel free to visit my website :: internet voor emigranten zonder gedoe
internet voor emigranten zonder gedoe
30 Jul 25 at 3:10 pm
После поступления звонка нарколог оперативно выезжает по указанному адресу и прибывает в течение 30–60 минут. Врач незамедлительно приступает к оказанию помощи по четко отработанному алгоритму, состоящему из следующих этапов:
Детальнее – https://narcolog-na-dom-voronezh00.ru/vyzov-narkologa-na-dom-voronezh
AlbertVal
30 Jul 25 at 3:10 pm
фільми 2025 безкоштовно дивитися фільми онлайн безкоштовно 2025
ua-bay-754
30 Jul 25 at 3:11 pm
I was recommended this website by my cousin. I’m not sure whether this post is written by him as
no one else know such detailed about my difficulty.
You’re wonderful! Thanks!
Visit my page – easiest internet for foreigners Hungary
easiest internet for foreigners Hungary
30 Jul 25 at 3:11 pm
прогнозы на хоккей с подробным анализом [url=https://luchshie-prognozy-na-khokkej6.ru/]https://luchshie-prognozy-na-khokkej6.ru/[/url] .
lychshie prognozi na hokkei_eaMi
30 Jul 25 at 3:13 pm
аренда яхты [url=http://www.yachts-charter-dubai.com]http://www.yachts-charter-dubai.com[/url] .
arenda yaht dybai_onSr
30 Jul 25 at 3:13 pm
https://clomidhubpharmacy.shop/# Clomid Hub
PatrickNeelp
30 Jul 25 at 3:13 pm
I don’t even know how I ended up here, but I thought this post was good.
I do not know who you are but certainly you are going to a famous blogger if you are not already 😉 Cheers!
Trade 350 App
30 Jul 25 at 3:17 pm
Actually no matter if someone doesn’t be aware of after that its up to other visitors
that they will help, so here it takes place.
Feel free to visit my web site; expat internet Hungary
expat internet Hungary
30 Jul 25 at 3:17 pm
I read tһis post completely regarding the difference of newest
and earlier technolоgies, it’s amazing articⅼe.
Taкe a look at my web site; opus Anglicanum
opus Anglicanum
30 Jul 25 at 3:18 pm
Incredibly individual friendly site. Enormous info available
on couple of clicks.
https://nysainfo.pl
https://nysainfo.pl
30 Jul 25 at 3:19 pm
кайтинг Кайт путешествия: Откройте для себя новые горизонты. Исследуйте экзотические кайт споты и наслаждайтесь красотой природы.
RamonLiata
30 Jul 25 at 3:23 pm
cheap generic prednisone: can i order prednisone – prednisone 40 mg
LarryBoymn
30 Jul 25 at 3:26 pm
Hi exceptional website! Does running a blog such as this require a massive amount work?
I have absolutely no expertise in computer programming however I had been hoping to
start my own blog in the near future. Anyhow, if
you have any ideas or tips for new blog owners please
share. I know this is off subject nevertheless I just had to ask.
Kudos!
Pusat4D platform analysis
30 Jul 25 at 3:30 pm
дивитися фільми без реклами новинки кіно 2025 дивитися безкоштовно
uakino-707
30 Jul 25 at 3:32 pm
Relief Meds USA: prednisone 200 mg tablets – Relief Meds USA
LarryBoymn
30 Jul 25 at 3:34 pm
It is perfect time to make some plans for the future and it’s time to be happy.
I have read this post and if I could I wish to suggest you few interesting things or tips.
Maybe you can write next articles referring to this article.
I desire to read even more things about it!
vibely 4d mascara reviews
30 Jul 25 at 3:39 pm
фільми онлайн без реклами новинки кіно 2025 дивитися безкоштовно
uakino-140
30 Jul 25 at 3:45 pm
Vous pouvez choisir des couleurs vives et des motifs élaborés pour un look plus décontracté, ou des couleurs
plus sobres et des lignes épurées pour un look plus sophistiqué.
casino bonus sans depot
30 Jul 25 at 3:46 pm
Les détails comme les manches bouffantes, les encolures bateau ou les dos nus étaient également très populaires à cette époque.
meilleur casino en ligne france
30 Jul 25 at 3:46 pm
Без медицинской помощи запой может перерасти в тяжёлую форму алкогольной интоксикации, вызывая серьёзные сбои в работе всех систем организма.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-arkhangelsk6.ru/]вывод из запоя на дому круглосуточно в архангельске[/url]
CharlesRam
30 Jul 25 at 3:53 pm
cost of prednisone 5mg tablets: order corticosteroids without prescription – anti-inflammatory steroids online
LarryBoymn
30 Jul 25 at 4:07 pm
В таких случаях своевременный вызов нарколога на дом позволяет быстро стабилизировать состояние больного и предотвратить тяжелые последствия.
Углубиться в тему – [url=https://narcolog-na-dom-novosibirsk00.ru/]врач нарколог на дом в новосибирске[/url]
DanielHah
30 Jul 25 at 4:09 pm
https://teletype.in/@alenacherny/gde_arendovat_auto_v_Sochi
https://teletype.in/@alenacherny/gde_arendovat_auto_v_Sochi
30 Jul 25 at 4:16 pm