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.rudik-diplom2.ru/]купить диплом в киселевске[/url] .
Diplomi_gepi
15 Oct 25 at 6:00 am
Seth Gamble
Brentsek
15 Oct 25 at 6:01 am
медсестра которая купила диплом врача [url=https://www.frei-diplom13.ru]https://www.frei-diplom13.ru[/url] .
Diplomi_aakt
15 Oct 25 at 6:01 am
диплом техникума с отличием купить пять плюс [url=http://www.frei-diplom8.ru]диплом техникума с отличием купить пять плюс[/url] .
Diplomi_zasr
15 Oct 25 at 6:06 am
купить диплом оценщика [url=www.rudik-diplom10.ru/]купить диплом оценщика[/url] .
Diplomi_yfSa
15 Oct 25 at 6:08 am
диплом техникум купить [url=http://frei-diplom11.ru]диплом техникум купить[/url] .
Diplomi_thsa
15 Oct 25 at 6:08 am
купить диплом с проводкой меня [url=https://frei-diplom1.ru]купить диплом с проводкой меня[/url] .
Diplomi_laOi
15 Oct 25 at 6:09 am
Hi there, this weekend is good in support of me, since this point in time i am reading this impressive educational post here at
my residence.
web site
15 Oct 25 at 6:10 am
купить диплом в октябрьском [url=www.rudik-diplom6.ru]купить диплом в октябрьском[/url] .
Diplomi_cqKr
15 Oct 25 at 6:10 am
потолочкин натяжные потолки самара официальный сайт [url=http://natyazhnye-potolki-samara-2.ru]http://natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_xePi
15 Oct 25 at 6:11 am
Hey there! I just wanted to ask if you ever have any problems with hackers?
My last blog (wordpress) was hacked and I ended up losing many months of hard work due
to no backup. Do you have any solutions to prevent hackers?
82200219 singapore
15 Oct 25 at 6:11 am
купить диплом спб занесением реестр [url=http://frei-diplom2.ru]купить диплом спб занесением реестр[/url] .
Diplomi_piEa
15 Oct 25 at 6:11 am
купить диплом легальный о высшем образовании [url=www.frei-diplom3.ru]www.frei-diplom3.ru[/url] .
Diplomi_wcKt
15 Oct 25 at 6:11 am
купить диплом инженера по охране труда [url=https://rudik-diplom10.ru/]купить диплом инженера по охране труда[/url] .
Diplomi_svSa
15 Oct 25 at 6:14 am
купить диплом штукатура [url=rudik-diplom9.ru]rudik-diplom9.ru[/url] .
Diplomi_ijei
15 Oct 25 at 6:15 am
درود برای همه زیرا جستجو پول آسان میباشند.
وبسایتهای شرطبندی فریب گستردهای
هستند اینکه منجر وابستگی به علاوه ضرر شدید مینمایند.
آشنایم بیشمار پول نابود کردم و اکنون ناراحت میگردم.
خواهش میکنم پرهیز کنید و از امور مثبت روی شوید!
باخت سریع شرط بندی
15 Oct 25 at 6:18 am
купить диплом о высшем образовании с занесением в реестр [url=www.frei-diplom3.ru/]купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_osKt
15 Oct 25 at 6:21 am
купить диплом техникума в калининграде [url=www.frei-diplom8.ru/]купить диплом техникума в калининграде[/url] .
Diplomi_yisr
15 Oct 25 at 6:21 am
купить диплом с занесением в реестр в спб [url=https://frei-diplom2.ru]https://frei-diplom2.ru[/url] .
Diplomi_qdEa
15 Oct 25 at 6:22 am
где купить диплом техникума в нижнем новгороде [url=www.frei-diplom11.ru/]где купить диплом техникума в нижнем новгороде[/url] .
Diplomi_nlsa
15 Oct 25 at 6:24 am
купить диплом ижевск с занесением в реестр [url=www.frei-diplom1.ru/]купить диплом ижевск с занесением в реестр[/url] .
Diplomi_alOi
15 Oct 25 at 6:25 am
купить диплом в симферополе [url=www.rudik-diplom2.ru/]www.rudik-diplom2.ru/[/url] .
Diplomi_llpi
15 Oct 25 at 6:26 am
Disney made a smart choice’
Despite the comparisons, Abu Dhabi isn’t positioning itself as a direct rival to Orlando — it’s aiming to be something more. The emirate sees its theme parks as part of a bigger portfolio of attractions, alongside cultural landmarks, luxury hotels, pristine beaches, and desert adventures.
[url=http://trips45.cc]tripscan[/url]
A 15-minute drive from Yas Island, Saadiyat Island is home to the Louvre Abu Dhabi, a franchised outpost of the famous Paris art museum, which welcomed 1.4 million visitors last year, 84% from abroad. The Guggenheim Abu Dhabi and Zayed National Museum are both under construction, adding to a cultural district that will be one of the region’s most concentrated hubs of art and heritage.
“Abu Dhabi’s unique appeal lies in the diversity of our tourism offering,” Al Geziry added. “For thrill-seekers, we have record-breaking roller coasters and dune bashing in the desert. For culture lovers, historic sites like Al Ain Oasis and institutions like the Saadiyat museums. And for luxury travelers, world-class dining, private island resorts, and high-end shopping.
“Where else can you start your day under the Louvre’s iconic rain-of-light dome and end it in the immersive, story-driven worlds of Warner Bros. World or Ferrari World?”
http://trips45.cc
trip scan
Still, not everyone is convinced that Disney’s expansion into the Middle East is a sure bet.
“The region has seen its share of false starts,” says Dennis Speigel, founder of the International Theme Park Services consultancy, comparing it to neighboring Dubai’s patchy record with theme park expansion ambitions in the mid-2010s. “Several of them struggled for profitability in their first decade.”
Related article
Saadiyat Cultural District in Abu Dhabi is set to become one of the world’s preeminent arts and culture hubs, with one of the highest concentrations of cultural institutions globally. But the area isn’t just for art connoisseurs. Explore what to do in the new district, from iconic museums to luxurious beach days to decadent dining options.
You can walk between the Louvre and the Guggenheim in this new art district
Spiegel believes Abu Dhabi is different. “Disney made a smart choice. The infrastructure, safety, and existing leisure developments create an ideal entry point,” he told CNN earlier this year. “It’s a much more controlled and calculated move.”
Under its Tourism Strategy 2030, Abu Dhabi aims to grow annual visitors from 24 million in 2023 to more than 39 million by the end of the decade. With Disneyland as a centerpiece, those targets may well be surpassed. The city’s population has already grown from 2.7 million in 2014 to more than 4.1 million today, a reflection of its rising profile as a regional hub.
Yas Island alone has been transformed in the space of a decade from a largely undeveloped stretch of sand to a self-contained resort destination, complete with golf courses, marinas, a mall, more than 160 restaurants, and a cluster of high-end hotels.
Orlando’s head start remains formidable — it still offers multiple Disney and Universal parks, has decades of brand loyalty, and an infrastructure built to handle tens of millions of tourists annually.
But Abu Dhabi is catching up fast. Its combination of frictionless travel, year-round comfort, cutting-edge attractions, and a cultural scene that adds depth to the experience gives Abu Dhabi its own unique selling point, potentially offering a model for the next generation of theme park capital.
RobertMaw
15 Oct 25 at 6:26 am
Snagged $MTAUR early; price jumps motivate. Presale’s ecosystem cohesive. Minotaur hero cool.
minotaurus coin
WilliamPargy
15 Oct 25 at 6:27 am
самара натяжные потолки [url=https://www.natyazhnye-potolki-samara-2.ru]самара натяжные потолки[/url] .
natyajnie potolki samara_zqPi
15 Oct 25 at 6:28 am
https://telegra.ph/Kupit-benzogenerator-karver-75-kvat-10-12-3
RonaldZer
15 Oct 25 at 6:28 am
makeprogressdaily – Love the simple design, very easy to navigate through.
Victoria Haldeman
15 Oct 25 at 6:28 am
fetish
Brentsek
15 Oct 25 at 6:29 am
Лазерные станки https://raymark.ru для резки металла в Москве. 20 лет на рынке, выгодная цена, скидка 5% при заявке с сайта + обучение
raymark-152
15 Oct 25 at 6:30 am
потолочек су [url=https://natyazhnye-potolki-samara-2.ru/]потолочек су[/url] .
natyajnie potolki samara_zmPi
15 Oct 25 at 6:32 am
диплом купить с проведением [url=frei-diplom1.ru]диплом купить с проведением[/url] .
Diplomi_gcOi
15 Oct 25 at 6:33 am
Лазерные станки https://raymark.ru для резки металла в Москве. 20 лет на рынке, выгодная цена, скидка 5% при заявке с сайта + обучение
raymark-113
15 Oct 25 at 6:33 am
HOME CLIMAT https://homeclimat36.ru кондиционеры и сплит системы в Воронеже. Скидка на монтаж от 3000 рублей! При покупке сплит-системы.
homeclimat36-37
15 Oct 25 at 6:36 am
https://www.imdb.com/list/ls4155661797/
mjrwtyl
15 Oct 25 at 6:37 am
купить диплом о высшем с занесением в реестр [url=www.frei-diplom1.ru]купить диплом о высшем с занесением в реестр[/url] .
Diplomi_daOi
15 Oct 25 at 6:39 am
HOME CLIMAT https://homeclimat36.ru кондиционеры и сплит системы в Воронеже. Скидка на монтаж от 3000 рублей! При покупке сплит-системы.
homeclimat36-555
15 Oct 25 at 6:39 am
купить диплом в северодвинске [url=http://rudik-diplom10.ru]купить диплом в северодвинске[/url] .
Diplomi_ctSa
15 Oct 25 at 6:41 am
купить диплом фельдшера [url=http://rudik-diplom9.ru/]купить диплом фельдшера[/url] .
Diplomi_cwei
15 Oct 25 at 6:41 am
купить свидетельство о заключении брака [url=www.rudik-diplom6.ru/]купить свидетельство о заключении брака[/url] .
Diplomi_mjKr
15 Oct 25 at 6:44 am
купить новый диплом [url=https://www.rudik-diplom7.ru]купить новый диплом[/url] .
Diplomi_ibPl
15 Oct 25 at 6:45 am
купить диплом техникума в самаре [url=https://frei-diplom9.ru]купить диплом техникума в самаре[/url] .
Diplomi_ybea
15 Oct 25 at 6:46 am
купить диплом в екатеринбурге [url=https://www.rudik-diplom2.ru]купить диплом в екатеринбурге[/url] .
Diplomi_ucpi
15 Oct 25 at 6:46 am
натяжные потолки от производителя в самаре [url=natyazhnye-potolki-samara-2.ru]натяжные потолки от производителя в самаре[/url] .
natyajnie potolki samara_jrPi
15 Oct 25 at 6:47 am
Купить диплом ВУЗа мы поможем. Мы поможем купить диплом юриста – [url=http://diplomybox.com/diplom-yurista/]diplomybox.com/diplom-yurista[/url]
Cazriyg
15 Oct 25 at 6:47 am
https://www.imdb.com/list/ls4155243441/
nlgmxnl
15 Oct 25 at 6:48 am
Запой — это не просто многодневное употребление алкоголя, а тяжёлое нарушение обмена веществ, работы сердца, нервной системы и внутренних органов. Без медицинской помощи резко возрастает риск развития осложнений: делирий, судороги, инсульт, сердечная недостаточность, тяжёлое обезвоживание и нарушения психики. Симптомы могут прогрессировать в любое время, причём угроза для жизни появляется внезапно.
Разобраться лучше – https://vyvod-iz-zapoya-shchelkovo6.ru/skoryj-vyvod-iz-zapoya-v-shchelkovo/
Davidlut
15 Oct 25 at 6:48 am
где можно купить диплом техникума в омске [url=https://www.frei-diplom8.ru]где можно купить диплом техникума в омске[/url] .
Diplomi_kbsr
15 Oct 25 at 6:48 am
Watch out, Orlando, a new world theme park capital is rising in the Arabian desert
[url=https://tripscan44.cc]трип скан[/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
tripscan
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 6:49 am
купить диплом в воронеже [url=http://rudik-diplom13.ru]купить диплом в воронеже[/url] .
Diplomi_fgon
15 Oct 25 at 6:50 am
купить медицинский диплом медсестры [url=frei-diplom13.ru]купить медицинский диплом медсестры[/url] .
Diplomi_bdkt
15 Oct 25 at 6:51 am