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=http://frei-diplom6.ru/]купить диплом с занесением в реестр в мурманске[/url] .
Diplomi_whOl
22 Oct 25 at 1:28 pm
This information is worth everyone’s attention. How can I find out more?
adameve coupon
22 Oct 25 at 1:31 pm
top rated seo [url=http://top-10-seo-prodvizhenie.ru]top rated seo[/url] .
top 10 seo prodvijenie_lkKa
22 Oct 25 at 1:32 pm
Thank you for every other magnificent post. The place else may just anyone get
that type of info in such a perfect approach of writing?
I have a presentation next week, and I’m at the look for such info.
backlink
22 Oct 25 at 1:33 pm
продвижение сайтов сео топ [url=www.seo-prodvizhenie-reiting-kompanij.ru/]продвижение сайтов сео топ[/url] .
seo prodvijenie reiting kompanii_oost
22 Oct 25 at 1:34 pm
купить диплом в курске [url=http://www.rudik-diplom2.ru]купить диплом в курске[/url] .
Diplomi_czpi
22 Oct 25 at 1:34 pm
medtronik.ru инструкции, как активировать бонусные программы и акции
Aaronawads
22 Oct 25 at 1:36 pm
купить диплом в новороссийске [url=https://rudik-diplom11.ru]купить диплом в новороссийске[/url] .
Diplomi_tfMi
22 Oct 25 at 1:36 pm
купить диплом с занесением в реестр [url=https://www.rudik-diplom10.ru]купить диплом с занесением в реестр[/url] .
Diplomi_rsSa
22 Oct 25 at 1:37 pm
click through the following web page
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
click through the following web page
22 Oct 25 at 1:37 pm
Thanks for the auspicious writeup. It in fact was a
entertainment account it. Look advanced to far introduced agreeable from you!
However, how can we communicate?
https://awppgh.com/
Gudang Senjata
22 Oct 25 at 1:41 pm
купить диплом в железногорске [url=www.rudik-diplom12.ru/]www.rudik-diplom12.ru/[/url] .
Diplomi_ghPi
22 Oct 25 at 1:42 pm
Hello! This is my first comment here so I just wanted to give a
quick shout out and say I truly enjoy reading through your
blog posts. Can you recommend any other blogs/websites/forums that cover the same subjects?
Many thanks!
slot gacor
22 Oct 25 at 1:43 pm
seo оптимизация москва [url=https://seo-prodvizhenie-reiting-kompanij.ru/]seo оптимизация москва[/url] .
seo prodvijenie reiting kompanii_pxst
22 Oct 25 at 1:43 pm
как купить диплом с реестром [url=https://frei-diplom5.ru/]как купить диплом с реестром[/url] .
Diplomi_ddPa
22 Oct 25 at 1:44 pm
Ямочный ремонт дорог — это один из самых распространенных и оперативных способов восстановления поврежденных участков дорожного покрытия. Этот метод позволяет быстро и с минимальными затратами устранять дефекты, такие как ямы, трещины и выбоины на дорогах, обеспечивая безопасность движения и продлевая срок службы дороги.
Несмотря на то, что ямочный ремонт не является долгосрочным решением, он играет ключевую роль в поддержании дорожной инфраструктуры в рабочем состоянии, особенно в условиях интенсивного движения и сложных климатических условий. Нужна услуга: [url=http://www.bisound.com/forum/showthread.php?p=2865691#post2865691]ямочный ремонт дорог от приозводителя?[/url]
Zacherynub
22 Oct 25 at 1:45 pm
Remarkable! Its genuinely awesome piece of writing, I have got much clear idea on the topic
of from this article.
88aa
22 Oct 25 at 1:46 pm
Сериалы в хорошем качестве — когда картинка радует!
русские сериалы
русские сериалы
22 Oct 25 at 1:47 pm
купить легальный диплом [url=https://frei-diplom6.ru]купить легальный диплом[/url] .
Diplomi_kyOl
22 Oct 25 at 1:49 pm
купить диплом в магадане [url=https://rudik-diplom11.ru]купить диплом в магадане[/url] .
Diplomi_yjMi
22 Oct 25 at 1:49 pm
как купить проведенный диплом отзывы [url=http://www.frei-diplom3.ru]http://www.frei-diplom3.ru[/url] .
Diplomi_jkKt
22 Oct 25 at 1:50 pm
My spouse and I stumbled over here coming from a different web address and thought I might check things out.
I like what I see so i am just following you. Look forward to exploring your web page
yet again.
Wzrost Coinmark
22 Oct 25 at 1:50 pm
Клиника «Детокс» в Сочи предлагает услугу вывода из запоя в стационаре. Под наблюдением профессиональных врачей пациент получит необходимую медицинскую помощь и поддержку. Услуга доступна круглосуточно, анонимно и начинается от 2000 ?.
Выяснить больше – [url=https://vyvod-iz-zapoya-sochi23.ru/]вывод из запоя клиника[/url]
Keithskito
22 Oct 25 at 1:50 pm
купить диплом пту в реестре [url=https://frei-diplom1.ru/]купить диплом пту в реестре[/url] .
Diplomi_spOi
22 Oct 25 at 1:51 pm
как купить легально диплом о высшем образовании [url=http://frei-diplom5.ru/]как купить легально диплом о высшем образовании[/url] .
Diplomi_mePa
22 Oct 25 at 1:51 pm
«Частный Медик 24» в стационаре помогает начать жизнь заново — с чистого листа, без последствий запоя.
Подробнее – https://vyvod-iz-zapoya-v-stacionare22.ru
LarryWousH
22 Oct 25 at 1:51 pm
seo продвижение сайта в москве [url=www.seo-prodvizhenie-reiting-kompanij.ru]www.seo-prodvizhenie-reiting-kompanij.ru[/url] .
seo prodvijenie reiting kompanii_rlst
22 Oct 25 at 1:51 pm
В Нижнем Новгороде клиника «Частный Медик 24» предлагает вывод из запоя в стационаре с полным медицинским контролем и комфортом.
Разобраться лучше – [url=https://vyvod-iz-zapoya-v-stacionare23.ru/]вывод из запоя в стационаре клиника[/url]
AnthonyFum
22 Oct 25 at 1:52 pm
оптимизация и seo продвижение сайтов москва [url=www.seo-prodvizhenie-reiting-kompanij.ru]www.seo-prodvizhenie-reiting-kompanij.ru[/url] .
seo prodvijenie reiting kompanii_lyst
22 Oct 25 at 1:54 pm
купить диплом в батайске [url=www.rudik-diplom12.ru]www.rudik-diplom12.ru[/url] .
Diplomi_diPi
22 Oct 25 at 1:54 pm
Стриминговые смотреть сериалы онлайн бесплатно — это новый уровень, не
то что раньше!
смотреть сериалы онлайн бесплатно
22 Oct 25 at 1:55 pm
жте907? Вроде говорят, что пока не доступен – находиться на экспертизе… Откуда инфа?
https://mariupolgd.ru
Просто КОСМОС
Donaldmoire
22 Oct 25 at 1:55 pm
Viagra générique pas cher: Viagra sans ordonnance avis – SildГ©nafil 100 mg prix en pharmacie en France
AnthonySep
22 Oct 25 at 1:56 pm
купить диплом электрика техникум [url=https://frei-diplom7.ru]купить диплом электрика техникум[/url] .
Diplomi_dlei
22 Oct 25 at 1:58 pm
купить диплом техникума с занесением в реестр [url=frei-diplom3.ru]купить диплом техникума с занесением в реестр[/url] .
Diplomi_nfKt
22 Oct 25 at 1:58 pm
sportwetten lizenz kaufen
Here is my site: sichere wetten rechner (Carabinieri.I-learn.it)
Carabinieri.I-learn.it
22 Oct 25 at 1:59 pm
I like the helpful information you provide in your
articles. I’ll bookmark your weblog and check once more here frequently.
I’m reasonably certain I will be told plenty of new stuff proper right here!
Good luck for the next!
kontol
22 Oct 25 at 1:59 pm
Лечение запоя с помощью капельниц на дому в Красноярске – это эффективный способ борьбы с алкогольной зависимостью. Множество людей испытывают трудности от периодов запойного пьянстваи профессиональная поддержка становится необходимостью. Капельницы способствует в детоксикации организма, снижая симптомы абстиненции. Специализированные услуги нарколога включают не только капельницы, но и восстановление от алкоголячто важно для полного восстановления. Роль семьи является важной в лечении. Профилактика запойного состояния также важна для предотвращения рецидивов. Обращайтесь к профессиональному подходу на сайте vivod-iz-zapoya-krasnoyarsk021.ru и закажите помощь специалиста на дому.
narkologiyakrasnoyarskNeT
22 Oct 25 at 2:00 pm
https://britmedsuk.com/# NHS Viagra cost alternatives
LanceHek
22 Oct 25 at 2:02 pm
куплю диплом цена [url=rudik-diplom7.ru]куплю диплом цена[/url] .
Diplomi_cxPl
22 Oct 25 at 2:04 pm
Discover the best PS2 games in Canada! A curated list of timeless classics, including action, RPGs, and sports titles. Relive the nostalgia of top PlayStation 2 hits loved by gamers: official PS2 games resource Canada
GabrielLyday
22 Oct 25 at 2:04 pm
диплом о высшем образовании с проводкой купить [url=https://frei-diplom6.ru/]диплом о высшем образовании с проводкой купить[/url] .
Diplomi_utOl
22 Oct 25 at 2:04 pm
click through the following website page
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
click through the following website page
22 Oct 25 at 2:05 pm
Operation Game Canada: A classic, fun-filled board game where players test their precision by removing ailments from the patient without triggering the buzzer: play Operation game for free
GabrielLyday
22 Oct 25 at 2:06 pm
I love your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone
to do it for you? Plz respond as I’m looking to create my own blog and would like to
find out where u got this from. kudos
Rozoxfin
22 Oct 25 at 2:07 pm
seo продвижение рейтинг компаний [url=https://seo-prodvizhenie-reiting-kompanij.ru]seo продвижение рейтинг компаний[/url] .
seo prodvijenie reiting kompanii_srst
22 Oct 25 at 2:08 pm
купить диплом в екатеринбурге [url=rudik-diplom7.ru]купить диплом в екатеринбурге[/url] .
Diplomi_hbPl
22 Oct 25 at 2:11 pm
диплом колледжа купить с занесением в реестр [url=https://www.frei-diplom6.ru]диплом колледжа купить с занесением в реестр[/url] .
Diplomi_hrOl
22 Oct 25 at 2:11 pm
What’s up, just wanted to tell you, I liked this post. It was
helpful. Keep on posting!
AU 88
22 Oct 25 at 2:11 pm
купить диплом моряка [url=https://rudik-diplom2.ru]купить диплом моряка[/url] .
Diplomi_fgpi
22 Oct 25 at 2:14 pm