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://rudik-diplom7.ru/]купить морской диплом[/url] .
Diplomi_ytPl
1 Nov 25 at 11:09 am
Good write-up. I certainly appreciate this site. Stick with it!
cosmetics manufacturers
1 Nov 25 at 11:10 am
online pharmacy reviews and ratings: compare online pharmacy prices – best online pharmacy
HaroldSHems
1 Nov 25 at 11:10 am
купить диплом матроса [url=https://rudik-diplom2.ru/]купить диплом матроса[/url] .
Diplomi_jcpi
1 Nov 25 at 11:11 am
https://t.me/ud_Sol/56
MichaelPione
1 Nov 25 at 11:11 am
https://t.me/ud_Kent/63
MichaelPione
1 Nov 25 at 11:13 am
mostbet kg [url=http://mostbet12034.ru/]http://mostbet12034.ru/[/url]
mostbet_kg_vrPr
1 Nov 25 at 11:13 am
диплом колледжа купить с занесением в реестр [url=frei-diplom12.ru]frei-diplom12.ru[/url] .
Diplomi_ttPt
1 Nov 25 at 11:14 am
Кто знает хорошую уничтожение клопов холодным туманом в Москве? Срочно нужно!
уничтожение клопов холодным туманом
Wernermog
1 Nov 25 at 11:14 am
диплом купить проведенный [url=http://www.frei-diplom1.ru]диплом купить проведенный[/url] .
Diplomi_siOi
1 Nov 25 at 11:15 am
купить диплом магистра [url=http://rudik-diplom12.ru/]купить диплом магистра[/url] .
Diplomi_qyPi
1 Nov 25 at 11:15 am
купить диплом в нальчике [url=http://rudik-diplom7.ru/]купить диплом в нальчике[/url] .
Diplomi_doPl
1 Nov 25 at 11:15 am
online pharmacy
Edmundexpon
1 Nov 25 at 11:16 am
Very nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed surfing around your
blog posts. After all I will be subscribing to your rss
feed and I hope you write again soon!
price action
1 Nov 25 at 11:16 am
можно ли купить диплом в реестре [url=http://www.frei-diplom3.ru]можно ли купить диплом в реестре[/url] .
Diplomi_qwKt
1 Nov 25 at 11:17 am
В данной обзорной статье представлены интригующие факты, которые не оставят вас равнодушными. Мы критикуем и анализируем события, которые изменили наше восприятие мира. Узнайте, что стоит за новыми открытиями и как они могут изменить ваше восприятие реальности.
Уникальные данные только сегодня – https://taxlama.com/2024/08/19/global-oatmeal-market-size-and-share-report-2024-2032
EdwinDub
1 Nov 25 at 11:19 am
купить диплом техникума в иркутске [url=www.frei-diplom12.ru]купить диплом техникума в иркутске[/url] .
Diplomi_wiPt
1 Nov 25 at 11:20 am
https://xn--j1adp.xn--80aejmgchrc3b6cf4gsa.xn--p1ai/ Точка включения
MathewLit
1 Nov 25 at 11:22 am
Irish Pharma Finder
Edmundexpon
1 Nov 25 at 11:23 am
This design is incredible! You certainly know how to
keep a reader amused. Between your wit and your videos,
I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job.
I really loved what you had to say, and more than that, how you presented it.
Too cool!
See details
1 Nov 25 at 11:24 am
купить диплом техникума ссср в тюмени [url=https://frei-diplom12.ru]купить диплом техникума ссср в тюмени[/url] .
Diplomi_vcPt
1 Nov 25 at 11:25 am
мостбет кж [url=https://mostbet12034.ru/]https://mostbet12034.ru/[/url]
mostbet_kg_vxPr
1 Nov 25 at 11:25 am
купить диплом высшем образовании занесением реестр [url=www.frei-diplom3.ru]купить диплом высшем образовании занесением реестр[/url] .
Diplomi_riKt
1 Nov 25 at 11:26 am
купить проведенный диплом отзывы [url=https://frei-diplom1.ru]https://frei-diplom1.ru[/url] .
Diplomi_yzOi
1 Nov 25 at 11:27 am
купить диплом в дербенте [url=www.rudik-diplom12.ru]купить диплом в дербенте[/url] .
Diplomi_bpPi
1 Nov 25 at 11:28 am
букмекерская контора мостбет [url=https://www.mostbet12034.ru]https://www.mostbet12034.ru[/url]
mostbet_kg_ufPr
1 Nov 25 at 11:28 am
Ich bin beeindruckt von Cat Spins Casino, es verspricht ein einzigartiges Abenteuer. Die Spielauswahl ist beeindruckend, mit Spielen fur Kryptowahrungen. Er sorgt fur einen starken Einstieg. Der Service ist immer zuverlassig. Gewinne werden ohne Wartezeit uberwiesen, jedoch regelma?igere Promos wurden das Spiel aufwerten. In Summe, Cat Spins Casino ist ein Highlight fur Casino-Fans. Zusatzlich ist das Design stilvoll und einladend, eine tiefe Immersion ermoglicht. Ein weiteres Highlight die regelma?igen Turniere fur Wettbewerbsspa?, die Community enger verbinden.
http://www.catspins24.com|
brightbyteex4zef
1 Nov 25 at 11:28 am
Hi there i am kavin, its my first time to commenting anywhere, when i
read this post i thought i could also create comment due to
this sensible post.
sarang188
1 Nov 25 at 11:29 am
Hmm is anyone else experiencing problems with the images on this blog loading?
I’m trying to determine if its a problem on my end or if it’s the blog.
Any feedback would be greatly appreciated.
Regards
1 Nov 25 at 11:32 am
купить диплом с реестром вуза [url=https://frei-diplom1.ru/]купить диплом с реестром вуза[/url] .
Diplomi_elOi
1 Nov 25 at 11:34 am
купить аттестаты за 11 [url=https://www.rudik-diplom12.ru]купить аттестаты за 11[/url] .
Diplomi_svPi
1 Nov 25 at 11:36 am
купить проведенный диплом одно [url=https://frei-diplom1.ru]купить проведенный диплом одно[/url] .
Diplomi_agOi
1 Nov 25 at 11:42 am
Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
Всё, что нужно знать – https://council-icc.org/cicc-international-business-conference-albania
Martygok
1 Nov 25 at 11:43 am
купить диплом преподавателя [url=rudik-diplom2.ru]купить диплом преподавателя[/url] .
Diplomi_bfpi
1 Nov 25 at 11:43 am
где купить диплом техникума одно [url=www.frei-diplom12.ru]где купить диплом техникума одно[/url] .
Diplomi_zzPt
1 Nov 25 at 11:45 am
купить диплом стоматолога [url=https://rudik-diplom7.ru]купить диплом стоматолога[/url] .
Diplomi_urPl
1 Nov 25 at 11:49 am
Refresh Renovation Suthwest Charlotte
1251 Arow Pine Dr c121,
Charlotte, NC 28273, United States
+19803517882
Your refresh renovattions start proect һome wіth (Jerilyn)
Jerilyn
1 Nov 25 at 11:51 am
купить диплом в ишимбае [url=https://rudik-diplom2.ru]https://rudik-diplom2.ru[/url] .
Diplomi_dipi
1 Nov 25 at 11:51 am
Клиника «ЧСП№1» в Ростове-на-Дону предлагает услуги по выводу из запоя. Вы можете выбрать удобный для вас вариант: выезд нарколога на дом или лечение в стационаре. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Разобраться лучше – https://vyvod-iz-zapoya-rostov11.ru
RobertTut
1 Nov 25 at 11:53 am
Если вы беспокоитесь за здоровье близкого, не позволяйте запою разрушать жизнь. В Екатеринбурге клиника Детокс оказывается срочная помощь на дому: врач-нарколог приедет по вашему адресу, выполнит необходимые инъекции или капельницы, дистанционно проконтролирует состояние и составит план лечения. Это решение позволяет сохранить здоровье, предотвратить осложнения и начать путь к выздоровлению с минимальными дискомфортом и рисками.
Подробнее – [url=https://narkolog-na-dom-ekaterinburg12.ru/]нарколог на дом анонимно екатеринбург[/url]
MichaelRot
1 Nov 25 at 11:53 am
Представьте, что помощь приходит прямо к вам: в квартире, где нужна поддержка. Детокс в Екатеринбурге реализует услугу вызова нарколога на дом, чтобы облегчить состояние пациента без транспортировки и лишнего стресса. Врач подключит капельницу, проведёт детоксикацию и даст рекомендации по восстановлению, всё это в вашем знакомом окружении.
Узнать больше – [url=https://narkolog-na-dom-ekaterinburg11.ru/]нарколог на дом недорого в екатеринбурге[/url]
DavidHic
1 Nov 25 at 11:54 am
I’m no longer certain where you’re getting your information,
but good topic. I must spend a while learning much more or working out more.
Thank you for wonderful info I used to be on the
lookout for this information for my mission.
ankara kürtaj
1 Nov 25 at 11:54 am
В Ростове-на-Дону клиника «ЧСП№1» оказывает услуги по выводу из запоя с полным медицинским сопровождением.
Получить больше информации – [url=https://vyvod-iz-zapoya-rostov15.ru/]вывод из запоя анонимно[/url]
Robertodes
1 Nov 25 at 11:55 am
Hi there terrific blog! Does running a blog such as this
require a great deal of work? I’ve no understanding of coding however I
was hoping to start my own blog soon. Anyhow,
if you have any suggestions or tips for new blog owners
please share. I understand this is off subject nevertheless I just
wanted to ask. Cheers!
informative
1 Nov 25 at 11:55 am
купить диплом в ноябрьске [url=http://rudik-diplom7.ru]купить диплом в ноябрьске[/url] .
Diplomi_bkPl
1 Nov 25 at 11:56 am
Your means of describing the whole thing in this piece of writing is
truly pleasant, all be capable of simply know it, Thanks a lot.
best facial moisturizer
1 Nov 25 at 11:56 am
Клиника «ЧСП№1» в Ростове-на-Дону предлагает услуги по выводу из запоя. Вы можете выбрать удобный для вас вариант: выезд нарколога на дом или лечение в стационаре. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-rostov18.ru/]вывод из запоя вызов на дом[/url]
Berryjew
1 Nov 25 at 11:56 am
trusted online pharmacy Ireland
Edmundexpon
1 Nov 25 at 11:56 am
Клиника «ЧСП№1» в Ростове-на-Дону предлагает услуги по выводу из запоя. Вы можете выбрать удобный для вас вариант: выезд нарколога на дом или лечение в стационаре. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Детальнее – [url=https://vyvod-iz-zapoya-rostov17.ru/]вывод из запоя на дому круглосуточно[/url]
Lamontdoubs
1 Nov 25 at 11:56 am
Быстро выйти из запоя можно с помощью клиники «ЧСП№1» в Ростове-на-Дону. Доступен выезд нарколога на дом.
Узнать больше – [url=https://vyvod-iz-zapoya-rostov16.ru/]вывод из запоя капельница[/url]
Donaldcer
1 Nov 25 at 11:57 am