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!
Cash Ultimate
Davidfes
19 Sep 25 at 11:14 pm
микрозаймы онлайн [url=http://zaimy-18.ru]микрозаймы онлайн[/url] .
zaimi_jkMl
19 Sep 25 at 11:15 pm
Hey! This is my first visit to your blog! We are
a group of volunteers and starting a new initiative
in a community in the same niche. Your blog provided us
valuable information to work on. You have done a wonderful job!
Margin Rivou
19 Sep 25 at 11:15 pm
Post writing is also a excitement, if you be acquainted with after that you can write if not it is complex to write.
крановое электрооборудование
19 Sep 25 at 11:16 pm
Venit suplimentar cu Farmasi Nutriplus! Alege o afacere la cheie, un venit online
cu Farmasi Nutriplus. Câștigi din vânzări directe, pentru că
beneficiezi de discount de până la 30% față de prețurile afișate în catalog Farmasi.
Farmasi Nutriplus
19 Sep 25 at 11:17 pm
Every weekend i used to go to see this website, because i wish for
enjoyment, since this this web site conations
in fact pleasant funny material too.
code bonus 1xbet sénégal
19 Sep 25 at 11:18 pm
Футболка с стильным принтом и футболки белые мужские в Костроме. Перчатки для сенсорных экранов женские и шарф серо розовый в Грозном. Футболки в полоску мужские и футболка ненависть в Липецке. Корпоративная одежда оптом и Scout одежда в Чебоксарах. Футболка оптом с логотипом найк и футболка с принтом Спб https://futbolki-s-printom.ru/
Gregorysnisp
19 Sep 25 at 11:18 pm
купить диплом в ханты-мансийске [url=http://rudik-diplom8.ru]купить диплом в ханты-мансийске[/url] .
Diplomi_yhMt
19 Sep 25 at 11:19 pm
great issues altogether, you simply won a emblem new reader.
What would you suggest in regards to your put up that you simply
made a few days in the past? Any sure?
трипскан вход
19 Sep 25 at 11:19 pm
купить диплом строителя [url=rudik-diplom11.ru]купить диплом строителя[/url] .
Diplomi_qzMi
19 Sep 25 at 11:19 pm
все займы на карту [url=http://zaimy-19.ru/]все займы на карту[/url] .
zaimi_qsKl
19 Sep 25 at 11:20 pm
When someone writes an post he/she maintains
the thought of a user in his/her mind that how a user can know it.
So that’s why this piece of writing is perfect. Thanks!
Teresita
19 Sep 25 at 11:20 pm
накрутка подписчиков тг
JerryBealo
19 Sep 25 at 11:22 pm
накрутка подписчиков в телеграм дешево
JerryBealo
19 Sep 25 at 11:23 pm
лучшие займы онлайн [url=www.zaimy-21.ru]лучшие займы онлайн[/url] .
zaimi_jhkl
19 Sep 25 at 11:24 pm
займы [url=https://www.zaimy-20.ru]https://www.zaimy-20.ru[/url] .
zaimi_rlPr
19 Sep 25 at 11:24 pm
куплю диплом медсестры в москве [url=http://www.frei-diplom13.ru]куплю диплом медсестры в москве[/url] .
Diplomi_kjkt
19 Sep 25 at 11:25 pm
купить диплом в верхней пышме [url=http://www.rudik-diplom8.ru]купить диплом в верхней пышме[/url] .
Diplomi_msMt
19 Sep 25 at 11:25 pm
купить диплом энергетика [url=http://rudik-diplom11.ru/]купить диплом энергетика[/url] .
Diplomi_lbMi
19 Sep 25 at 11:26 pm
Безупречный выбор игровых автоматов Вулкана оценит каждый посетитель виртуального зала.
казино онлайн
19 Sep 25 at 11:27 pm
как купить диплом техникума в казани [url=http://frei-diplom9.ru]как купить диплом техникума в казани[/url] .
Diplomi_uiea
19 Sep 25 at 11:27 pm
Awesome article.
GHL Review
19 Sep 25 at 11:28 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 11:28 pm
актуальные зеркала kraken kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
19 Sep 25 at 11:30 pm
Folks, fear the gap hor, maths groundwork гemains essential ɗuring Junior College іn understanding figures, vital ԝithin todaү’s
online market.
Goodness, even wһether establishment іѕ atas, maths acts ⅼike
the critical subject fⲟr cultivating poise іn calculations.
Anglo-Chinese School (Independent) Junior College оffers a faith-inspired education tһаt harmonizes intellectual pursuits ᴡith ethical values, empowering
students tօ end up beeing thoughtful international citizens.
Іtѕ International Baccalaureate program encourages crucial thinking аnd questions, supported Ƅy fіrst-rate resources аnd devoted teachers.
Trainees stand оut in a wide selection οf ϲo-curricular activities, fгom robotics to music, building versatility ɑnd
imagination. The school’ѕ emphasis оn service learning imparts а
sense of responsibility ɑnd community engagement from an еarly phase.
Graduates ɑre well-prepared fߋr distinguished universities, continuing ɑ tradition of
quality ɑnd stability.
Dunman Ηigh School Junior College differentiates іtself throuցh its
remarkable multilingual education framework, ѡhich skillfully
combines Eastern cultural knowledge ѡith Western analytical techniques, nurturing
trainees іnto flexible, culturally sensitive thimkers ԝho
are proficient аt bridging varied viewpoints in а globalized
worⅼd. The school’s incorporated ѕix-year program makes sᥙre a smooth ɑnd enriched shift,
including specialized curricula іn STEM fields ᴡith access to state-of-thе-art
reѕearch labs and in liberal arts ѡith immersive language immersion modules,
аll created tο promote intellectual depth ɑnd ingenious analytical.
In a nurturing ɑnd unified campus environment,
trainees actively participate іn management roles,
innovative ventures likе debate cⅼubs and cultural celebrations, аnd neighborhood
tasks tһat boost theіr social awareness and collective skills.
Ƭһе college’s robust international immersion initiatives, consisting of
trainee exchanges ѡith partner schools in Asia and Europe,
as well as international competitions, offer hands-оn experiences tһat sharpen cross-cultural proficiencies ɑnd prepare
trainees foг thriving in multicultural settings.
Ԝith a consistent record of outstanding academic efficiency, Dunman Ꮋigh School Junior
College’ѕ graduates safe ɑnd secure placements
іn premier universities worldwide, exhibiting tһe institution’s commitment to
fostering scholastic rigor, individual excellence, ɑnd a lifelong passion for learning.
Hey hey, composed pom ρi pi, math remаins among іn the һighest subjects ɗuring Junior College, establishing
groundwork іn A-Level calculus.
Aрart from establishment resources, focus սpon mathematics to prevent frequent pitfalls
ѕuch as inattentive blunders іn tests.
Ⲟh no, primary math teaches everyday applications such as financial planning, tһus make sսre your youngster grasps tһat
properly starting early.
Parents, competitive approach engaged lah, solid primary math guides
tο betteг STEM grasp as well aѕ tech dreams.
Wah, mathematics іs the foundation block in primary learning, assisting youngsters іn dimensional
reasoning for architecture paths.
Βе kiasu and seek help from teachers; A-levels reward tһose ԝho
persevere.
Aiyo, ᴡithout solid mathematics аt Junior College, regaгdless top establishment kids might stumble wіth next-level algebra,
ѕo build this noᴡ leh.
Also visit mү blog … Raffles Institution Junior College
Raffles Institution Junior College
19 Sep 25 at 11:31 pm
купить диплом колледжа недорого [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_dpea
19 Sep 25 at 11:33 pm
купить диплом техникума в сургуте [url=https://www.frei-diplom9.ru]купить диплом техникума в сургуте[/url] .
Diplomi_biea
19 Sep 25 at 11:34 pm
Специалист уточняет продолжительность запоя, тип употребляемого алкоголя и наличие сопутствующих заболеваний. Такой подробный анализ позволяет подобрать оптимальные методы детоксикации и снизить риск осложнений.
Детальнее – http://kapelnica-ot-zapoya-lugansk-lnr0.ru/kapelnicza-ot-zapoya-czena-lugansk-lnr/
MatthewShuth
19 Sep 25 at 11:35 pm
легально купить диплом [url=https://www.frei-diplom4.ru]легально купить диплом[/url] .
Diplomi_teOl
19 Sep 25 at 11:35 pm
купить диплом о среднем профессиональном образовании с занесением в реестр [url=http://www.frei-diplom5.ru]купить диплом о среднем профессиональном образовании с занесением в реестр[/url] .
Diplomi_efPa
19 Sep 25 at 11:36 pm
можно купить легальный диплом [url=https://frei-diplom3.ru]https://frei-diplom3.ru[/url] .
Diplomi_soKt
19 Sep 25 at 11:37 pm
купить диплом с занесением реестра [url=frei-diplom2.ru]купить диплом с занесением реестра[/url] .
Diplomi_oqEa
19 Sep 25 at 11:37 pm
купить проведенный диплом всеми [url=http://frei-diplom6.ru]купить проведенный диплом всеми[/url] .
Diplomi_euOl
19 Sep 25 at 11:38 pm
Clear Meds Hub: ClearMedsHub –
DerekStops
19 Sep 25 at 11:38 pm
In today’s fast-evolving financial landscape, it’s rare to find a platform that seamlessly bridges both crypto
and fiat operations, especially for large-scale operations.
However, I came across this discussion that dives deep into
a website which supports everything from buying Bitcoin to managing fiat payments, and it’s especially recommended for corporate accounts.
I found the topic to be incredibly insightful because it covers not
just the basics of buying crypto, but also the extended features like
multi-currency fiat support, bulk payment processing, and advanced tools for
businesses.
What’s particularly valuable is the level of detail provided in the
forum topic, including the pros and cons, user reviews, and case studies showing how enterprises have integrated the platform into their operations.
I’ve rarely come across such a balanced opinion that addresses both crypto-savvy users and traditional finance professionals,
especially in the context of business-scale needs.
It’s a long read, but this forum topic offers some of the most
detailed opinions on using crypto platforms for corporate and fiat operations alike.
Definitely worth digging into this website.
forum topic
19 Sep 25 at 11:39 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2web at
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 11:40 pm
купить диплом мед колледжа [url=www.frei-diplom9.ru/]купить диплом мед колледжа[/url] .
Diplomi_ccea
19 Sep 25 at 11:40 pm
накрутка подписчиков телеграм телеграмм
DavidNOb
19 Sep 25 at 11:40 pm
Very great post. I just stumbled upon your weblog and wanted to mention that I
have truly loved surfing around your blog posts.
After all I’ll be subscribing for your feed and I’m hoping you write
again very soon!
درمان سرفه های خشک آنفولانزا
19 Sep 25 at 11:41 pm
купить диплом техникума об окончании [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_opea
19 Sep 25 at 11:43 pm
купить диплом сантехника [url=http://rudik-diplom8.ru]купить диплом сантехника[/url] .
Diplomi_xoMt
19 Sep 25 at 11:44 pm
купить диплом с занесением в реестр пенза [url=http://www.frei-diplom4.ru]купить диплом с занесением в реестр пенза[/url] .
Diplomi_owOl
19 Sep 25 at 11:44 pm
prague plug https://cocaine-prague-shop.com
prague-drugs-582
19 Sep 25 at 11:44 pm
купить диплом в троицке [url=http://rudik-diplom1.ru/]http://rudik-diplom1.ru/[/url] .
Diplomi_zker
19 Sep 25 at 11:45 pm
купить диплом с проводкой моего [url=frei-diplom5.ru]купить диплом с проводкой моего[/url] .
Diplomi_ncPa
19 Sep 25 at 11:45 pm
In today’s fast-evolving financial landscape, it’s rare to find a platform that seamlessly bridges both crypto and
fiat operations, especially for large-scale operations. However, I came across this forum topic that dives deep into a website which supports everything from buying Bitcoin to
managing fiat payments, and it’s especially recommended for
corporate accounts.
The opinion shared by users in the discussion made it clear that this platform is
more than just a simple exchange – it’s a full-fledged
financial ecosystem for both individuals and companies.
Whether you’re running a startup or managing finances for
a multinational corporation, the features highlighted in this discussion could be a game-changer – multi-user
accounts, compliance tools, fiat gateways, and crypto custody all in one.
I’ve rarely come across such a balanced discussion that addresses both crypto-savvy
users and traditional finance professionals, especially
in the context of business-scale needs.
Highly suggest taking a look if you’re involved in finance, tech, or enterprise operations.
The recommendation alone is worth checking out.
topic
19 Sep 25 at 11:45 pm
купить диплом о высшем образовании легально [url=frei-diplom3.ru]купить диплом о высшем образовании легально[/url] .
Diplomi_ofKt
19 Sep 25 at 11:45 pm
список займов онлайн [url=http://zaimy-22.ru]http://zaimy-22.ru[/url] .
zaimi_wzKi
19 Sep 25 at 11:45 pm
купить диплом в тобольске [url=http://rudik-diplom11.ru/]http://rudik-diplom11.ru/[/url] .
Diplomi_ytMi
19 Sep 25 at 11:46 pm
диплом купить с проводкой [url=http://frei-diplom2.ru/]диплом купить с проводкой[/url] .
Diplomi_prEa
19 Sep 25 at 11:46 pm