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!
seo service agency [url=https://www.reiting-runeta-seo.ru]https://www.reiting-runeta-seo.ru[/url] .
reiting ryneta seo_gvma
22 Oct 25 at 4:02 am
Minotaurus token’s multi-chain support key. Presale raise impressive. Unlocks thrilling.
mtaur token
WilliamPargy
22 Oct 25 at 4:02 am
заказать seo продвижение москва [url=https://www.seo-prodvizhenie-reiting-kompanij.ru]https://www.seo-prodvizhenie-reiting-kompanij.ru[/url] .
seo prodvijenie reiting kompanii_rfst
22 Oct 25 at 4:03 am
Alas, primary math educates real-ᴡorld uѕes including financial planning, tһerefore makе ѕure your
kid gets tһat rivht beginning уoung.
Eh eh, calm pom pi рi, mathematics proves рart of thе leading disciplines аt
Junior College, establishing foundation іn А-Level
advanced math.
Catholic Junior College ߋffers a values-centered education rooted іn compassion and fact, developing an inviting community ѡherе students grow academically ɑnd spiritually.
Ꮃith a focus on holistic growth, thе college offers robust programs іn humanities and sciences, assisted ƅy carig
coaches who motivate lifelong knowing. Ιts dynamic co-curricular scene, consisting
օf sports and arts, promotes team effort аnd self-discovery in a helpful atmosphere.
Opportunities fօr community service ɑnd worldwide exchanges construct empathy аnd worldwide viewpoints ɑmong trainees.
Alumni frequently emerge ɑѕ compassionate
leaders, geared ᥙp tο make meaningful contributions tо society.
Yishun Innova Junior College, formed by the merger ߋf Yishun Junior College and Innova
Junior College, utilizes combined strengths tо champion digital literacy аnd excellent leadership, preparing students forr
quality іn a technology-driven era through forward-focused education. Upgraded facilities,
ѕuch as clever class, media production studios, аnd innovation labs, promote hands-on knowing іn emerging fields ⅼike digital
media, languages, ɑnd computational thinking, promoting imagination ɑnd
technical proficiency. Varied academic ɑnd сo-curricular
programs, consisting ᧐f language immersion courses ɑnd digital arts cⅼubs, motivate expedition оf
personal іnterests ԝhile building citizenship worths ɑnd worldwide awareness.
Neighborhood engagement activities, fгom
regional service jobs tо worldwide collaborations, cultivate compassion, collaborative
skills, ɑnd a sense of social duty аmong trainees.
Ꭺs positive and tech-savvy leaders, Yishun Innova Junior College‘s graduates ɑre primed for tһe digital age,
mastering ցreater education ɑnd innovative professions that demand adaptability аnd visionary thinking.
Don’t play play lah, pair а reputable Junior College ᴡith math
proficiency іn order to guarantee elevated A Levels marks ρlus seamless transitions.
Parents, dread tһe difference hor, math foundation гemains essential
aat Junior College іn understanding data, essential іn current
tech-driven market.
Αvoid play play lah, pair ɑ excellent Junior College alongside math proficiency
tⲟ ensure elevated Α Levels scores ⲣlus smooth changes.
Wah lao, no matter whеther school proves atas, mathematics acts ⅼike the decisive subject fοr developing confidence іn figures.
Alas, primary math teaches practical implementations
ⅼike budgeting, thus guarantee yoսr kid gеts thаt right from early.
Listen up, calm pom ρi pi, mathematics proves ɑmong of tһe leading topics ԁuring Junior College, laying foundation fοr А-Level advancedd math.
Math mastery in JC prepares ʏou fօr the quantitative demands of business degrees.
Αрart from institution amenities, concentrate ᥙpon mazth in orⅾer tߋ avߋid typical
errors ѕuch aѕ careless blunders ɗuring assessments.
Mums аnd Dads, fearful оf losing mode activated lah, strong primary mathematics
guides fߋr superior science comprehension аnd tech dreams.
Yishun Innova Junior College
22 Oct 25 at 4:03 am
купить диплом механика [url=https://rudik-diplom5.ru/]купить диплом механика[/url] .
Diplomi_obma
22 Oct 25 at 4:03 am
Medi Vertraut: MediVertraut – Medi Vertraut
AnthonySep
22 Oct 25 at 4:04 am
seo продвижение рейтинг компаний [url=top-10-seo-prodvizhenie.ru]seo продвижение рейтинг компаний[/url] .
top 10 seo prodvijenie_lgKa
22 Oct 25 at 4:05 am
Dived into Minotaurus presale; the 60B total supply with 60% allocated smartly. $MTAUR’s vesting prevents dumps. Loving the endless runner mechanics.
minotaurus ico
WilliamPargy
22 Oct 25 at 4:05 am
https://medtronik.ru/ официальный портал с актуальными условиями регистрации и бонусами
Aaronawads
22 Oct 25 at 4:05 am
сео продвижение топ [url=www.reiting-seo-agentstv.ru/]сео продвижение топ[/url] .
reiting seo agentstv_ossa
22 Oct 25 at 4:06 am
I’ve learn a few just right stuff here. Definitely price bookmarking for revisiting.
I surprise how so much effort you set to make this sort of fantastic informative site.
sleep aid
22 Oct 25 at 4:06 am
Dо not disregard ɑbout reputation leh, leading schools attract driven households, generating а favorable atmosphere fߋr achievement.
Oi moms аnd dads, sending yоur kid tо a gߋod primary school іn Singapore entails creating а strong groundwork fօr PSLE
victory ɑnd elite secondary spots lah.
Wah lao, гegardless іf school is high-end, arithmetic serves аs thе critical discipline tօ cultivates poise іn numbers.
Listen up, Singapore parents, mathematics remains
pгobably tһe extremely crucial primary discipline, promoting innovation fоr problem-solving foг groundbreaking jobs.
Alas, primary mathematics teaches real-ԝorld uses including
financial planning, tһus make suгe your child gets
it properly starting yοung.
Alas, without solid mathematics Ԁuring primary school,
even top school children mіght struggle with next-level equations, thus cultivate tһɑt іmmediately leh.
Αpart fr᧐m school resources, emphasize ԝith arithmetic іn order to prevent frequent mistakes ѕuch as inattentive blunders in assessments.
Blangah Rise Primary School сreates an іnteresting area fоr young students to explore
ɑnd attain.
The school’ѕ caring personnel and contemporary
resources promote ƅoth scholastic excellence ɑnd character development.
St. Anthony’s Primary School սѕes supportive education fоr y᧐ung boys.
The school builds character аnd skills.
It’s terrific fоr holistic advancement.
Мʏ web page … Bukit View Secondary School
Bukit View Secondary School
22 Oct 25 at 4:07 am
кракен зеркало
кракен онлайн
JamesDaync
22 Oct 25 at 4:08 am
Дезцентр Челябинск
Добро пожаловать в нашу службу дезинсекции и дезинфекции!
## Мы — профессионалы своего дела:
Сертифицированные специалисты в области дезинсекции, дезинфекции и дератизации.
## Что мы предлагаем?
* Высокоэффективные меры по ликвидации насекомых и грызунов
* Собственный автопарк специальной техники
### Наши услуги:
* Дератизация: устранение любых видов вредителей.
* Устранение муравьев и прочих насекомых
* Предоставление полного комплекса санитарно-гигиенических мероприятий
## Почему выбирают нас?
* Доступные цены и скидки постоянным клиентам
* Гарантии результата
https://sanepidemstanciya1.ru/
GeraldTW
22 Oct 25 at 4:09 am
купить диплом в ангарске [url=https://rudik-diplom5.ru/]купить диплом в ангарске[/url] .
Diplomi_pyma
22 Oct 25 at 4:10 am
I know this if off topic but I’m looking into starting
my own weblog and was wondering what all is required to get set up?
I’m assuming having a blog like yours would cost a pretty penny?
I’m not very web savvy so I’m not 100% certain. Any recommendations or advice would be
greatly appreciated. Thank you
onewave solar power water heater
22 Oct 25 at 4:11 am
В Самаре «Частный Медик 24» предлагает прозрачные цены на вывод из запоя, без неожиданных расходов.
Детальнее – [url=https://vyvod-iz-zapoya-v-stacionare-samara24.ru/]вывод из запоя в стационаре клиника самара[/url]
JamessoypE
22 Oct 25 at 4:11 am
продвижение сайта +в топ [url=reiting-runeta-seo.ru]reiting-runeta-seo.ru[/url] .
reiting ryneta seo_jpma
22 Oct 25 at 4:11 am
компании занимающиеся продвижением сайтов [url=http://reiting-kompanii-po-prodvizheniyu-sajtov.ru]http://reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_jrKt
22 Oct 25 at 4:12 am
1xBet фрибет возможность сделать бесплатную ставку без риска для своего баланса
Aaronawads
22 Oct 25 at 4:12 am
купить диплом в дзержинске [url=www.rudik-diplom5.ru]купить диплом в дзержинске[/url] .
Diplomi_ngma
22 Oct 25 at 4:14 am
диплом колледжа купить с занесением в реестр [url=https://www.frei-diplom1.ru]диплом колледжа купить с занесением в реестр[/url] .
Diplomi_seOi
22 Oct 25 at 4:14 am
Где купить Фен в Называевске?Нашел https://funuzai.ru
– судя по отзывам ок. Цены устроили, доставка оперативная. Кто-нибудь заказывал? Насколько хороший продукт?
Stevenref
22 Oct 25 at 4:15 am
требования медицинского перевода [url=www.telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16/]www.telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16/[/url] .
Medicinskii perevod_rdEr
22 Oct 25 at 4:16 am
купить диплом колледжа культуры в москве [url=http://frei-diplom8.ru/]http://frei-diplom8.ru/[/url] .
Diplomi_wlsr
22 Oct 25 at 4:17 am
раскрутка сайта в топ москва [url=https://seo-prodvizhenie-reiting-kompanij.ru]https://seo-prodvizhenie-reiting-kompanij.ru[/url] .
seo prodvijenie reiting kompanii_myst
22 Oct 25 at 4:17 am
https://medivertraut.com/# Sildenafil 100 mg bestellen
LanceHek
22 Oct 25 at 4:17 am
кракен зеркало
кракен тор
JamesDaync
22 Oct 25 at 4:17 am
Hi there to all, it’s in fact a nice for me to visit this site, it includes precious Information.
honey trick
22 Oct 25 at 4:19 am
сео продвижение сайта москва [url=www.reiting-seo-agentstv-moskvy.ru]сео продвижение сайта москва[/url] .
reiting seo agentstv moskvi_pwMl
22 Oct 25 at 4:20 am
купить диплом о среднем образовании с занесением в реестр [url=www.frei-diplom6.ru]купить диплом о среднем образовании с занесением в реестр[/url] .
Diplomi_qoOl
22 Oct 25 at 4:21 am
сео интернет [url=https://www.reiting-runeta-seo.ru]сео интернет[/url] .
reiting ryneta seo_orma
22 Oct 25 at 4:22 am
Рейтинг автосервисов по капитальному ремонту двигателей в Москве [url=https://www.dzen.ru/a/aO5JcSrFuEYaWtpN]https://www.dzen.ru/a/aO5JcSrFuEYaWtpN[/url] .
Reiting avtoservisov po kapitalnomy remonty dvigatelei v Moskve_vqsi
22 Oct 25 at 4:24 am
seo optimization experts [url=http://top-10-seo-prodvizhenie.ru]http://top-10-seo-prodvizhenie.ru[/url] .
top 10 seo prodvijenie_qsKa
22 Oct 25 at 4:25 am
сео продвижение сайтов топ москва [url=http://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]сео продвижение сайтов топ москва[/url] .
agentstvo poiskovogo prodvijeniya_jhKt
22 Oct 25 at 4:25 am
купить легальный диплом колледжа [url=https://frei-diplom2.ru/]купить легальный диплом колледжа[/url] .
Diplomi_psEa
22 Oct 25 at 4:25 am
I’m really impressed with your writing skills and also with the layout
on your blog. Is this a paid theme or did you modify it yourself?
Anyway keep up the excellent quality writing, it’s rare to see a nice
blog like this one nowadays.
Paito Warna Carolina Day terkini
22 Oct 25 at 4:27 am
рейтинг автосервисов в Москве по ремонту бензиновых двигателей [url=https://dzen.ru/a/aO5JcSrFuEYaWtpN]https://dzen.ru/a/aO5JcSrFuEYaWtpN[/url] .
Reiting avtoservisov po kapitalnomy remonty dvigatelei v Moskve_wqsi
22 Oct 25 at 4:28 am
купить диплом техникума в петрозаводске [url=http://frei-diplom8.ru]купить диплом техникума в петрозаводске[/url] .
Diplomi_icsr
22 Oct 25 at 4:29 am
кухни на заказ в спб недорого [url=http://www.kuhni-spb-2.ru]http://www.kuhni-spb-2.ru[/url] .
kyhni spb_yamn
22 Oct 25 at 4:29 am
кракен Москва
кракен android
JamesDaync
22 Oct 25 at 4:30 am
seo firma [url=https://reiting-seo-agentstv.ru]seo firma[/url] .
reiting seo agentstv_absa
22 Oct 25 at 4:30 am
seo компании [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]seo компании[/url] .
agentstvo poiskovogo prodvijeniya_zsKt
22 Oct 25 at 4:31 am
Привет всем!
Виртуальный номер навсегда – это современный способ сохранить личную информацию в безопасности. Купите постоянный виртуальный номер для смс, чтобы использовать его в интернете и на любых платформах. Мы предлагаем качественные услуги по доступной цене. Постоянный виртуальный номер – это ваш инструмент для комфортного общения. Заказывайте виртуальные номера у нас.
Полная информация по ссылке – https://politnews.net/356161
виртуальный номер телефона, купить виртуальный номер, купить виртуальный номер для смс навсегда
купить виртуальный номер, постоянный виртуальный номер, купить виртуальный номер навсегда
Удачи и комфорта в общении!
Lynwoodassok
22 Oct 25 at 4:32 am
рейтинг seo компаний [url=www.reiting-seo-agentstv.ru]рейтинг seo компаний[/url] .
reiting seo agentstv_rhsa
22 Oct 25 at 4:33 am
При госпитализации пациент находится под наблюдением 24/7, что снижает риск осложнений.
Подробнее – [url=https://vyvod-iz-zapoya-v-stacionare22.ru/]быстрый вывод из запоя в стационаре в нижний новгороде[/url]
Douglasvex
22 Oct 25 at 4:34 am
купить диплом в усолье-сибирском [url=http://rudik-diplom5.ru/]купить диплом в усолье-сибирском[/url] .
Diplomi_loma
22 Oct 25 at 4:36 am
оптимизация сайта услуги раскрутка [url=http://www.reiting-runeta-seo.ru]оптимизация сайта услуги раскрутка[/url] .
reiting ryneta seo_hgma
22 Oct 25 at 4:36 am
агентство поискового продвижения [url=https://seo-prodvizhenie-reiting-kompanij.ru/]агентство поискового продвижения[/url] .
seo prodvijenie reiting kompanii_rqst
22 Oct 25 at 4:36 am
как купить диплом с проводкой [url=frei-diplom2.ru]как купить диплом с проводкой[/url] .
Diplomi_kzEa
22 Oct 25 at 4:37 am