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=https://karniz-shtor-elektroprivodom.ru]https://karniz-shtor-elektroprivodom.ru[/url] .
karniz dlya shtor s elektroprivodom_pyer
14 Oct 25 at 7:27 am
купить проведенный диплом отзывы [url=https://frei-diplom5.ru]https://frei-diplom5.ru[/url] .
Diplomi_itPa
14 Oct 25 at 7:27 am
электрокранизы [url=www.karniz-elektroprivodom.ru/]www.karniz-elektroprivodom.ru/[/url] .
karniz elektroprivodom shtor kypit_vpei
14 Oct 25 at 7:28 am
натяжные потолки официальный [url=www.natyazhnye-potolki-samara-2.ru/]натяжные потолки официальный[/url] .
natyajnie potolki samara_vlPi
14 Oct 25 at 7:28 am
купить диплом медсестры [url=www.frei-diplom15.ru]купить диплом медсестры[/url] .
Diplomi_rvoi
14 Oct 25 at 7:30 am
best games
Brentsek
14 Oct 25 at 7:31 am
электрокарнизы в москве [url=https://www.elektrokarnizy797.ru]электрокарнизы в москве[/url] .
elektrokarnizi_etMl
14 Oct 25 at 7:31 am
автоматические рулонные шторы на окна [url=https://www.rulonnaya-shtora-s-elektroprivodom.ru]https://www.rulonnaya-shtora-s-elektroprivodom.ru[/url] .
rylonnaya shtora s elektroprivodom_hmKt
14 Oct 25 at 7:32 am
перепланировка нежилых помещений [url=www.pereplanirovka-nezhilogo-pomeshcheniya11.ru]перепланировка нежилых помещений[/url] .
pereplanirovka nejilogo pomesheniya_wxer
14 Oct 25 at 7:32 am
купить диплом продавца [url=http://rudik-diplom5.ru/]купить диплом продавца[/url] .
Diplomi_jpma
14 Oct 25 at 7:32 am
перепланировка нежилого помещения в многоквартирном доме [url=https://pereplanirovka-nezhilogo-pomeshcheniya9.ru]перепланировка нежилого помещения в многоквартирном доме[/url] .
pereplanirovka nejilogo pomesheniya_kbKl
14 Oct 25 at 7:32 am
аренда экскаватора погрузчика цена [url=https://arenda-ekskavatora-pogruzchika-cena-2.ru/]аренда экскаватора погрузчика цена[/url] .
arenda ekskavatora pogryzchika cena_uest
14 Oct 25 at 7:33 am
купить диплом о среднем профессиональном образовании с занесением в реестр [url=frei-diplom6.ru]купить диплом о среднем профессиональном образовании с занесением в реестр[/url] .
Diplomi_bgOl
14 Oct 25 at 7:33 am
купить диплом педагога [url=https://www.rudik-diplom3.ru]купить диплом педагога[/url] .
Diplomi_mzei
14 Oct 25 at 7:33 am
купить диплом в калининграде [url=www.rudik-diplom4.ru/]купить диплом в калининграде[/url] .
Diplomi_kfOr
14 Oct 25 at 7:35 am
Very nice post. I just stumbled upon your weblog and wished to say that I’ve really enjoyed surfing around
your blog posts. After all I’ll be subscribing to your
feed and I hope you write again very soon!
đoàn di băng bị bắt
14 Oct 25 at 7:35 am
Astronomers first discovered Cha 1107-7626 in 2008, and since then, they have observed it with different telescopes to learn more about how the infant planet evolves, as well as to study its surroundings.
[url=https://tlk-triga.ru/tral/]тралл машина[/url]
The research team observed the planet with Webb in 2024, making a clear detection of the surrounding disk. Next, the researchers studied it using the X-shooter spectrograph on the Very Large Telescope, which can capture different wavelengths of light emitted by an object ranging from ultraviolet to near-infrared.
The observations detected a puzzling event as the planet transitioned from a steady accretion rate in April and May to a burst of growth between June and August.
https://tlk-triga.ru/tarif/
грузоперевозки на дальние расстояния
“I fully expected that this is a short-term event, because those are much more common,” Scholz said. “When the burst kept going through July and August, I was absolutely stunned.”
Follow-up observations made using the Webb telescope also showed that the chemistry of the disk had changed. Water vapor, present during the growth spurt, wasn’t in the disk before. Webb is the only telescope capable of capturing such detailed changes in the environment for such a faint object, Scholz said. Prior to this research, astronomers had only ever seen the chemistry of a disk change around a star, but not around a planet.
Comparing observations from before and during the event showed that magnetic activity seems to be the main driver behind how much gas and dust is falling on the planet — a phenomenon typically associated with stars as they grow.
But the new observations suggest that objects with much less mass than stars — the rogue world is less than 1% the mass of our sun — can have strong magnetic fields capable of driving the growth of the object, according to the study authors.
An infrared image taken with the Visible and Infrared Telescope for Astronomy shows Cha 1107-7626, a dot located in the center.
An infrared image taken with the Visible and Infrared Telescope for Astronomy shows Cha 1107-7626, a dot located in the center. ESO/Meingast et al.
A planet that acts like a star
The origin of rogue planets remains murky. It’s possible they are planets that are kicked out of orbit around stars due to the gravitational influence of other objects. Or perhaps they are the lowest-mass objects that happen to form like stars. For Cha 1107-7626, astronomers said they think it’s the latter.
“This object most likely formed in a way similar to stars — from the collapse and fragmentation of a molecular cloud,” Scholz said.
A molecular cloud is a massive, cold cloud of gas and dust that can stretch for hundreds of light-years, according to NASA.
“We’re struck by quite how much the infancy of free-floating planetary-mass objects resembles that of stars like the Sun,” Jayawardhana said in a statement. “Our new findings underscore that similarity, and imply that some objects comparable to giant planets form the way stars do, from contracting clouds of gas and dust accompanied by disks of their own, and they go through growth episodes just like newborn stars.”
JustinRhila
14 Oct 25 at 7:36 am
купить диплом в ишиме [url=https://www.rudik-diplom5.ru]https://www.rudik-diplom5.ru[/url] .
Diplomi_ouma
14 Oct 25 at 7:37 am
карниз электро [url=www.karniz-elektroprivodom.ru/]www.karniz-elektroprivodom.ru/[/url] .
karniz elektroprivodom shtor kypit_idei
14 Oct 25 at 7:38 am
купить диплом украина с занесением в реестр [url=www.frei-diplom6.ru/]www.frei-diplom6.ru/[/url] .
Diplomi_boOl
14 Oct 25 at 7:39 am
перепланировка нежилого помещения в москве [url=https://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]перепланировка нежилого помещения в москве[/url] .
pereplanirovka nejilogo pomesheniya_peer
14 Oct 25 at 7:39 am
Parents, worry аbout the disparity hor, mathematics foundation гemains essential ԁuring Junior College for comprehending
data, crucial in today’s online economy.
Goodness, гegardless ѡhether institution іs high-end,
maths serves ɑs tһe critical discipline іn cultivating assurance reցarding figures.
Temasek Junior College influences trailblazers tһrough rigorous academics and ethical
values, mixing custom ԝith innovation. Ꭱesearch centers ɑnd electives in languages and arts promote deep learning.
Vibrant ϲo-curriculars build team effort ɑnd creativity.
International partnerships improve worldwide proficiency.
Alumni prosper іn prominent institutions, embodying excellence ɑnd service.
Tampines Meridian Junior College, born fгom the dynamic merger of Tampines Junior College and Meridian Junior College,
рrovides an innovative аnd culturally abundant education highlighted Ƅy specialized electives іn drama and Malay language,
supporting meaningful and multilingual skills in a forward-thinking community.
Τhe college’s innovative centers, including
theater ɑreas, commerce simulation labs, аnd science innovation hubs, assistance diverse
scholastic streams tһat motivate interdisciplinary expedition ɑnd սseful
skill-building throughout arts, sciences, and company.
Skill advaancement programs, coupled ԝith abroad immersion trips аnd cultural celebrations, foster strong management
qualities, cultural awareness, ɑnd flexibility to global
dynamics. Within a caring and understanding campus
culture, trainees tаke рart in health initiatives, peer support ѕystem, and co-curricular сlubs that promote
durability, psychological intelligence, аnd collaborative spirit.
Аs a result, Tampines Meridian Junior College’s
students accomplish holistic development ɑnd are well-prepared too tackle global obstacles, ƅecoming confident, flexible people ready fⲟr university success аnd beуond.
Eh eh, composed pom рi pі, maths іs аmong from the leading topics
Ԁuring Junior College, building foundation t᧐ A-Level calculus.
In adⅾition from establishment resources, emphasize ᴡith math for av᧐id
common pitfalls ⅼike careless blunders during assessments.
Wah lao, regardless if establishment remains fancy, math acts ⅼike the make-оr-break subject
tо building poise regaгding numbeгs.
Oһ no, primary maths educates practical սses like money management,
s᧐ makе sսre үߋur child grasps it correctly ƅeginning early.
Alas, lacking solid mathematics Ԁuring Junior College, no matter tоp establishment kids ϲould falter ѡith hіgh
school equations, ѕo develop itt рromptly leh.
Ꭰon’t be complacent; А-levels аre yoᥙr launchpad to entrepreneurial
success.
Αvoid take lightly lah, combine а good Junior College
alongside math superiority fоr guarantee elevated Ꭺ Levels marks as wеll
aѕ seamless transitions.
Parents, dread tһe difference hor, maths foundation гemains
critical in Junior College fօr understanding іnformation, essential іn current digital economy.
Ꮋere is my webpage Singapore Junior Colleges
Singapore Junior Colleges
14 Oct 25 at 7:39 am
https://www.imdb.com/list/ls4155634597/
hrmvujd
14 Oct 25 at 7:40 am
купить диплом инженера механика [url=https://rudik-diplom8.ru]купить диплом инженера механика[/url] .
Diplomi_kaMt
14 Oct 25 at 7:40 am
Wow! This blog looks exactly like my old one! It’s on a completely different subject but it has pretty much the
same layout and design. Superb choice of colors!
mv88
14 Oct 25 at 7:41 am
Купить диплом колледжа в Донецк [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_jeea
14 Oct 25 at 7:41 am
купить диплом в южно-сахалинске [url=https://rudik-diplom3.ru]купить диплом в южно-сахалинске[/url] .
Diplomi_huei
14 Oct 25 at 7:41 am
экскаватор погрузчик jcb аренда москва [url=https://arenda-ekskavatora-pogruzchika-cena-2.ru/]экскаватор погрузчик jcb аренда москва[/url] .
arenda ekskavatora pogryzchika cena_nwst
14 Oct 25 at 7:42 am
купить диплом об образовании с реестром [url=http://frei-diplom5.ru]купить диплом об образовании с реестром[/url] .
Diplomi_mjPa
14 Oct 25 at 7:43 am
купить свидетельство о браке [url=https://rudik-diplom4.ru]купить свидетельство о браке[/url] .
Diplomi_dfOr
14 Oct 25 at 7:43 am
купить диплом высшее [url=www.rudik-diplom11.ru/]купить диплом высшее[/url] .
Diplomi_byMi
14 Oct 25 at 7:44 am
аренда экскаватора погрузчика terex [url=http://www.arenda-ekskavatora-pogruzchika-cena-2.ru]http://www.arenda-ekskavatora-pogruzchika-cena-2.ru[/url] .
arenda ekskavatora pogryzchika cena_dxst
14 Oct 25 at 7:45 am
The $MTAUR ICO is community-focused with events. Token’s in-game role vital. Presale value clear.
minotaurus presale
WilliamPargy
14 Oct 25 at 7:45 am
рулонные шторы на большие окна [url=https://rulonnaya-shtora-s-elektroprivodom.ru/]рулонные шторы на большие окна[/url] .
rylonnaya shtora s elektroprivodom_dyKt
14 Oct 25 at 7:45 am
потолочкин натяжные потолки отзывы [url=https://stretch-ceilings-samara.ru/]https://stretch-ceilings-samara.ru/[/url] .
natyajnie potolki samara_vukl
14 Oct 25 at 7:46 am
купить диплом парикмахера [url=www.rudik-diplom3.ru/]купить диплом парикмахера[/url] .
Diplomi_weei
14 Oct 25 at 7:46 am
Howdy! Do you use Twitter? I’d like to follow you if that would be okay.
I’m definitely enjoying your blog and look
forward to new updates.
Also visit my web site teencarinsurance.z21.web.core.windows.net
teencarinsurance.z21.web.core.windows.net
14 Oct 25 at 7:47 am
переустройство нежилого помещения [url=http://pereplanirovka-nezhilogo-pomeshcheniya9.ru/]http://pereplanirovka-nezhilogo-pomeshcheniya9.ru/[/url] .
pereplanirovka nejilogo pomesheniya_wbKl
14 Oct 25 at 7:47 am
электрокарниз [url=www.karniz-elektroprivodom.ru/]электрокарниз[/url] .
karniz elektroprivodom shtor kypit_hzei
14 Oct 25 at 7:47 am
купить диплом с занесением в реестр в уфе [url=www.frei-diplom4.ru/]www.frei-diplom4.ru/[/url] .
Diplomi_efOl
14 Oct 25 at 7:47 am
купить диплом о образовании недорого [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_bpea
14 Oct 25 at 7:48 am
купить диплом в оренбурге [url=http://rudik-diplom4.ru]купить диплом в оренбурге[/url] .
Diplomi_gcOr
14 Oct 25 at 7:49 am
Hi! This is kind of off topic but I need some guidance from an established blog.
Is it difficult to set up your own blog? I’m not very
techincal but I can figure things out pretty quick.
I’m thinking about setting up my own but I’m not sure where to begin.
Do you have any ideas or suggestions? With thanks
Dornatrixel Erfahrungen
14 Oct 25 at 7:49 am
потолочник отзывы натяжные потолки [url=http://stretch-ceilings-samara-1.ru/]http://stretch-ceilings-samara-1.ru/[/url] .
natyajnie potolki samara_ecsl
14 Oct 25 at 7:49 am
перепланировка нежилых помещений [url=https://pereplanirovka-nezhilogo-pomeshcheniya10.ru/]перепланировка нежилых помещений[/url] .
pereplanirovka nejilogo pomesheniya_vjSr
14 Oct 25 at 7:49 am
аренда мини экскаватора с гидромолотом [url=www.arenda-mini-ekskavatora-v-moskve-2.ru]аренда мини экскаватора с гидромолотом[/url] .
arenda mini ekskavatora v moskve_idKt
14 Oct 25 at 7:51 am
электрокранизы [url=www.karniz-shtor-elektroprivodom.ru/]www.karniz-shtor-elektroprivodom.ru/[/url] .
karniz dlya shtor s elektroprivodom_pxer
14 Oct 25 at 7:51 am
купить диплом без занесения в реестр [url=www.frei-diplom5.ru]купить диплом без занесения в реестр[/url] .
Diplomi_jzPa
14 Oct 25 at 7:51 am
электрокарниз [url=www.karniz-elektroprivodom.ru]электрокарниз[/url] .
karniz elektroprivodom shtor kypit_mdei
14 Oct 25 at 7:52 am
разрешение на перепланировку нежилого помещения не требуется [url=www.pereplanirovka-nezhilogo-pomeshcheniya10.ru/]www.pereplanirovka-nezhilogo-pomeshcheniya10.ru/[/url] .
pereplanirovka nejilogo pomesheniya_faSr
14 Oct 25 at 7:52 am