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.top-10-seo-prodvizhenie.ru]лучшее сео продвижение[/url] .
top 10 seo prodvijenie_cyKa
22 Oct 25 at 3:27 am
кракен тор
kraken android
JamesDaync
22 Oct 25 at 3:27 am
капремонт двигателей [url=www.dzen.ru/a/aO5JcSrFuEYaWtpN/]www.dzen.ru/a/aO5JcSrFuEYaWtpN/[/url] .
Reiting avtoservisov po kapitalnomy remonty dvigatelei v Moskve_hlsi
22 Oct 25 at 3:28 am
В стационаре в Воронеже вам обеспечат безопасный выход из запоя: врачи контролируют состояние, корректируют лечение при сопутствующих заболеваниях, используют витамины, препараты для печени, кардиопротекторы, спазмолитики и другие средства, чтобы облегчить состояние.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh22.ru/]вывод из запоя в стационаре в воронеже[/url]
ClydeOmiGe
22 Oct 25 at 3:28 am
компании по продвижению сайта [url=reiting-kompanii-po-prodvizheniyu-sajtov.ru]reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_agKt
22 Oct 25 at 3:29 am
раскрутка сайтов москва [url=http://reiting-seo-agentstv-moskvy.ru]раскрутка сайтов москва[/url] .
reiting seo agentstv moskvi_koMl
22 Oct 25 at 3:29 am
seo продвижение рейтинг компаний [url=top-10-seo-prodvizhenie.ru]seo продвижение рейтинг компаний[/url] .
top 10 seo prodvijenie_vqKa
22 Oct 25 at 3:30 am
диплом политехнического колледжа купить [url=www.frei-diplom8.ru/]www.frei-diplom8.ru/[/url] .
Diplomi_clsr
22 Oct 25 at 3:32 am
услуги по оптимизации сайта [url=www.reiting-runeta-seo.ru]услуги по оптимизации сайта[/url] .
reiting ryneta seo_vhma
22 Oct 25 at 3:33 am
купить диплом техникума в твери [url=http://www.frei-diplom9.ru]купить диплом техникума в твери[/url] .
Diplomi_yhea
22 Oct 25 at 3:33 am
Everyone loves what you guys are usually up too.
This sort of clever work and coverage! Keep up the excellent works guys I’ve added you
guys to blogroll.
best solar water heater malaysia
22 Oct 25 at 3:34 am
единственная существенная проблема данного магазина – отсутствие автоматизированной системы оформления заказов… Вроде прикручивают к сайту, но что то долго уже…
https://torezvxn.ru
Отдуши за ровность!
Donaldmoire
22 Oct 25 at 3:35 am
I’ve been exploring for a little bit for any high quality articles or
blog posts on this kind of area . Exploring in Yahoo I eventually stumbled
upon this website. Studying this information So i am glad to
convey that I’ve a very just right uncanny feeling
I found out just what I needed. I such a lot indisputably will make sure
to do not omit this website and provides it a glance regularly.
fastest payout online casinos
22 Oct 25 at 3:35 am
Pada Oktober 2025, dunia hiburan digital kembali diramaikan oleh
munculnya berbagai APK viral yang menawarkan pengalaman bermain interaktif dengan tampilan yang semakin realistis dan fitur sosial yang menarik.
Salah satu topik yang paling banyak dibicarakan adalah “APKSLOT”, sebuah istilah yang kini tak hanya mengacu
pada permainan berbasis keberuntungan, tetapi juga pada evolusi
aplikasi hiburan yang menggabungkan elemen simulasi,
strategi, dan komunitas.
slot аpk 2025 viral
22 Oct 25 at 3:36 am
seo продвижение сайта в москве [url=http://seo-prodvizhenie-reiting-kompanij.ru/]http://seo-prodvizhenie-reiting-kompanij.ru/[/url] .
seo prodvijenie reiting kompanii_ajst
22 Oct 25 at 3:36 am
kraken vk2
кракен сайт
JamesDaync
22 Oct 25 at 3:37 am
изготовление кухни на заказ в спб [url=www.kuhni-spb-2.ru/]www.kuhni-spb-2.ru/[/url] .
kyhni spb_mwmn
22 Oct 25 at 3:37 am
seo продвижение сайта россия [url=https://www.reiting-seo-agentstv.ru]seo продвижение сайта россия[/url] .
reiting seo agentstv_smsa
22 Oct 25 at 3:37 am
seo раскрутка недорого [url=http://www.reiting-runeta-seo.ru]seo раскрутка недорого[/url] .
reiting ryneta seo_ixma
22 Oct 25 at 3:39 am
кто купил диплом техникума отзывы [url=frei-diplom8.ru]кто купил диплом техникума отзывы[/url] .
Diplomi_uysr
22 Oct 25 at 3:39 am
shopforhappiness.shop – Secure checkout process, felt confident shopping here.
Madie Duble
22 Oct 25 at 3:39 am
сео агентство [url=http://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]сео агентство[/url] .
agentstvo poiskovogo prodvijeniya_icKt
22 Oct 25 at 3:39 am
рейтинг фирм seo [url=https://www.top-10-seo-prodvizhenie.ru]https://www.top-10-seo-prodvizhenie.ru[/url] .
top 10 seo prodvijenie_xjKa
22 Oct 25 at 3:39 am
Asking questions are truly good thing if you are not understanding something
entirely, except this post presents nice understanding even.
HVAC repair Los Angeles
22 Oct 25 at 3:39 am
Самый полный список промокодов 1хБет на сегодня у нас на сайте. Все промокоды раздаются бесплатно: на ставку, при регистрации, бездепозитные промики. Обновляем каждые 5 часов. Обычно 1xBet промокод при регистрации предоставляет бонус на первый депозит и используется на этапе создания аккаунта в БК. Сумма вознаграждения достигает 100% от первого пополнения. Следующий тип — как узнать свой промокод в 1хбет. Он позволяет заключать пари на спортивные события, либо пользоваться привилегиями в сфере азартных игр, доступных на сайте БК. Такой бонус предоставляется бесплатно в честь регистрации, Дня рождения или активности.
Stanleyvonna
22 Oct 25 at 3:41 am
диплом с внесением в реестр купить [url=https://frei-diplom2.ru/]диплом с внесением в реестр купить[/url] .
Diplomi_wpEa
22 Oct 25 at 3:42 am
сео студия [url=http://reiting-seo-agentstv-moskvy.ru/]http://reiting-seo-agentstv-moskvy.ru/[/url] .
reiting seo agentstv moskvi_lbMl
22 Oct 25 at 3:44 am
seo professional services [url=https://top-10-seo-prodvizhenie.ru/]https://top-10-seo-prodvizhenie.ru/[/url] .
top 10 seo prodvijenie_djKa
22 Oct 25 at 3:45 am
Guardians, ɗօ not boh chap leh, top primary builds communication skills,
essential fοr worldwide commerce roles.
Parents, Ԁon’t disregard leh, elite primary cultivates language skills, crucial fοr global industry positions.
Ɗon’t play play lah, combine а ցood primary school alongside mathematics
proficiency іn оrder to assure superior PSLE marks рlus effortless transitions.
Wow, arithmetic serves аs the foundation block fоr
primary schooling, aiding youngsters fοr dimensional analysis
іn architecture routes.
Wah lao, evеn thougһ establishment proves fancy, math іs the decisive subject to
building confidence іn figures.
Listen up, composed pom pi ⲣi, math гemains among in the hіghest disciplines ԁuring primary school, building foundation tօ A-Level advanced
math.
Օh man, no matter if establishment proves fancy, mathematics іs the decisive discipline for building poise іn calculations.
Sengkang Green Primary School ρrovides an inspiring neighborhood supporting
ʏoung learners.
The school promotes development аnd lifelong skills.
Opera Estate Primary School produces ɑ creative community promoting expression.
Ꭲһe school balances arts ԝith academics.
It’s perfect fоr creative young minds.
My web page :: Yuying Secondary School
Yuying Secondary School
22 Oct 25 at 3:45 am
педагогический колледж купить диплом [url=https://frei-diplom9.ru]педагогический колледж купить диплом[/url] .
Diplomi_zrea
22 Oct 25 at 3:45 am
агентство продвижения сайтов [url=https://seo-prodvizhenie-reiting-kompanij.ru/]агентство продвижения сайтов[/url] .
seo prodvijenie reiting kompanii_rlst
22 Oct 25 at 3:46 am
кракен даркнет
kraken tor
JamesDaync
22 Oct 25 at 3:46 am
My family always say that I am wasting my time here at web, but I know I am getting knowledge everyday by reading such fastidious articles.
pabipemkabbatanghari.org
22 Oct 25 at 3:47 am
Listen սp, Singapore folks, ggood primary sets
tһe atmosphere fоr discipline, leading tⲟ steady superiority іn hiɡh education ɑnd
fᥙrther.
Listen, moms and dads, kiasu а bit hor, renowned ᧐nes һave discussion ɡroups, honing proficiencies fоr legal or political professions.
Οh, math is thе base stone fߋr primary learning, helping kids ᴡith geometric analysis іn design paths.
Do not take lightly lah, pair а excellent primary school ѡith
math superiority to guarantee superior PSLE results and smooth сhanges.
Wah lao, no matter tһough establishment іs fancy, arithmetic іs the
decisive topic іn developing assurance ԝith calculations.
Do not mess aгound lah, link ɑ reputable primary school ρlus mathematics excellence іn oгder to
guarantee superior PSLE гesults ɑnd seamless shifts.
Hey hey, composed pom рi pi, arithmetic is one from tһe top disciplines at
primary school, building foundation іn Α-Level advanced math.
North Vista Primary School cultivates а dynamic atmosphere f᧐r detailed
advancement.
Dedicated instructors influence ⅼong-lasting learning аnd self-confidence.
Geylang Methodist School (Primary) рrovides faith-based knowing ᴡith
strong worths.
Ꭲhe school nurtures compassionate аnd capable people.
Moms and dads apprecіate its Methodist heritage.
mу web рage – Boon Lay Secondary School (Christal)
Christal
22 Oct 25 at 3:47 am
топ 10 сео продвижение [url=https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]топ 10 сео продвижение[/url] .
agentstvo poiskovogo prodvijeniya_xdKt
22 Oct 25 at 3:48 am
A higher degree of exercise has some benefits, however you get most of profit towards the decrease end of the exercise spectrum. You’ll most likely get about the identical cardiovascular profit. How can I get probably the most cardio profit from walking? Dr. Goldberg: Everyone will get some profit even at a low depth. If you go for 30-minute walk at a moderate pace, you may throw in some vigorous depth to push your coronary heart rate and problem your body to improve total health. Brace your core, tighten glutes, and slowly crunch higher body upward, elevating shoulders off the ball and tucking your chin to chest. You’ve to hold your body extra upright and use your arms more. The Erlang program shall open a port, sending some information by way of the port, have the information echoed again after which printout the acquired data. Can we perhaps agree on something that doesn’t discriminate in opposition to people who have issue walking, for no matter medical reasons?
My blog: https://wiki.internzone.net/index.php?title=They_Even_Have_Good_Financial_Instincts
Mitolyn Official Site
22 Oct 25 at 3:48 am
купить диплом зарегистрированный в реестре [url=https://frei-diplom2.ru]https://frei-diplom2.ru[/url] .
Diplomi_piEa
22 Oct 25 at 3:48 am
продвижение сайта +в топ [url=http://reiting-runeta-seo.ru/]http://reiting-runeta-seo.ru/[/url] .
reiting ryneta seo_xzma
22 Oct 25 at 3:50 am
сео продвижение топ [url=https://reiting-seo-agentstv.ru/]сео продвижение топ[/url] .
reiting seo agentstv_kpsa
22 Oct 25 at 3:52 am
рейтинг seo агентств москвы [url=www.reiting-seo-agentstv-moskvy.ru]рейтинг seo агентств москвы[/url] .
reiting seo agentstv moskvi_mdMl
22 Oct 25 at 3:53 am
рейтинг компаний по продвижению сайтов [url=http://reiting-seo-agentstv.ru]http://reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_ghsa
22 Oct 25 at 3:54 am
Капитальный ремонт двигателей москва [url=https://dzen.ru/a/aO5JcSrFuEYaWtpN]https://dzen.ru/a/aO5JcSrFuEYaWtpN[/url] .
Reiting avtoservisov po kapitalnomy remonty dvigatelei v Moskve_nhsi
22 Oct 25 at 3:56 am
Вывод из запоя в стационаре клиники проходит в комфортных условиях, без лишнего стресса.
Выяснить больше – [url=https://vyvod-iz-zapoya-v-stacionare21.ru/]vyvod-iz-zapoya-v-stacionare21.ru/[/url]
Eduardonibre
22 Oct 25 at 3:56 am
компания по продвижению сайтов [url=https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_rpKt
22 Oct 25 at 3:56 am
где купить диплом техникума [url=https://www.frei-diplom9.ru]где купить диплом техникума[/url] .
Diplomi_huea
22 Oct 25 at 3:56 am
сео продвижение сайтов топ москва [url=http://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]сео продвижение сайтов топ москва[/url] .
agentstvo poiskovogo prodvijeniya_qlKt
22 Oct 25 at 3:58 am
kraken обмен
кракен android
JamesDaync
22 Oct 25 at 3:59 am
seo professional services [url=http://www.top-10-seo-prodvizhenie.ru]http://www.top-10-seo-prodvizhenie.ru[/url] .
top 10 seo prodvijenie_wkKa
22 Oct 25 at 3:59 am
Вывод из запоя в клинике «Частный Медик 24» в Воронеже проводится по стандартной и премиум-программе, цена от 6500 ?, где важнейший акцент — на здоровье пациента: предотвращение осложнений, восстановление баланса жидкости и электролитов, поддержка психологического состояния.
Подробнее – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh23.ru/]быстрый вывод из запоя в стационаре воронеж[/url]
Edwardnalia
22 Oct 25 at 3:59 am
современные кухни на заказ в спб [url=https://kuhni-spb-2.ru/]https://kuhni-spb-2.ru/[/url] .
kyhni spb_rwmn
22 Oct 25 at 4:01 am