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://alloopt.ru]https://alloopt.ru[/url]
Спасибо за внимание! Надеюсь, вам было интересно.
fixRow
20 Oct 25 at 2:35 am
купить диплом в рубцовске [url=https://rudik-diplom15.ru/]https://rudik-diplom15.ru/[/url] .
Diplomi_tuPi
20 Oct 25 at 2:36 am
Bullish on $MTAUR coin for its referral and vesting perks. ICO phase’s low entry beats later prices. Whimsical gameplay hooks you instantly.
minotaurus ico
WilliamPargy
20 Oct 25 at 2:36 am
уколы от алкоголя на дому [url=https://narkolog-na-dom-1.ru/]https://narkolog-na-dom-1.ru/[/url] .
narkolog na dom_qpkt
20 Oct 25 at 2:37 am
Капельница от похмелья в Нижнем Новгороде — доступная и эффективная процедура для снятия симптомов интоксикации. Стоимость услуги начинается от 2?100??.
Разобраться лучше – [url=https://vyvod-iz-zapoya-nizhnij-novgorod12.ru/]наркологический вывод из запоя в нижний новгороде[/url]
Miltondiolo
20 Oct 25 at 2:38 am
can you get generic doxycycline without rx
doxycycline buy uk online
20 Oct 25 at 2:40 am
1win uz kazino [url=https://1win5510.ru]https://1win5510.ru[/url]
1win_uz_yksi
20 Oct 25 at 2:40 am
диплом колледжа купить в екатеринбурге [url=http://frei-diplom11.ru]http://frei-diplom11.ru[/url] .
Diplomi_jhsa
20 Oct 25 at 2:41 am
платный наркологический стационар [url=http://www.narkologicheskaya-klinika-20.ru]http://www.narkologicheskaya-klinika-20.ru[/url] .
narkologicheskaya klinika _vzPr
20 Oct 25 at 2:42 am
купить диплом техникума до 1996 года [url=https://frei-diplom9.ru]купить диплом техникума до 1996 года[/url] .
Diplomi_rbea
20 Oct 25 at 2:42 am
kraken официальный
кракен Москва
JamesDaync
20 Oct 25 at 2:43 am
купить диплом электрика [url=www.rudik-diplom6.ru]купить диплом электрика[/url] .
Diplomi_gfKr
20 Oct 25 at 2:43 am
купить диплом в ельце [url=https://rudik-diplom7.ru/]https://rudik-diplom7.ru/[/url] .
Diplomi_arPl
20 Oct 25 at 2:44 am
Celebrate your achievements: finishing a winning bet on our website [url=https://praqrado.com/download-the-1xbet-app-for-an-unmatched-betting/]https://praqrado.com/download-the-1xbet-app-for-an-unmatched-betting/[/url] money will be automatically transferred to balance.
Allisonken
20 Oct 25 at 2:45 am
нарколог психолог [url=http://narkologicheskaya-klinika-20.ru/]http://narkologicheskaya-klinika-20.ru/[/url] .
narkologicheskaya klinika _nsPr
20 Oct 25 at 2:46 am
1вин ios приложение [url=https://www.1win5510.ru]https://www.1win5510.ru[/url]
1win_uz_yesi
20 Oct 25 at 2:48 am
В Сочи стационар клиники «Детокс» предлагает комплексный вывод из запоя. Пациентам обеспечивают комфорт, безопасность и круглосуточный контроль.
Углубиться в тему – [url=https://vyvod-iz-zapoya-sochi23.ru/]вывод из запоя на дому круглосуточно в сочи[/url]
Gordontrive
20 Oct 25 at 2:48 am
диплом колледжа купить диплом юриста [url=http://frei-diplom9.ru/]http://frei-diplom9.ru/[/url] .
Diplomi_nkea
20 Oct 25 at 2:48 am
купить диплом техникума в самаре [url=https://frei-diplom8.ru/]купить диплом техникума в самаре[/url] .
Diplomi_ebsr
20 Oct 25 at 2:49 am
В «Частном Медике 24» в Самаре выход из запоя организуют поэтапно: диагностика, лечение, реабилитация.
Разобраться лучше – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]нарколог вывод из запоя в стационаре[/url]
GilbertCoeby
20 Oct 25 at 2:51 am
куплю диплом высшего образования [url=www.rudik-diplom7.ru/]куплю диплом высшего образования[/url] .
Diplomi_whPl
20 Oct 25 at 2:53 am
right here on 9signal
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
right here on 9signal
20 Oct 25 at 2:53 am
прогнозы на спорт с аналитикой [url=http://prognozy-ot-professionalov4.ru/]http://prognozy-ot-professionalov4.ru/[/url] .
prognozi ot professionalov_ukOr
20 Oct 25 at 2:53 am
купить диплом в саранске [url=rudik-diplom6.ru]купить диплом в саранске[/url] .
Diplomi_rwKr
20 Oct 25 at 2:54 am
1win [url=http://1win5510.ru]http://1win5510.ru[/url]
1win_uz_jjsi
20 Oct 25 at 2:56 am
Scale your operations safely! An antidetect browser is engineered specifically for multi-account management, allowing you to run separate profiles for social media, ads, or e-commerce without any cross-linking risk.
DouglasJasse
20 Oct 25 at 2:57 am
купить диплом фармацевта [url=http://rudik-diplom3.ru/]купить диплом фармацевта[/url] .
Diplomi_raei
20 Oct 25 at 2:57 am
диплом жд техникума купить в [url=http://frei-diplom8.ru/]диплом жд техникума купить в[/url] .
Diplomi_nhsr
20 Oct 25 at 2:57 am
купить диплом о высшем образовании с занесением в реестр в москве [url=http://www.frei-diplom6.ru]купить диплом о высшем образовании с занесением в реестр в москве[/url] .
Diplomi_owOl
20 Oct 25 at 2:59 am
купить диплом вуза [url=https://rudik-diplom7.ru/]купить диплом вуза[/url] .
Diplomi_fzPl
20 Oct 25 at 2:59 am
купить украинский диплом техникума [url=https://frei-diplom11.ru]купить украинский диплом техникума[/url] .
Diplomi_iasa
20 Oct 25 at 2:59 am
кракен vk5
кракен vk6
JamesDaync
20 Oct 25 at 3:00 am
Scale your operations safely! An antidetect browser is engineered specifically for multi-account management, allowing you to run separate profiles for social media, ads, or e-commerce without any cross-linking risk.
DouglasJasse
20 Oct 25 at 3:00 am
https://muckrack.com/person-27433392
Anthonycam
20 Oct 25 at 3:01 am
potenzmittel cialis: PotenzVital – cialis generika
RaymondNit
20 Oct 25 at 3:02 am
проект перепланировки стоимость москва [url=https://proekt-pereplanirovki-kvartiry11.ru/]https://proekt-pereplanirovki-kvartiry11.ru/[/url] .
proekt pereplanirovki kvartiri_amot
20 Oct 25 at 3:02 am
cialis 20 mg achat en ligne: livraison rapide et confidentielle – cialis sans ordonnance
JosephPseus
20 Oct 25 at 3:02 am
новости хоккея [url=http://sportivnye-novosti-2.ru]новости хоккея[/url] .
sportivnie novosti_lhma
20 Oct 25 at 3:03 am
Kaizenaire.ⅽom leads tһе pack іn curating deals f᧐r Singapore’s smart shoppers.
In Singapore’ѕ heart, shopping paradise ɡrows оn deals that thrill its people.
Scuba diving journeys tо nearby islands excitement underwater travelers
from Singapore, and bear іn mind to remɑin updated on Singapore’ѕ neѡest promotions and shopping deals.
Rye mɑkes easy females’ѕ clothing, valued by casual style enthusiasts in Singapore
fߋr tһeir relaxed үеt stylish designs.
Fraser and Neave creates drinks ⅼike 100PᒪUЅ аnd F&N cordials lor, cherished Ƅy Singaporeans fоr thеіr refreshing drinks Ԁuring heat leh.
SaladStop! assembles fresh salads ɑnd wraps, treasured ƅy fitness enthusiasts fօr personalized, nutritious meals ᧐n the fly.
Ꭰon’t Ƅe obsoleted leh, Kaizenaire.ϲom updates with nwwest discounts оne.
Feel free tօ visit my һomepage – Kaizenaire Promotions
Kaizenaire Promotions
20 Oct 25 at 3:03 am
Refresh Renovation Southwest Charlotte
1251 Arrow Piine Ɗr c121,
Charlotte, NC 28273, United Ѕtates
+19803517882
Project renovation management
Project renovation management
20 Oct 25 at 3:05 am
В Краснодаре клиника «Детокс» предлагает услугу выезда нарколога на дом. Быстро, безопасно, анонимно.
Получить дополнительную информацию – [url=https://narkolog-na-dom-krasnodar27.ru/]врач нарколог на дом[/url]
DanielNus
20 Oct 25 at 3:05 am
Стационарное лечение запоя в Воронеже помогает быстрее восстановить силы и вернуть ясность мышления.
Узнать больше – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh22.ru/]вывод из запоя в стационаре в воронеже[/url]
RichardJuids
20 Oct 25 at 3:06 am
Halo teman-teman! Artikel ini informatif dan mudah diikuti.
Buat yang mencari platform gaming dengan desain elegan dan fitur lengkap, saya rekomendasikan King7.
Selain punya reputasi bagus dan banyak dipakai, mereka juga
rutin kasih promo berjalan dengan proteksi kuat sehingga main terasa aman.
Aksesnya ringkas, navigasi intuitif, dan performa stabil.
Yang ingin cek bisa ke king7.
Terima kasih untuk kontennya; sukses selalu untuk blog ini!
king7
20 Oct 25 at 3:06 am
1вин лайв ставки [url=https://1win5510.ru/]https://1win5510.ru/[/url]
1win_uz_zfsi
20 Oct 25 at 3:06 am
Thanks very interesting blog!
Adam and Eve coupons
20 Oct 25 at 3:07 am
I visited various web pages however the audio feature for audio songs present at this web page is actually wonderful.
solar power water heater Malaysia
20 Oct 25 at 3:08 am
Great delivery. Sound arguments. Keep up the amazing work.
man with a van
20 Oct 25 at 3:08 am
[url=https://jili-bet.hashnode.dev/]jili casino[/url] or betting?
Joshuahic
20 Oct 25 at 3:09 am
диплом с внесением в реестр купить [url=https://www.frei-diplom3.ru]диплом с внесением в реестр купить[/url] .
Diplomi_vuKt
20 Oct 25 at 3:09 am
частные наркологические клиники в москве [url=www.narkologicheskaya-klinika-20.ru]www.narkologicheskaya-klinika-20.ru[/url] .
narkologicheskaya klinika _uoPr
20 Oct 25 at 3:09 am