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!
https://purebeautyoutlet.bond/
Wava Yokiel
21 Oct 25 at 10:38 am
купить диплом ижевск с занесением в реестр [url=http://www.frei-diplom4.ru]купить диплом ижевск с занесением в реестр[/url] .
Diplomi_hmOl
21 Oct 25 at 10:39 am
classyhomegoods.bond – Would love to see customer reviews to build trust in the items.
Hallie Spohn
21 Oct 25 at 10:40 am
Виртуальные номера
Antoniooscig
21 Oct 25 at 10:40 am
smarttradingmentor.bond – Just discovered this site, looks promising for trading guidance.
Rafael Marrujo
21 Oct 25 at 10:41 am
At this time it looks like Drupal is the best blogging platform available right now.
(from what I’ve read) Is that what you are
using on your blog?
medali303
21 Oct 25 at 10:41 am
купить диплом эколога [url=https://rudik-diplom11.ru/]https://rudik-diplom11.ru/[/url] .
Diplomi_kwMi
21 Oct 25 at 10:43 am
купить диплом швеи [url=https://rudik-diplom4.ru]купить диплом швеи[/url] .
Diplomi_juOr
21 Oct 25 at 10:43 am
купить диплом занесенный реестр [url=https://www.frei-diplom5.ru]купить диплом занесенный реестр[/url] .
Diplomi_ohPa
21 Oct 25 at 10:43 am
Minotaurus coin’s audits by top firms reassure. Presale stage savings massive. Customizations await.
minotaurus ico
WilliamPargy
21 Oct 25 at 10:44 am
купить диплом в чайковском [url=www.rudik-diplom10.ru]купить диплом в чайковском[/url] .
Diplomi_mzSa
21 Oct 25 at 10:46 am
kraken обмен
кракен ios
JamesDaync
21 Oct 25 at 10:47 am
купить диплом с реестром красноярск [url=http://frei-diplom4.ru/]купить диплом с реестром красноярск[/url] .
Diplomi_hpOl
21 Oct 25 at 10:47 am
купить диплом фитнес инструктора [url=rudik-diplom3.ru]купить диплом фитнес инструктора[/url] .
Diplomi_tdei
21 Oct 25 at 10:47 am
диплом техникум где купить [url=www.frei-diplom10.ru]диплом техникум где купить[/url] .
Diplomi_yhEa
21 Oct 25 at 10:48 am
сео продвижения поддержка сайта [url=http://reiting-runeta-seo.ru]http://reiting-runeta-seo.ru[/url] .
reiting ryneta seo_vhma
21 Oct 25 at 10:48 am
Amo a energia selvagem de PlayPIX Casino, sinto um pulsar selvagem. A selecao de jogos e fenomenal, com slots de design inovador. Fortalece seu saldo inicial. A assistencia e eficiente e amigavel, oferecendo respostas claras. Os pagamentos sao seguros e fluidos, no entanto ofertas mais generosas seriam bem-vindas. Para finalizar, PlayPIX Casino oferece uma experiencia memoravel para amantes de emocoes fortes ! Adicionalmente o design e moderno e vibrante, tornando cada sessao mais vibrante. Outro destaque o programa VIP com niveis exclusivos, assegura transacoes confiaveis.
Clique agora|
JungleVibeK8zef
21 Oct 25 at 10:50 am
I’ve been exploring for a bit for any high-quality articles or weblog posts on this sort of space .
Exploring in Yahoo I finally stumbled upon this site.
Reading this info So i’m happy to exhibit that
I’ve an incredibly excellent uncanny feeling I discovered exactly what I needed.
I most undoubtedly will make certain to do not disregard this site and give it a
look on a constant basis.
Prestine glass solutions LLc
21 Oct 25 at 10:51 am
Привет всем!
University of Masherova in Vitebsk offers a variety of educational programs in the fields of arts, humanities, and natural sciences. Students have the opportunity to receive a quality education using modern teaching methods and infrastructure. The university actively supports students’ scientific and cultural initiatives, promoting their creative and professional development.
Полная информация по ссылке – https://vsu.by/studentam/vakantnye-byudzhetnye-mesta.html
VSU recruitment for the I and II stages of higher education, sale, benefits for entering university
еЌљеЈ«з ”з©¶з”џиЇѕзЁ‹, [url=https://vsu.by/en/university/about-belarus.html]ABOUT VSU.by [/url], VSU named P.M. Masherov
Удачи и успехов в учебе!
KeithAligo
21 Oct 25 at 10:51 am
kraken сайт
кракен сайт
JamesDaync
21 Oct 25 at 10:53 am
Hey there just wanted to give you a quick heads up.
The text in your article seem to be running off the screen in Chrome.
I’m not sure if this is a format issue or something to do with internet browser compatibility but I thought I’d post to let you know.
The design and style look great though! Hope you get the
issue fixed soon. Thanks
bet888.plus
21 Oct 25 at 10:54 am
купить диплом в кемерово [url=http://www.rudik-diplom3.ru]купить диплом в кемерово[/url] .
Diplomi_piei
21 Oct 25 at 10:57 am
купить диплом с занесением в реестр в иркутске [url=www.frei-diplom4.ru]купить диплом с занесением в реестр в иркутске[/url] .
Diplomi_udOl
21 Oct 25 at 10:58 am
купить диплом в первоуральске [url=www.rudik-diplom4.ru]www.rudik-diplom4.ru[/url] .
Diplomi_opOr
21 Oct 25 at 10:58 am
купить диплом в волгодонске [url=https://rudik-diplom10.ru]купить диплом в волгодонске[/url] .
Diplomi_vnSa
21 Oct 25 at 10:59 am
рейтинг рунета сео [url=https://reiting-seo-agentstv.ru]https://reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_izsa
21 Oct 25 at 11:00 am
компания seo [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_yeKt
21 Oct 25 at 11:00 am
рейтинг агентств по seo [url=https://www.luchshie-digital-agencstva.ru]рейтинг агентств по seo[/url] .
lychshie digital agentstva_vdoi
21 Oct 25 at 11:00 am
Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
Изучить материалы по теме – https://kec.ind.in/2017/01/11/enterprise-performance-management-epm-for-santa-claus-inc-2-2
Sheldonhog
21 Oct 25 at 11:02 am
pin up aviator strategiyasi [url=http://pinup5007.ru/]pin up aviator strategiyasi[/url]
pin_up_uz_tusr
21 Oct 25 at 11:03 am
купить диплом медсестры [url=http://frei-diplom13.ru/]купить диплом медсестры[/url] .
Diplomi_cdkt
21 Oct 25 at 11:05 am
как купить диплом с занесением в реестр [url=http://frei-diplom5.ru]как купить диплом с занесением в реестр[/url] .
Diplomi_mnPa
21 Oct 25 at 11:05 am
купить диплом с занесением в реестр [url=rudik-diplom11.ru]купить диплом с занесением в реестр[/url] .
Diplomi_qlMi
21 Oct 25 at 11:05 am
продвижение сайтов поисковых системах москва [url=www.reiting-seo-agentstv-moskvy.ru/]www.reiting-seo-agentstv-moskvy.ru/[/url] .
reiting seo agentstv moskvi_viMl
21 Oct 25 at 11:06 am
купить диплом в самаре [url=rudik-diplom4.ru]купить диплом в самаре[/url] .
Diplomi_acOr
21 Oct 25 at 11:06 am
купить диплом в евпатории [url=http://rudik-diplom3.ru]купить диплом в евпатории[/url] .
Diplomi_ioei
21 Oct 25 at 11:09 am
Приятно видеть такую красивую и обаятельную девушку, которая одновременно делает массаж искусно и с заботой. Каждое движение расслабляет мышцы и дарит эмоциональное удовольствие. Вышел полностью обновлённым и с отличным настроением. Попробуйте, проститутки цена нск, https://sibirka.com/. Девушки внимательные и красивые, рекомендую.
Bobbyham
21 Oct 25 at 11:09 am
компании занимающиеся продвижением сайтов [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_ffKt
21 Oct 25 at 11:10 am
best seo agency [url=https://www.reiting-runeta-seo.ru]https://www.reiting-runeta-seo.ru[/url] .
reiting ryneta seo_jbma
21 Oct 25 at 11:13 am
где купить дипломы медсестры [url=frei-diplom13.ru]где купить дипломы медсестры[/url] .
Diplomi_vekt
21 Oct 25 at 11:13 am
Вообщем так, с момента отправки из курьерской службы до рук курьера в нашем городе прошло 3 дня, забрал я значительно позже, но это не суть.
Онлайн магазин – купить мефедрон, кокаин, бошки
заказывали реагент jv 61, брали 15 гр, с данным продовцом работаю с 11 года, сейчас регу тянул на зону, в целом все хорошо как обычно какачество соответствует заявленному, единственное проблеммы с отправкой возникают но думаю эти проблемы временные, поссылка дошла за два дня после отправки,, затестить сиогли на днях как все зашло, с первой прикурки чесно сказать прихуели думали что опять дживи 100 пришел, но ннет , держало часа по два сначало, на третий день время прихода испало до 4 0мин, вообщем все понравилось в очередной раз, на днях закажем еще
ArturoIcedy
21 Oct 25 at 11:16 am
online sportwetten österreich
Feel free to visit my blog; wettbüro aktien – https://www.opet.com.br,
https://www.opet.com.br
21 Oct 25 at 11:17 am
купить диплом во всеволожске [url=https://rudik-diplom4.ru]https://rudik-diplom4.ru[/url] .
Diplomi_idOr
21 Oct 25 at 11:18 am
http://www.sluck.kr/g5/bbs/board.php?bo_table=free&wr_id=1598306
http://www.sluck.kr/g5/bbs/board.php?bo_table=free&wr_id=1598306
21 Oct 25 at 11:18 am
This is really interesting, You are a very skilled blogger.
I have joined your feed and look forward to seeking
more of your wonderful post. Also, I’ve shared your website in my
social networks!
lastenrad
21 Oct 25 at 11:19 am
куплю диплом младшей медсестры [url=https://frei-diplom13.ru]https://frei-diplom13.ru[/url] .
Diplomi_odkt
21 Oct 25 at 11:20 am
купить диплом техникума до 1996 года [url=www.frei-diplom12.ru/]купить диплом техникума до 1996 года[/url] .
Diplomi_tnPt
21 Oct 25 at 11:21 am
купить диплом вуза занесением реестр [url=www.frei-diplom5.ru/]www.frei-diplom5.ru/[/url] .
Diplomi_gxPa
21 Oct 25 at 11:21 am
купить диплом в россоши [url=https://rudik-diplom11.ru]купить диплом в россоши[/url] .
Diplomi_jaMi
21 Oct 25 at 11:22 am
Cabinet IQ Austin
2419 Ⴝ Bell Blvd, Cedar Park,
TX 78613, United Ⴝtates
+12543183528
Bookmarks
Bookmarks
21 Oct 25 at 11:23 am