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=www.karniz-s-elektroprivodom.ru]электрокарнизы для штор купить[/url] .
karniz s elektroprivodom_nrKt
15 Sep 25 at 11:19 am
электрокранизы [url=http://avtomaticheskie-karnizy-dlya-shtor.ru/]http://avtomaticheskie-karnizy-dlya-shtor.ru/[/url] .
avtomaticheskie karnizi dlya shtor_zvOr
15 Sep 25 at 11:20 am
электрокарнизы для штор цена [url=www.elektrokarniz-cena.ru]электрокарнизы для штор цена[/url] .
elektrokarniz cena_ahPL
15 Sep 25 at 11:21 am
электрокарниз москва [url=www.karniz-s-elektroprivodom.ru/]электрокарниз москва[/url] .
karniz s elektroprivodom_hwKt
15 Sep 25 at 11:23 am
электрокарниз двухрядный [url=http://elektro-karniz77.ru]http://elektro-karniz77.ru[/url] .
elektro karniz_ntSl
15 Sep 25 at 11:23 am
электрокарнизы в москве [url=http://www.avtomaticheskie-karnizy.ru]http://www.avtomaticheskie-karnizy.ru[/url] .
avtomaticheskie karnizi_slSa
15 Sep 25 at 11:23 am
карниз с приводом [url=https://www.avtomaticheskie-karnizy-dlya-shtor.ru]карниз с приводом[/url] .
avtomaticheskie karnizi dlya shtor_ngOr
15 Sep 25 at 11:24 am
It’s enormous that you are getting ideas from this piece
of writing as well as from our dialogue made at this
time.
Take a look at my web site; خرید کتاب زبان از زبانمهر
خرید کتاب زبان از زبانمهر
15 Sep 25 at 11:25 am
Keеp upgraded on Singapore’s deals by mеans of Kaizenaire.cοm, thе premier site
curating promotions from favored brands.
Ԝith varied offerings, Singapore’ѕ shopping heaven satisfies
promotion-craving residents.
Checking Օut Sentosa Island fߋr beach daүs іs a best
task fοr fun-seeking Singaporeans, аnd
bear іn mind to stay upgraded օn Singapore’s moѕt recеnt promotions аnd
shopping deals.
Singlife deals electronic insurance coverage аnd financial savings products, appreciated by Singaporeans fοr
theiг tech-savvy approach and monetary security.
SP Ꮐroup takeѕ care of electrical power аnd gas energies leh, valued Ьy Singaporeans for their lasting energy options and efficient
service shipment оne.
Select Ԍroup Limited prоvides banquets аnd buffets, cherished fߋr trustworthy occasion food services.
Do nnot play cheat leh, usage Kaizenaire.ϲom consistently tο gеt the ideal shopping pгovides оne.
My рage: best job recruitment agency in singapore
best job recruitment agency in singapore
15 Sep 25 at 11:26 am
Medicines information. Brand names.
effexor et bupropion
All information about medicines. Get information here.
effexor et bupropion
15 Sep 25 at 11:27 am
электрокарнизы для штор цена [url=http://elektro-karniz77.ru/]http://elektro-karniz77.ru/[/url] .
elektro karniz_jaSl
15 Sep 25 at 11:27 am
автоматические карнизы для штор [url=http://www.avtomaticheskie-karnizy.ru]автоматические карнизы для штор[/url] .
avtomaticheskie karnizi_yaSa
15 Sep 25 at 11:27 am
купить диплом в кургане занесением в реестр [url=http://arus-diplom31.ru]купить диплом в кургане занесением в реестр[/url] .
Priobresti diplom lubogo VYZa!_nqOl
15 Sep 25 at 11:29 am
купить диплом занесенный реестр [url=www.arus-diplom33.ru]купить диплом занесенный реестр[/url] .
Diplomi_fuSa
15 Sep 25 at 11:30 am
электрокарнизы [url=https://elektrokarniz-cena.ru/]электрокарнизы[/url] .
elektrokarniz cena_ejPL
15 Sep 25 at 11:31 am
Greetings! This is my 1st comment here so I just
wanted to give a quick shout out and tell you I genuinely enjoy reading
your articles. Can you recommend any other blogs/websites/forums
that deal with the same topics? Many thanks!
penipuan transnasional
15 Sep 25 at 11:33 am
Обращение к наркологам в Красноярске — необходимая мера, которая людям, страдающим от зависимостей. Наркологическая клиника Красноярск предлагает широкий спектр услуг, среди которых лечение зависимостей и помощь при алкоголизме. Если вы или ваши близкие нуждаетесь в поддержке, обязательно рассмотрите вариант вызова нарколога.Консультация нарколога может стать первым шагом к выздоровлению. Специалисты предоставляют анонимное лечение, чтобы обеспечить комфорт и конфиденциальность пациента. Круглосуточная горячая линия всегда готова помочь и ответить на ваши вопросы, особенно в экстренных ситуациях. vivod-iz-zapoya-krasnoyarsk014.ru Реабилитация зависимых включает программы по лечению зависимостей и психотерапевтические методики. Вы можете вызвать нарколога в любое время, что делает процесс лечения максимально удобным. Не откладывайте обращение за помощью, поскольку здоровье — это самое ценное.
lecheniekrasnoyarskNeT
15 Sep 25 at 11:34 am
Spot on with this write-up, I honestly believe this amazing site needs
far more attention. I’ll probably be returning to read more, thanks matcha tea for focus the info!
matcha tea for focus
15 Sep 25 at 11:36 am
Mega ссылка Мега даркнет Мега сайт Мега онион Мега ссылка Mega даркнет Mega сайт Mega онион Mega ссылка Mega darknet Mega onion
RichardPep
15 Sep 25 at 11:37 am
купить диплом с проводкой меня [url=http://arus-diplom31.ru]купить диплом с проводкой меня[/url] .
Priobresti diplom o visshem obrazovanii!_vlOl
15 Sep 25 at 11:39 am
Domain Rating
Position in search results is crucial for SEO.
We specialize in attracting Google bots to your website to raise the site’s ranking using content marketing, SEO tools, in addition, we also generate crawler traffic through third-party sources.
There are two primary categories of crawlers – exploratory and data-processing.
Exploratory crawlers are the initial visitors to the site and also instruct indexing robots to enter.
Higher click volume from search robots to the site, the more positive it is for the site.
Before launching the process, we will send you with a image of the DR from ahrefs.com/backlink-checker, and once the project is finished, there will be another a snapshot of the domain rating from ahrefs.com/backlink-checker.
You pay only upon success!
Timeline for completion is from 3 to 14 days,
Occasionally, additional time is necessary.
We accept projects for websites up to 50 DR.
Domain Rating
15 Sep 25 at 11:39 am
карниз для штор с электроприводом [url=elektrokarniz-cena.ru]карниз для штор с электроприводом[/url] .
elektrokarniz cena_rkPL
15 Sep 25 at 11:39 am
электрокарниз [url=http://avtomaticheskie-karnizy-dlya-shtor.ru]электрокарниз[/url] .
avtomaticheskie karnizi dlya shtor_tmOr
15 Sep 25 at 11:42 am
электронный карниз для штор [url=www.karniz-s-elektroprivodom.ru/]электронный карниз для штор[/url] .
karniz s elektroprivodom_mpKt
15 Sep 25 at 11:43 am
электрокарнизы [url=www.elektrokarniz-cena.ru/]электрокарнизы[/url] .
elektrokarniz cena_dhPL
15 Sep 25 at 11:43 am
Hello my family member! I wish to say that this article is amazing,
great written and come with approximately all significant infos.
I’d like to see extra posts like this .
Hướng dẫn chế bom xăng
15 Sep 25 at 11:43 am
электрокарнизы для штор купить в москве [url=www.avtomaticheskie-karnizy-dlya-shtor.ru/]электрокарнизы для штор купить в москве[/url] .
avtomaticheskie karnizi dlya shtor_bpOr
15 Sep 25 at 11:45 am
электрокарнизы [url=www.avtomaticheskie-karnizy-dlya-shtor.ru/]электрокарнизы[/url] .
avtomaticheskie karnizi dlya shtor_bhOr
15 Sep 25 at 11:46 am
электрокарнизы для штор цена [url=https://elektro-karniz77.ru]https://elektro-karniz77.ru[/url] .
elektro karniz_hhSl
15 Sep 25 at 11:47 am
карниз для штор с электроприводом [url=https://avtomaticheskie-karnizy.ru/]avtomaticheskie-karnizy.ru[/url] .
avtomaticheskie karnizi_feSa
15 Sep 25 at 11:47 am
электрокарниз двухрядный [url=www.karniz-s-elektroprivodom.ru]электрокарниз двухрядный[/url] .
karniz s elektroprivodom_diKt
15 Sep 25 at 11:49 am
I have read some excellent stuff here. Definitely price bookmarking for revisiting.
I wonder how much effort you set to make this sort of magnificent
informative web site.
Visit my page premium matcha tea
premium matcha tea
15 Sep 25 at 11:50 am
карниз с приводом для штор [url=www.elektro-karniz77.ru/]www.elektro-karniz77.ru/[/url] .
elektro karniz_smSl
15 Sep 25 at 11:51 am
карниз моторизованный [url=https://avtomaticheskie-karnizy.ru]https://avtomaticheskie-karnizy.ru[/url] .
avtomaticheskie karnizi_wySa
15 Sep 25 at 11:51 am
автоматические гардины для штор [url=http://www.elektro-karniz77.ru]http://www.elektro-karniz77.ru[/url] .
elektro karniz_jxSl
15 Sep 25 at 11:54 am
карниз с электроприводом [url=www.avtomaticheskie-karnizy.ru]карниз с электроприводом[/url] .
avtomaticheskie karnizi_eeSa
15 Sep 25 at 11:54 am
купить диплом легальный [url=www.arus-diplom33.ru]купить диплом легальный[/url] .
Diplomi_skSa
15 Sep 25 at 11:54 am
Dive rigһt into financial savings witһ Kaizenaire.com, thе premier site fоr Singapore’ѕ shopping occasions.
Singapore’sretail wonders make it a heaven, ᴡith promotions
that residents ɡo aftеr eagerly.
Playing mahjong ᴡith family mеmbers during gatherings is a standard preferred amоng Singaporeans, and kеep in mind to remain upgraded on Singapore’s most current promotions ɑnd shopping deals.
OSIM markets massage chairs ɑnd wellness tools,
tdeasured Ьʏ Singaporeans for their soothing һome medspa experiences.
ComfortDelGro ߋffers taxi and public transport services
lor, valued bby Singaporeans fօr tһeir dependable trips and comprehensive
network tһroughout the city leh.
Ng Ah Sio Bak Kut Teh spices pork ribs ѡith bold peppers, preferred fоr genuine, warming up bowls since
the 1970s.
Singaporeans, remain in advance mah, inspect Kaizenaire.ϲom everyday lah.
Ꭺlso visit my web site netflix singapore is using which recruitment agency
netflix singapore is using which recruitment agency
15 Sep 25 at 11:55 am
автоматический карниз для штор [url=http://avtomaticheskie-karnizy-dlya-shtor.ru/]автоматический карниз для штор[/url] .
avtomaticheskie karnizi dlya shtor_ucOr
15 Sep 25 at 11:55 am
электрокарниз москва [url=karniz-s-elektroprivodom.ru]электрокарниз москва[/url] .
karniz s elektroprivodom_naKt
15 Sep 25 at 11:56 am
В отдельном разделе статьи про сайты продать скины кс2 с выводом на карту представлены ответы на часто задаваемые вопросы покупателей и продавцов: касаются быстроты выплат, безопасности сделок, минимальных сумм для вывода, вариантов вывода средств и возможности работы без банковской карты. Автор акцентирует внимание на высокой надёжности и положительных отзывах о предложенных сервисах.
RomanNam
15 Sep 25 at 11:59 am
1 вин официальный вход [url=https://www.1win12007.ru]https://www.1win12007.ru[/url]
1win_hopn
15 Sep 25 at 11:59 am
internet apotheke: sildenafil tabletten online bestellen – online apotheke günstig
Donaldanype
15 Sep 25 at 12:00 pm
диплом автотранспортного техникума купить в [url=www.educ-ua10.ru]www.educ-ua10.ru[/url] .
Diplomi_lfKl
15 Sep 25 at 12:01 pm
https://intimgesund.com/# kamagra erfahrungen deutschland
Williamves
15 Sep 25 at 12:01 pm
карниз для штор с электроприводом [url=elektrokarniz-cena.ru]карниз для штор с электроприводом[/url] .
elektrokarniz cena_icPL
15 Sep 25 at 12:02 pm
I’m gone to say to my little brother, that he should also pay a quick visit this web site on regular basis to take updated from most up-to-date news update.
mua bảo hiểm nhân thọ
15 Sep 25 at 12:02 pm
карниз для штор с электроприводом [url=www.avtomaticheskie-karnizy-dlya-shtor.ru]карниз для штор с электроприводом[/url] .
avtomaticheskie karnizi dlya shtor_phOr
15 Sep 25 at 12:02 pm
автоматический карниз для штор [url=www.elektro-karniz77.ru/]www.elektro-karniz77.ru/[/url] .
elektro karniz_feSl
15 Sep 25 at 12:03 pm
With havin so much written content do you ever run into any problems of
plagorism or copyright violation? My website has a lot
of unique content I’ve either written myself or outsourced
but it looks like a lot of it is popping it up all over
the internet without my authorization. Do you know any
techniques to help protect against content from being
ripped off? I’d truly appreciate it.
Also visit my web-site; nfl stream
nfl stream
15 Sep 25 at 12:03 pm