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://frei-diplom9.ru/]как купить диплом в колледже[/url] .
Diplomi_htea
17 Oct 25 at 4:53 am
promo bet Don’t start betting without a valid betting promo code. Maximize your potential winnings with exclusive promotions, bonus funds, and risk-free bets. Act now!
Caseypeash
17 Oct 25 at 4:53 am
https://t.me/Official_1xbet_1xbet/s/198
AlbertEnark
17 Oct 25 at 4:55 am
https://t.me/Official_1xbet_1xbet/s/465
AlbertEnark
17 Oct 25 at 4:56 am
купить проведенный диплом одно [url=https://frei-diplom1.ru]купить проведенный диплом одно[/url] .
Diplomi_kdOi
17 Oct 25 at 4:57 am
купить диплом об окончании колледжа в екатеринбурге [url=https://frei-diplom12.ru]https://frei-diplom12.ru[/url] .
Diplomi_tyPt
17 Oct 25 at 4:58 am
generic Cialis online pharmacy: cialis – cialis
Andresstold
17 Oct 25 at 4:59 am
masturbate
Brentsek
17 Oct 25 at 5:02 am
Right here is the perfect web site for anyone who hopes
to find out about this topic. You realize a whole
lot its almost hard to argue with you (not that I really would want to…HaHa).
You certainly put a new spin on a topic that’s been written about
for many years. Excellent stuff, just great!
http://federalbureauinvestigation.5nx.ru/viewtopic.php?f=3&t=1704
17 Oct 25 at 5:04 am
купить диплом в кемерово [url=https://rudik-diplom2.ru/]купить диплом в кемерово[/url] .
Diplomi_mmpi
17 Oct 25 at 5:05 am
где купить диплом техникума кого [url=www.frei-diplom9.ru]где купить диплом техникума кого[/url] .
Diplomi_hkea
17 Oct 25 at 5:06 am
купить диплом техникума госзнак [url=https://frei-diplom7.ru/]купить диплом техникума госзнак[/url] .
Diplomi_ppei
17 Oct 25 at 5:08 am
купить диплом в черкесске [url=https://rudik-diplom7.ru]купить диплом в черкесске[/url] .
Diplomi_rkPl
17 Oct 25 at 5:10 am
Клиника принимает 24/7 без очередей: ночной блок специально настроен под «трудные часы», когда усиливаются панические мысли и реактивность пульса. Для тех, кому легче дома, выездная служба приводит помощь в знакомое пространство; если нужны короткие контрольные включения, применяем видеосвязь вечером (15–20 минут), чтобы корректно настроить ритуалы засыпания, дыхательные циклы и «световые правила». Маршрут фиксируется в единой карте наблюдения — этот документ доступен команде по ролям и защищает от «повторов заново», когда формат меняется (дом – амбулатория – стационар).
Разобраться лучше – http://narkologicheskaya-klinika-v-stavropole15.ru
BrianSoafe
17 Oct 25 at 5:10 am
Вы, случайно, не эксперт?
in the event that you deposit the minimum amount that meets the requirements (twenty bucks), [url=http://crown-green-casino.org/]crowngreen casino[/url] you will receive 15 dollars of bonus money to personal account at gambling establishment.
Kiameery
17 Oct 25 at 5:12 am
купить диплом украина с занесением в реестр [url=https://www.frei-diplom1.ru]https://www.frei-diplom1.ru[/url] .
Diplomi_zfOi
17 Oct 25 at 5:14 am
Kaizenaire.com stands tall witһ Singapore’ѕ ideal shopping deals ɑnd promotions.
Singapore stands аpɑrt as a shopping paradise, ѡhere Singaporeans’ excitement for deals ɑnd promotions knoѡs
no bounds.
Reviewing novels at cozy collections рrovides а peaceful escape fоr bookish Singaporeans, and keеp in mind tο stay updated on Singapore’s most current promotions ɑnd shopping deals.
Adidas ɡives sportswear and sneakers, cherished ƅʏ Singaporeans fߋr tһeir elegant activewear and recommendation ƅy local athletes.
Ginlee crafts classic females’ѕ wear with toρ quality
materials leh, preferred ƅy sophisticated Singaporeans f᧐r their
enduring design оne.
Aalst Chocolate crafts Belgian-inspired chocolates, enjoyed fоr smooth, indulgent bars ɑnd neighborhood developments.
Eh, wһy pay fuⅼl rate mah, regularly search Kaizenaire.ⅽom for the ѵery beѕt
promotions lah.
Check ⲟut my site: singapore promotions
singapore promotions
17 Oct 25 at 5:14 am
Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
Что ещё нужно знать? – https://royaltea.in/benefits-of-indian-spices-in-your-tea
Jamesmow
17 Oct 25 at 5:16 am
https://t.me/Official_1xbet_1xbet/s/911
AlbertEnark
17 Oct 25 at 5:17 am
купить диплом медсестры [url=https://frei-diplom13.ru]купить диплом медсестры[/url] .
Diplomi_abkt
17 Oct 25 at 5:17 am
https://t.me/Official_1xbet_1xbet/s/61
AlbertEnark
17 Oct 25 at 5:18 am
купить диплом колледжа отзывы [url=http://frei-diplom9.ru/]http://frei-diplom9.ru/[/url] .
Diplomi_voea
17 Oct 25 at 5:19 am
купить диплом техникума с реестром [url=https://www.frei-diplom1.ru]купить диплом техникума с реестром[/url] .
Diplomi_idOi
17 Oct 25 at 5:22 am
What are the benefits of yoga
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
What are the benefits of yoga
17 Oct 25 at 5:22 am
купить диплом об окончании техникума в москве [url=https://frei-diplom12.ru]купить диплом об окончании техникума в москве[/url] .
Diplomi_gvPt
17 Oct 25 at 5:22 am
https://t.me/Official_1xbet_1xbet/s/579
AlbertEnark
17 Oct 25 at 5:23 am
Автоматизация избавляет от рутины актуальные зеркала kraken kraken рабочая ссылка onion сайт kraken onion kraken darknet
RichardPep
17 Oct 25 at 5:23 am
https://t.me/Official_1xbet_1xbet/s/958
AlbertEnark
17 Oct 25 at 5:24 am
купить диплом во владивостоке [url=http://www.rudik-diplom7.ru]купить диплом во владивостоке[/url] .
Diplomi_lqPl
17 Oct 25 at 5:24 am
Please let me know if you’re looking for a article writer for your site.
You have some really great posts and I believe I would be a good asset.
If you ever want to take some of the load off, I’d really like to write some articles for your blog in exchange for a link back to mine.
Please blast me an e-mail if interested. Many thanks!
local roofers Phoenix AZ
17 Oct 25 at 5:26 am
купить диплом техникума 1997 [url=http://www.frei-diplom8.ru]купить диплом техникума 1997[/url] .
Diplomi_tdsr
17 Oct 25 at 5:27 am
купить диплом ижевск с занесением в реестр [url=https://www.frei-diplom1.ru]купить диплом ижевск с занесением в реестр[/url] .
Diplomi_qfOi
17 Oct 25 at 5:27 am
Ранняя врачебная помощь не только снижает тяжесть абстинентного синдрома, но и предотвращает опасные осложнения, даёт шанс пациенту быстрее вернуться к обычной жизни, а его близким — обрести уверенность в завтрашнем дне.
Узнать больше – https://vyvod-iz-zapoya-shchelkovo6.ru/vyvod-iz-zapoya-na-domu-v-shchelkovo/
VictorVok
17 Oct 25 at 5:29 am
купить диплом в горном колледже [url=http://frei-diplom12.ru]http://frei-diplom12.ru[/url] .
Diplomi_ukPt
17 Oct 25 at 5:31 am
Just swapped BNB for $MTAUR—smooth on BSC. Referral rewards motivate sharing. Game’s power-ups via tokens strategic.
minotaurus coin
WilliamPargy
17 Oct 25 at 5:34 am
Hello Dear, are you actually visiting this website daily, if so then you will definitely obtain good knowledge.
riobet casino зеркало
17 Oct 25 at 5:36 am
https://plisio.net/ko/blog/what-is-a-crypto-layer-2
CameronJaisp
17 Oct 25 at 5:36 am
Bullish on Minotaurus ICO’s viral referrals. $MTAUR utility strong. Sector expansion aids.
mtaur token
WilliamPargy
17 Oct 25 at 5:38 am
BearPrint — типография полного цикла в Москве: цифровая и офсетная печать визиток, листовок, буклетов, каталогов, этикеток и упаковочных шуберов, плюс широкоформат и постпечатная обработка. Команда подключается от дизайна до сборки тиража, работает срочно и аккуратно, с доставкой по городу. Посмотрите услуги и контакты на https://bearprint.pro/ — там же форма «Свяжитесь со мной», WhatsApp и Telegram. Чёткое качество, понятные сроки и цены ниже рынка на сопоставимом уровне.
jukyveRop
17 Oct 25 at 5:38 am
купить диплом штукатура [url=https://www.rudik-diplom7.ru]https://www.rudik-diplom7.ru[/url] .
Diplomi_quPl
17 Oct 25 at 5:38 am
linebet bd app download
linebet partner
17 Oct 25 at 5:39 am
Nacho Vidal
Brentsek
17 Oct 25 at 5:39 am
возможно ли купить диплом техникума [url=http://frei-diplom8.ru/]возможно ли купить диплом техникума[/url] .
Diplomi_lmsr
17 Oct 25 at 5:41 am
Very quickly this web site will be famous amid all blog viewers, due to it’s pleasant
articles or reviews
turkish visa australia
17 Oct 25 at 5:41 am
Register at glory game casino and receive bonuses on your first deposit on online casino games and slots right now!
Miguelhen
17 Oct 25 at 5:42 am
http://sm.co.kr/bbs/board.php?bo_table=free&wr_id=3339634
Leroypap
17 Oct 25 at 5:43 am
купить свидетельство о рождении [url=https://www.rudik-diplom10.ru]купить свидетельство о рождении[/url] .
Diplomi_lrSa
17 Oct 25 at 5:45 am
https://t.me/Official_1xbet_1xbet/s/599
AlbertEnark
17 Oct 25 at 5:46 am
купить диплом о средне специальном образовании реестр [url=http://frei-diplom1.ru]купить диплом о средне специальном образовании реестр[/url] .
Diplomi_luOi
17 Oct 25 at 5:47 am
Если на любом этапе проявляется нестабильность давления/ритма, падает сатурация или ухудшается контакт, врач эскалирует формат немедленно. Важно: в стационаре мы продолжаем тот же курс, не «перепридумывая» его с нуля — благодаря единой карте наблюдения теряется меньше времени и сил.
Получить больше информации – [url=https://vyvod-iz-zapoya-stavropol15.ru/]наркологический вывод из запоя[/url]
Ronaldgag
17 Oct 25 at 5:47 am