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!
*Седативные компоненты применяются по строгим показаниям, с мониторингом дыхания и сатурации.
Подробнее тут – [url=https://vyvod-iz-zapoya-ulan-ude0.ru/]вывод из запоя с выездом в улан-удэ[/url]
LouisDof
14 Oct 25 at 9:01 pm
электрокарниз двухрядный цена [url=https://www.elektrokarnizy797.ru]https://www.elektrokarnizy797.ru[/url] .
elektrokarnizi_zuMl
14 Oct 25 at 9:01 pm
Ich bin absolut hingerissen von NV Casino, es fuhlt sich an wie ein Wirbel aus Freude. Das Angebot an Spielen ist phanomenal, inklusive aufregender Sportwetten. Der Kundensupport ist hervorragend, garantiert hochwertige Hilfe. Die Auszahlungen sind ultraschnell, obwohl zusatzliche Freispiele waren toll. Zum Abschluss, NV Casino garantiert Top-Unterhaltung fur Krypto-Liebhaber ! Daruber hinaus die Oberflache ist intuitiv und stylish, gibt Lust auf mehr.
playnvcasino.de|
PhantomVaultE6zef
14 Oct 25 at 9:02 pm
http://swiatnastolatek.phorum.pl/viewtopic.php?p=603494#603494
faswkie
14 Oct 25 at 9:03 pm
потолки натяжные в самаре [url=natyazhnye-potolki-samara-1.ru]natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_lhor
14 Oct 25 at 9:05 pm
натяжной потолок в самаре [url=http://natyazhnye-potolki-samara-2.ru/]натяжной потолок в самаре[/url] .
natyajnie potolki samara_naPi
14 Oct 25 at 9:05 pm
Sou viciado em BETesporte Casino, e uma plataforma que pulsa com emocao atletica. A variedade de titulos e impressionante, suportando jogos adaptados para criptos. Fortalece seu saldo inicial. O acompanhamento e impecavel, com suporte preciso e rapido. Os saques sao rapidos como um sprint, no entanto recompensas extras seriam um hat-trick. No geral, BETesporte Casino oferece uma experiencia inesquecivel para fas de cassino online ! Tambem a navegacao e intuitiva e rapida, facilita uma imersao total. Outro destaque os eventos comunitarios envolventes, fortalece o senso de comunidade.
Ver o site|
FutebolFogoM4zef
14 Oct 25 at 9:08 pm
натяжные потолки сайт [url=https://stretch-ceilings-samara.ru]https://stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_jjkl
14 Oct 25 at 9:08 pm
купить диплом медсестры [url=http://frei-diplom15.ru]купить диплом медсестры[/url] .
Diplomi_owoi
14 Oct 25 at 9:09 pm
потолочник натяжные потолки самара [url=https://stretch-ceilings-samara-1.ru/]stretch-ceilings-samara-1.ru[/url] .
natyajnie potolki samara_rwsl
14 Oct 25 at 9:11 pm
согласование перепланировки нежилого помещения в москве [url=http://pereplanirovka-nezhilogo-pomeshcheniya9.ru/]http://pereplanirovka-nezhilogo-pomeshcheniya9.ru/[/url] .
pereplanirovka nejilogo pomesheniya_mnKl
14 Oct 25 at 9:13 pm
купить диплом в армавире [url=https://rudik-diplom15.ru/]купить диплом в армавире[/url] .
Diplomi_bhPi
14 Oct 25 at 9:13 pm
https://yourbookmarklist.com/story20615264/1xbet-promo-codes-bonuses
qccmcts
14 Oct 25 at 9:13 pm
Когда проблемы с алкоголизмом достигают критической точки, оперативное вмешательство становится жизненно необходимым. В Мариуполе квалифицированные наркологи оказывают помощь на дому, обеспечивая оперативную детоксикацию организма, стабилизацию жизненно важных показателей и психологическую поддержку. Такой формат лечения позволяет пациенту получить качественную медицинскую помощь в привычной домашней обстановке, сохраняя конфиденциальность и минимизируя стресс, связанный с посещением стационара.
Получить больше информации – https://narcolog-na-dom-mariupol0.ru
DonaldSKYNC
14 Oct 25 at 9:14 pm
Your style is very unique in comparison to other folks
I have read stuff from. Thank you for posting when you’ve got
the opportunity, Guess I’ll just book mark this web site.
lemon perfume
14 Oct 25 at 9:15 pm
Домашняя помощь — это не “облегченная версия” клиники. Команда «Балтийский МедЦентр» использует переносное оборудование и стандартизированные протоколы, позволяющие воспроизвести критически важные этапы стационарного вмешательства в условиях квартиры или частного дома. Врач заранее получает от оператора структурированный опросник по симптомам и сопутствующим заболеваниям, подбирает базовую схему инфузий, проверяет возможные лекарственные взаимодействия и берет с собой расширенный набор медикаментов. По прибытии специалист заново оценивает состояние и при необходимости корректирует назначения, ориентируясь на жизненные показатели, данные экспресс-диагностики и неврологический статус.
Подробнее тут – [url=https://narcolog-na-dom-kaliningrad0.ru/]врач нарколог на дом калининград[/url]
Philliprob
14 Oct 25 at 9:17 pm
BJ88 대한민국에 오신 것을 환영합니다 – 당신의 승리,
전액 지급. 지금 바로 매력적인 보너스를 받고, 최고의 게임을 즐기며, 믿을
수 있고 편리한 온라인 베팅 경험을 시작하세요!
전액 지급
14 Oct 25 at 9:17 pm
wetten spiel
Visit my homepage: wettquoten bielefeld stuttgart (https://demo.wpemailmanager.com)
https://demo.wpemailmanager.com
14 Oct 25 at 9:18 pm
Hey! This post couldn’t be written any better!
Reading this post reminds me of my good old room mate!
He always kept chatting about this. I will forward this post to him.
Pretty sure he will have a good read. Thanks for sharing!
Winning soccer tips
14 Oct 25 at 9:19 pm
потолочкин натяжные потолки отзывы клиентов самара [url=www.natyazhnye-potolki-samara-2.ru/]www.natyazhnye-potolki-samara-2.ru/[/url] .
natyajnie potolki samara_odPi
14 Oct 25 at 9:20 pm
В «АльтерМед» используются самые актуальные технологии, прошедшие проверку временем и доказавшие эффективность в тысячах клинических случаев. Выбор методики зависит от тяжести зависимости, состояния здоровья, наличия хронических заболеваний, прошлых попыток лечения и психологической мотивации пациента.
Узнать больше – [url=https://kodirovanie-ot-alkogolizma-dolgoprudnyj6.ru/]medikamentoznoe-kodirovanie-ot-alkogolizma-dolgoprudnyj[/url]
ArthurKalse
14 Oct 25 at 9:21 pm
все самое лучшее тут: https://9xc.ru/udalennyj-dostup-k-mediczinskoj-pomoshhi-vozmozhnost-byt-zdorovym-na-rasstoyanii/
JefferyADOTS
14 Oct 25 at 9:22 pm
потолочкин ру самара [url=http://www.stretch-ceilings-samara-1.ru]http://www.stretch-ceilings-samara-1.ru[/url] .
natyajnie potolki samara_qksl
14 Oct 25 at 9:22 pm
натяжные потолки официальный [url=stretch-ceilings-samara.ru]stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_rikl
14 Oct 25 at 9:22 pm
потолочник [url=http://www.natyazhnye-potolki-samara-1.ru]http://www.natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_ztor
14 Oct 25 at 9:23 pm
I’m gone to convey my little brother, that he should also pay a quick visit this blog on regular basis to obtain updated from most up-to-date reports.
сайт leebet casino
GichardMam
14 Oct 25 at 9:23 pm
best games
Brentsek
14 Oct 25 at 9:23 pm
купить диплом техникума с занесением пять плюс [url=frei-diplom9.ru]купить диплом техникума с занесением пять плюс[/url] .
Diplomi_rvea
14 Oct 25 at 9:24 pm
Алкоголизм — это заболевание, которое разрушает не только физическое здоровье, но и личность человека, отношения в семье, профессиональную и социальную жизнь. На определённом этапе стандартные методы поддержки оказываются недостаточными, и именно тогда встает вопрос о профессиональном вмешательстве. В наркологической клинике «Трезвая Линия» в Коломне кодирование стало одним из наиболее востребованных и эффективных решений для закрепления трезвости, создания дополнительной мотивации и защиты от рецидивов. Процедура проводится строго индивидуально, с учётом медицинских показаний, психоэмоционального состояния пациента и длительности зависимости.
Разобраться лучше – http://kodirovanie-ot-alkogolizma-kolomna6.ru/kodirovanie-ot-alkogolizma-telefon-v-kolomne/
Rodneybeany
14 Oct 25 at 9:26 pm
Чтобы делать ставки, нужно пополнить баланс, а процедура
внесения депозита доступна только тем, у кого есть подтвержденная
учетная запись на сайте.
бонусы кэт казино
14 Oct 25 at 9:27 pm
Cleaning Service Amsterdam-Centrum is expert in commercial cleaning
and operates in the Tuindorp Nieuwendam area in Amsterdam.
Tuindorp Nieuwendam, located at approximately 52.3840° N latitude and 4.9170° E longitude, is a residential area known for its blend of small businesses and community offices.
With a population of about 10,000 residents, the area hosts various commercial spaces that
demand professional cleaning to maintain hygiene and productivity standards.
Cleaning Service Amsterdam-Centrum appreciates the importance of maintaining a clean office environment in such a community, ensuring workplaces are
sanitized and tidy for employees and clients alike.
Tuindorp Nieuwendam includes key points of interest such as the Nieuwendammerdijk shopping street and local business centers, which often see high foot traffic.
Cleaning Service Amsterdam-Centrum’s knowledge helps them address the unique cleaning needs of these commercial hubs by offering tailored office cleaning schedules that limit disruption. Their service coverage makes certain that businesses
gain from thorough cleaning practices, promoting a healthy workspace in this vibrant
Amsterdam neighborhood.
Office Floor Cleaning
14 Oct 25 at 9:31 pm
потолочкин ру самара [url=stretch-ceilings-samara.ru]stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_hakl
14 Oct 25 at 9:32 pm
I loved as much as you’ll receive carried out right here.
The sketch is tasteful, your authored subject matter stylish.
nonetheless, you command get bought an impatience over that you wish be delivering the
following. unwell unquestionably come more formerly again since exactly the same nearly very often inside case you shield this increase.
Какие поломки встречаются у холодильников
14 Oct 25 at 9:32 pm
купить диплом в канске [url=www.rudik-diplom14.ru]купить диплом в канске[/url] .
Diplomi_gdea
14 Oct 25 at 9:33 pm
потолочкин ру натяжные потолки отзывы [url=natyazhnye-potolki-samara-1.ru]natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_dror
14 Oct 25 at 9:33 pm
купить диплом в черкесске [url=http://www.rudik-diplom6.ru]купить диплом в черкесске[/url] .
Diplomi_jgKr
14 Oct 25 at 9:34 pm
потолочники [url=https://stretch-ceilings-samara.ru/]stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_mwkl
14 Oct 25 at 9:34 pm
купить диплом в салавате [url=www.rudik-diplom15.ru/]купить диплом в салавате[/url] .
Diplomi_czPi
14 Oct 25 at 9:35 pm
автоматический карниз для штор [url=www.elektrokarnizy797.ru]www.elektrokarnizy797.ru[/url] .
elektrokarnizi_wbMl
14 Oct 25 at 9:36 pm
потолки натяжные в самаре [url=https://www.stretch-ceilings-samara-1.ru]https://www.stretch-ceilings-samara-1.ru[/url] .
natyajnie potolki samara_ufsl
14 Oct 25 at 9:37 pm
потолочкин потолки натяжные [url=https://natyazhnye-potolki-samara-2.ru/]natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_ggPi
14 Oct 25 at 9:39 pm
потолочкин натяжные потолки отзывы клиентов самара [url=http://stretch-ceilings-samara.ru/]http://stretch-ceilings-samara.ru/[/url] .
natyajnie potolki samara_uukl
14 Oct 25 at 9:41 pm
куплю диплом младшей медсестры [url=http://frei-diplom13.ru]http://frei-diplom13.ru[/url] .
Diplomi_cekt
14 Oct 25 at 9:42 pm
Minotaurus token’s DAO governance empowers users. Presale’s multi-crypto support widens access. Battling obstacles feels epic.
minotaurus presale
WilliamPargy
14 Oct 25 at 9:43 pm
потолочник натяжные потолки отзывы [url=http://natyazhnye-potolki-samara-1.ru/]http://natyazhnye-potolki-samara-1.ru/[/url] .
natyajnie potolki samara_rxor
14 Oct 25 at 9:44 pm
You really make it appear so easy with your presentation but I
in finding this topic to be really one thing which I
think I might by no means understand. It kind of feels too complicated and very vast
for me. I’m having a look forward to your subsequent put up, I will
attempt to get the cling of it!
Nhà cái 79KING
14 Oct 25 at 9:45 pm
Hello! I could have sworn I’ve been to this blog before but after checking through some of the post I realized it’s new
to me. Nonetheless, I’m definitely happy I found it and I’ll be bookmarking and checking
back often!
Open link
14 Oct 25 at 9:45 pm
потолочкин в каждый дом [url=http://natyazhnye-potolki-samara-1.ru]http://natyazhnye-potolki-samara-1.ru[/url] .
natyajnie potolki samara_fuor
14 Oct 25 at 9:46 pm
купить диплом массажиста [url=http://rudik-diplom7.ru]купить диплом массажиста[/url] .
Diplomi_asPl
14 Oct 25 at 9:47 pm
E28BET Việt Nam – Cá cược minh bạch, nạp
rút siêu tốc, ưu đãi VIP khủng. Chơi ngay Thể thao, Casino, Slot đỉnh cao.
Đăng ký và nhận thưởng ngay hôm nay!
thanh toán 100%
14 Oct 25 at 9:48 pm