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=frei-diplom12.ru]frei-diplom12.ru[/url] .
Diplomi_vtPt
17 Oct 25 at 6:31 am
В этой статье вы найдете уникальные исторические пересечения с научными открытиями. Каждый абзац — это шаг к пониманию того, как наука и события прошлого создают основу для технологического будущего.
Как это работает — подробно – https://carolarodriguezdebauer.com/sobre-la-autora-2
Robertbum
17 Oct 25 at 6:31 am
купить диплом пту в реестре [url=http://frei-diplom2.ru]купить диплом пту в реестре[/url] .
Diplomi_qnEa
17 Oct 25 at 6:31 am
futuregoalsnetwork – I enjoy reading, content is inspiring without being overwhelming.
Clement Stum
17 Oct 25 at 6:35 am
купить диплом в соликамске [url=https://rudik-diplom7.ru/]купить диплом в соликамске[/url] .
Diplomi_psPl
17 Oct 25 at 6:36 am
купить диплом в биробиджане [url=https://rudik-diplom10.ru/]купить диплом в биробиджане[/url] .
Diplomi_neSa
17 Oct 25 at 6:37 am
Pretty! This has been a really wonderful article.
Thank you for supplying this info.
neue online casinos
17 Oct 25 at 6:38 am
купить диплом в гуково [url=www.rudik-diplom2.ru]купить диплом в гуково[/url] .
Diplomi_bjpi
17 Oct 25 at 6:39 am
https://t.me/Official_1xbet_1xbet/s/265
AlbertEnark
17 Oct 25 at 6:39 am
https://t.me/Official_1xbet_1xbet/s/696
AlbertEnark
17 Oct 25 at 6:40 am
https://plisio.net/fr/blog/ledger-nano-x
CameronJaisp
17 Oct 25 at 6:41 am
купить диплом колледжа с занесением в реестр в [url=www.frei-diplom3.ru/]купить диплом колледжа с занесением в реестр в[/url] .
Diplomi_rxKt
17 Oct 25 at 6:42 am
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Посмотреть всё – https://portalonbus.com.br/2023/10/11/coldplay-e-antigo-empresario-se-processam-por-valores-milionario
RolandToinc
17 Oct 25 at 6:42 am
купить свидетельство о заключении брака [url=www.rudik-diplom7.ru]купить свидетельство о заключении брака[/url] .
Diplomi_elPl
17 Oct 25 at 6:42 am
Register at glory casino online and receive bonuses on your first deposit on online casino games and slots right now!
Miguelhen
17 Oct 25 at 6:42 am
mostbet hu
mostbet hu
17 Oct 25 at 6:43 am
This website definitely has all of the information and facts I wanted concerning this subject and didn’t know who to ask.
Fairholt Cryptrix Anmeldelse
17 Oct 25 at 6:44 am
как купить диплом техникума в уфе [url=www.frei-diplom12.ru]как купить диплом техникума в уфе[/url] .
Diplomi_rvPt
17 Oct 25 at 6:45 am
https://t.me/Official_1xbet_1xbet/s/1125
AlbertEnark
17 Oct 25 at 6:46 am
купить диплом с занесением в реестр цена [url=http://www.frei-diplom2.ru]купить диплом с занесением в реестр цена[/url] .
Diplomi_xlEa
17 Oct 25 at 6:46 am
В этой статье представлен занимательный и актуальный контент, который заставит вас задуматься. Мы обсуждаем насущные вопросы и проблемы, а также освещаем истории, которые вдохновляют на действия и изменения. Узнайте, что стоит за событиями нашего времени!
Детали по клику – https://indivinejourneys.com/holi-festival-in-india
Donaldirofe
17 Oct 25 at 6:46 am
OMT’s interactive quizzes gamify learning, mɑking mathematics habit forming fоr Singapore trainees ɑnd
inspiring them to promote exceptional test qualities.
Experience versatile learning anytime, ɑnywhere tһrough OMT’s tһorough
online e-learning platform, including endless access tο video lessons and
interactive tests.
Сonsidered that mathematics plays ɑ critical role іn Singapore’ѕ financial development аnd development,
purchasing specialized math tuition gears ᥙp trainees ԝith thе analytical abilities required tߋ thrive іn a competitive landscape.
Ꮤith PSLE mathematics contributing ѕubstantially t᧐
total ratings, tuition supplies extra resources ⅼike model responses fօr
pattern recognition аnd algebraic thinking.
Linking mathematics ideas tο real-world circumstances
tһrough tuition deepens understanding, making O Level application-based concerns а lot moгe friendly.
Individualized junior college tuition helps bridge tһe space
frߋm О Level to A Level math, guaranteeing students adjust tօ the increased roughness and depth needed.
Distinctively, OMT enhances tһe MOE curriculum wіth a
personalized program featuring diagnostic assessments tο tailor
content tߋ every trainee’ѕ staminas.
Aesthetic aids ⅼike representations assist imagine ρroblems lor,
improving understanding ɑnd test performance.
Tuition reveals trainees t᧐ varied concern types, broadening tһeir preparedness for uncertain Singapore math
exams.
Ⅿy webpage … math tuition singapore (Vernita)
Vernita
17 Oct 25 at 6:48 am
купить диплом дорожного техникума в спб [url=https://frei-diplom7.ru]купить диплом дорожного техникума в спб[/url] .
Diplomi_iyei
17 Oct 25 at 6:48 am
где купить диплом техникума кого [url=http://frei-diplom9.ru]где купить диплом техникума кого[/url] .
Diplomi_jjea
17 Oct 25 at 6:52 am
Сначала администратор собирает ключевые данные: возраст и примерный вес, длительность употребления, описание симптомов, хронические заболевания, аллергии и принимаемые лекарства. По этой информации врач заранее продумывает схему инфузии и прогнозирует длительность процедуры.
Подробнее – [url=https://narkolog-na-dom-serpuhov6.ru/]narkolog-na-dom-kruglosutochno[/url]
BlakeKib
17 Oct 25 at 6:52 am
Хотите узнать больше о природе нашей страны? Присоединяйтесь к обсуждению.
По теме “Изучение ООПТ России: парки, заповедники, водоемы”, там просто кладезь информации.
Вот, делюсь ссылкой:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Жду ваших отзывов и вопросов по теме.
fixRow
17 Oct 25 at 6:55 am
диплом реестр купить [url=www.frei-diplom3.ru/]диплом реестр купить[/url] .
Diplomi_ynKt
17 Oct 25 at 6:56 am
Keiran Lee
Brentsek
17 Oct 25 at 6:57 am
Register at glory casino and receive bonuses on your first deposit on online casino games and slots right now!
Miguelhen
17 Oct 25 at 6:57 am
купить диплом в сарапуле [url=http://rudik-diplom2.ru]купить диплом в сарапуле[/url] .
Diplomi_uipi
17 Oct 25 at 6:58 am
https://zomi.net/post/216403_1win-new-promo-code-casino-fans-get-a-treat-with-1w500gift-1025-plus-400-free-sp.html
Bernardgef
17 Oct 25 at 6:59 am
купить диплом с занесением в реестр новокузнецке [url=https://frei-diplom1.ru]купить диплом с занесением в реестр новокузнецке[/url] .
Diplomi_fdOi
17 Oct 25 at 7:00 am
где купить диплом техникума одних [url=http://www.frei-diplom8.ru]где купить диплом техникума одних[/url] .
Diplomi_fusr
17 Oct 25 at 7:01 am
https://medicosur.shop/# mexico pharmacy
Hermandug
17 Oct 25 at 7:02 am
خرید سود سوز آور – قیمت تگزاپون – خرید بنزن
فرزانه یوسفی
17 Oct 25 at 7:06 am
купить диплом электрика [url=http://www.rudik-diplom2.ru]купить диплом электрика[/url] .
Diplomi_fupi
17 Oct 25 at 7:07 am
купить диплом украины с занесением в реестр [url=www.frei-diplom1.ru/]www.frei-diplom1.ru/[/url] .
Diplomi_wqOi
17 Oct 25 at 7:08 am
https://t.me/Official_1xbet_1xbet/s/1194
AlbertEnark
17 Oct 25 at 7:08 am
купить бланк диплома [url=rudik-diplom7.ru]купить бланк диплома[/url] .
Diplomi_jjPl
17 Oct 25 at 7:09 am
https://t.me/Official_1xbet_1xbet/s/923
AlbertEnark
17 Oct 25 at 7:09 am
купить диплом проведенный [url=www.frei-diplom2.ru]купить диплом проведенный[/url] .
Diplomi_ydEa
17 Oct 25 at 7:11 am
можно ли купить диплом колледжа [url=frei-diplom9.ru]frei-diplom9.ru[/url] .
Diplomi_fbea
17 Oct 25 at 7:11 am
Amazing things here. I am very happy to look your post.
Thank you a lot and I’m taking a look forward to touch you.
Will you please drop me a e-mail?
สล็อต888เว็บตรง
17 Oct 25 at 7:12 am
linebet download apk
linebet bonus
17 Oct 25 at 7:14 am
https://t.me/Official_1xbet_1xbet/s/66
AlbertEnark
17 Oct 25 at 7:14 am
купить речной диплом [url=http://www.rudik-diplom2.ru]купить речной диплом[/url] .
Diplomi_ippi
17 Oct 25 at 7:14 am
Hi, for all time i used to check webpage posts here early in the dawn, as
i enjoy to learn more and more.
Zoderovexis
17 Oct 25 at 7:14 am
https://t.me/Official_1xbet_1xbet/s/1104
AlbertEnark
17 Oct 25 at 7:14 am
купить диплом о высшем образовании с реестром [url=frei-diplom1.ru]купить диплом о высшем образовании с реестром[/url] .
Diplomi_qaOi
17 Oct 25 at 7:15 am
I love what you guys are up too. This kind of clever work and exposure!
Keep up the good works guys I’ve added you guys to our blogroll.
Vumon Capital
17 Oct 25 at 7:16 am