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!
Hi there, yes this paragraph is in fact pleasant
and I have learned lot of things from it concerning blogging.
thanks.
roofing companies
15 Oct 25 at 3:16 am
http://britmedsdirect.com/# UK online pharmacy without prescription
Raymondspemn
15 Oct 25 at 3:19 am
купить диплом в екатеринбург реестр [url=www.frei-diplom1.ru]купить диплом в екатеринбург реестр[/url] .
Diplomi_rrOi
15 Oct 25 at 3:20 am
https://telegra.ph/Dji-matrice-300-rtk-kupit-10-12-4
RonaldZer
15 Oct 25 at 3:20 am
Greate pieces. Keep posting such kind of information on your site.
Im really impressed by it.
Hey there, You’ve performed a great job. I will definitely
digg it and in my opinion recommend to my friends. I’m sure they’ll be benefited from this website.
Clarum Monerra
15 Oct 25 at 3:21 am
I know this if off topic but I’m looking into starting my own weblog and was
curious 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 smart so I’m not 100% positive. Any tips
or advice would be greatly appreciated. Thanks
Paito Warna Sydney 6D Master Lengkap
15 Oct 25 at 3:21 am
Snagged more $MTAUR; referrals pay. Presale’s value jumps. Minotaur customizable.
minotaurus coin
WilliamPargy
15 Oct 25 at 3:21 am
https://medreliefuk.com/# cheap prednisolone in UK
HerbertScacy
15 Oct 25 at 3:22 am
Hi there it’s me, I am also visiting this website
on a regular basis, this website is really pleasant and the users are truly sharing fastidious thoughts.
Chariot SACS
15 Oct 25 at 3:22 am
Winpro129
| Daftar Link Situs Slot Paling Gacor Malam ini Kosisten Pasti
Menang !!!
Winpro129
15 Oct 25 at 3:25 am
купить диплом в ессентуках [url=https://rudik-diplom13.ru/]купить диплом в ессентуках[/url] .
Diplomi_cwon
15 Oct 25 at 3:25 am
купить диплом инженера по охране труда [url=https://www.rudik-diplom2.ru]купить диплом инженера по охране труда[/url] .
Diplomi_mepi
15 Oct 25 at 3:29 am
купить диплом в гуково [url=www.rudik-diplom9.ru/]купить диплом в гуково[/url] .
Diplomi_vyei
15 Oct 25 at 3:30 am
купить диплом с занесением в реестр в украине [url=www.frei-diplom1.ru/]www.frei-diplom1.ru/[/url] .
Diplomi_rmOi
15 Oct 25 at 3:31 am
E28BET भारत में आपका स्वागत है – आपकी जीत, पूरी तरह से भुगतान। रोमांचक बोनस का आनंद लें,
रोमांचक खेल खेलें, और एक निष्पक्ष और आरामदायक ऑनलाइन
सट्टेबाजी का अनुभव करें। अभी पंजीकरण करें!
E28BET भारत – आपकी जीत
15 Oct 25 at 3:31 am
купить диплом с реестром красноярск [url=http://frei-diplom3.ru]купить диплом с реестром красноярск[/url] .
Diplomi_kzKt
15 Oct 25 at 3:31 am
купить легально диплом [url=http://frei-diplom2.ru/]купить легально диплом[/url] .
Diplomi_igEa
15 Oct 25 at 3:31 am
best UK online chemist for Prednisolone [url=https://medreliefuk.com/#]order steroid medication safely online[/url] MedRelief UK
Jameshoasy
15 Oct 25 at 3:32 am
купить диплом в ялте [url=https://rudik-diplom6.ru/]купить диплом в ялте[/url] .
Diplomi_zyKr
15 Oct 25 at 3:34 am
потолочкин ру натяжные потолки отзывы [url=http://natyazhnye-potolki-samara-2.ru/]http://natyazhnye-potolki-samara-2.ru/[/url] .
natyajnie potolki samara_ehPi
15 Oct 25 at 3:37 am
купить диплом в ялте [url=http://rudik-diplom10.ru/]купить диплом в ялте[/url] .
Diplomi_ghSa
15 Oct 25 at 3:39 am
купить диплом в тольятти [url=https://rudik-diplom2.ru/]купить диплом в тольятти[/url] .
Diplomi_nwpi
15 Oct 25 at 3:41 am
купить диплом автомобильного техникума с [url=www.frei-diplom10.ru]купить диплом автомобильного техникума с[/url] .
Diplomi_hdEa
15 Oct 25 at 3:43 am
Very good article. I certainly appreciate this website.
Continue the good work!
دنس بت
15 Oct 25 at 3:44 am
купить диплом в новоуральске [url=http://rudik-diplom9.ru]http://rudik-diplom9.ru[/url] .
Diplomi_fiei
15 Oct 25 at 3:45 am
сайт натяжной потолок [url=https://natyazhnye-potolki-samara-2.ru]https://natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_zyPi
15 Oct 25 at 3:48 am
купить диплом техникум заочная форма обучения иркутск [url=https://www.frei-diplom9.ru]купить диплом техникум заочная форма обучения иркутск[/url] .
Diplomi_woea
15 Oct 25 at 3:49 am
Right away I am ready to do my breakfast, afterward having my breakfast coming yet
again to read further news.
kra41
15 Oct 25 at 3:50 am
https://telegra.ph/Kupit-botinki-takticheskie-ustavnye-10-12-5
RonaldZer
15 Oct 25 at 3:51 am
What’s up to every one, because I am actually eager of
reading this webpage’s post to be updated on a regular basis.
It includes pleasant information.
Finxor GPT
15 Oct 25 at 3:51 am
купить диплом в калуге [url=http://www.rudik-diplom10.ru]купить диплом в калуге[/url] .
Diplomi_fiSa
15 Oct 25 at 3:51 am
At this moment I am ready to do my breakfast, when having
my breakfast coming yet again to read other news.
easy C5A file viewer
15 Oct 25 at 3:52 am
купить диплом в вологде [url=www.rudik-diplom7.ru]купить диплом в вологде[/url] .
Diplomi_fdPl
15 Oct 25 at 3:52 am
Купить диплом о высшем образовании поможем. Купить диплом техникума, колледжа в Липецке – [url=http://diplomybox.com/kupit-diplom-tekhnikuma-kolledzha-v-lipetske/]diplomybox.com/kupit-diplom-tekhnikuma-kolledzha-v-lipetske[/url]
Cazrwyk
15 Oct 25 at 3:53 am
Watch out, Orlando, a new world theme park capital is rising in the Arabian desert
[url=https://tripscan44.cc]tripscan[/url]
For decades, Orlando has reigned as the global capital of theme parks — a place where Disney, Universal, SeaWorld and countless other attractions have drawn millions of visitors.
But a challenger for the crown has emerged from an unlikely place: the deserts of the Arabian Gulf. In a destination once known more for oil wealth and camel racing than roller coasters, Abu Dhabi is building an adrenaline-charged playground that could give Orlando a run for its money.
And it just landed the ultimate weapon: Disney.
https://tripscan44.cc
трипскан
In May 2025, when Disney announced its first new theme park in 15 years, it chose Abu Dhabi over other key theme park destinations in California, Japan and even Orlando.
There was “no question,” says Josh D’Amaro, chairman of Disney Experiences. The UAE capital, already home to Ferrari World, with the world’s fastest roller coaster; Warner Bros. World (built under license by CNN’s parent company, Warner Brothers Discovery); Yas Waterworld, an epic network of slides and pools; and more recently, SeaWorld Yas Island Abu Dhabi. It’s clear the emirate is emerging as the most serious challenger Orlando has ever faced.
Ferrari World Abu Dhabi is home to the world’s fastest rollercoaster and the highest loop ride.
Ferrari World Abu Dhabi is home to the world’s fastest rollercoaster and the highest loop ride. Leisa Tyler/LightRocket/Getty Images
Disneyland Abu Dhabi, expected to open on Yas Island in the early 2030s, will be the company’s most technologically advanced park ever. Renderings show a shimmering, futuristic tower at its center — more closely resembling Abu Dhabi’s gleaming skyline than a traditional European castle. It will be the first Disney resort set on an accessible shoreline, located just 20 minutes from downtown Abu Dhabi.
Related video
What began as a shared passion between two friends has grown into the “Abu Dhabi House Movement” — a fast-growing community redefining the city’s music scene. Co-founder Tom Worton takes us inside this grassroots world, where music lovers, DJs, and cultural spaces collide.
video
House beats and hidden venues: A new sound is emerging in Abu Dhabi
The theme park will be developed, built and operated by Miral, the Abu Dhabi company behind Yas Island’s roster of other attractions. Disney Imagineers will handle creative design and operational oversight, making sure the new park is in keeping with Disney’s brand.
Miral’s CEO, Mohamed Abdalla Al Zaabi, says demand already exists: 2024 saw a 20% rise in theme park attendance on Yas Island. And expansion is already in the works — a Harry Potter–themed land at Warner Bros. World, more record-breaking rides at Ferrari World, new themed hotels, and even two beaches along Yas Bay Waterfront.
‘This isn’t about building another theme park’
disney 3.jpg
Why Disney chose Abu Dhabi for their next theme park location
7:02
Abu Dhabi’s location, a medium-haul flight away from both Europe and Asia, and relatively short hop away from India, means millions of potential visitors are within relatively easy reach.
“This isn’t about building another theme park,” Saleh Mohamed Al Geziry, Abu Dhabi’s director general of tourism, told CNN. “It’s about defining Abu Dhabi as a global destination where culture, entertainment and luxury intersect.”
DanielZep
15 Oct 25 at 3:55 am
купить диплом в киселевске [url=https://rudik-diplom9.ru/]купить диплом в киселевске[/url] .
Diplomi_wiei
15 Oct 25 at 3:57 am
потолочкин [url=www.natyazhnye-potolki-samara-2.ru/]потолочкин[/url] .
natyajnie potolki samara_wvPi
15 Oct 25 at 3:58 am
диплом техникума торгового купить [url=https://frei-diplom10.ru/]диплом техникума торгового купить[/url] .
Diplomi_diEa
15 Oct 25 at 3:59 am
купить диплом техникума строительного [url=https://frei-diplom8.ru]купить диплом техникума строительного[/url] .
Diplomi_bdsr
15 Oct 25 at 4:00 am
I’m not positive the place you’re getting your info, but good topic.
I needs to spend a while finding out more or understanding more.
Thank you for excellent info I used to be on the
lookout for this information for my mission.
beste casino norge
15 Oct 25 at 4:00 am
Franchising Path Carlsbad
Carlsbad, ϹA 92008, United Stateѕ
+18587536197
franchise consultants in hyderabad
franchise consultants in hyderabad
15 Oct 25 at 4:00 am
медсестра которая купила диплом врача [url=frei-diplom13.ru]frei-diplom13.ru[/url] .
Diplomi_zvkt
15 Oct 25 at 4:02 am
MedRelief UK [url=http://medreliefuk.com/#]buy corticosteroids without prescription UK[/url] buy prednisolone
Jameshoasy
15 Oct 25 at 4:04 am
http://www.kalyamalya.ru/modules/newbb_plus/viewtopic.php?topic_id=20713&post_id=100023&order=0&viewmode=flat&pid=0&forum=4#100023
Nathanhip
15 Oct 25 at 4:05 am
диплом техникума купить киев [url=www.frei-diplom9.ru/]диплом техникума купить киев[/url] .
Diplomi_xcea
15 Oct 25 at 4:05 am
купить диплом техникума ссср в волжске [url=http://frei-diplom11.ru]купить диплом техникума ссср в волжске[/url] .
Diplomi_cmsa
15 Oct 25 at 4:06 am
купить диплом в омске [url=https://www.rudik-diplom7.ru]купить диплом в омске[/url] .
Diplomi_lmPl
15 Oct 25 at 4:08 am
диплом техникум колледж купить [url=https://frei-diplom10.ru]https://frei-diplom10.ru[/url] .
Diplomi_hsEa
15 Oct 25 at 4:11 am
Keep on writing, great job!
best massage parlor
15 Oct 25 at 4:12 am
купить легальный диплом [url=https://frei-diplom1.ru]купить легальный диплом[/url] .
Diplomi_vrOi
15 Oct 25 at 4:12 am