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://www.zaimy-15.ru]займы онлайн[/url] .
zaimi_yzpn
18 Sep 25 at 8:34 am
купить украинский диплом о высшем образовании [url=www.educ-ua19.ru/]купить украинский диплом о высшем образовании[/url] .
Diplomi_cjml
18 Sep 25 at 8:34 am
https://www.grepmed.com/xictudogvyf
Timothyces
18 Sep 25 at 8:36 am
займ все [url=http://zaimy-14.ru/]http://zaimy-14.ru/[/url] .
zaimi_nxSr
18 Sep 25 at 8:36 am
You made some really good points there. I looked
on the internet for more info about the issue and
found most people will go along with your views on this site.
parenting resources
18 Sep 25 at 8:36 am
купить проведенный диплом Украина [url=educ-ua15.ru]educ-ua15.ru[/url] .
Diplomi_memi
18 Sep 25 at 8:38 am
микро займы онлайн [url=https://zaimy-11.ru/]https://zaimy-11.ru/[/url] .
zaimi_uvPt
18 Sep 25 at 8:40 am
What’s up colleagues, good paragraph and nice arguments commented at this place, I am genuinely enjoying by these.
آدرس دانشگاه علوم پزشکی زاهدان
18 Sep 25 at 8:42 am
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2web at
bs2best.at blacksprut marketplace Official
CharlesNarry
18 Sep 25 at 8:45 am
все займы ру [url=http://zaimy-14.ru/]http://zaimy-14.ru/[/url] .
zaimi_qlSr
18 Sep 25 at 8:45 am
Автоматические рулонные шторы не только обеспечивают удобство управления, но и стильный акцент в интерьере вашего дома, особенно если вы выберете [url=https://avtorulon.ru]автоматические рулонные шторы|автоматика для рулонных штор|автоматические шторы для труднодоступных окон[/url].
Использование автоматических рулонных штор приносит много преимуществ.
Прокарниз
18 Sep 25 at 8:45 am
раздвижной электрокарниз купить [url=www.razdvizhnoj-elektrokarniz.ru/]www.razdvizhnoj-elektrokarniz.ru/[/url] .
razdvijnoi elektrokarniz_mmei
18 Sep 25 at 8:48 am
займы все [url=www.zaimy-11.ru]www.zaimy-11.ru[/url] .
zaimi_ayPt
18 Sep 25 at 8:48 am
официальные займы онлайн на карту бесплатно [url=www.zaimy-15.ru]www.zaimy-15.ru[/url] .
zaimi_pipn
18 Sep 25 at 8:49 am
If you want to obtain much from this piece of writing then you have to apply these strategies to
your won blog.
HZ88
18 Sep 25 at 8:49 am
все займы ру [url=www.zaimy-14.ru/]www.zaimy-14.ru/[/url] .
zaimi_huSr
18 Sep 25 at 8:50 am
Этот информационный материал привлекает внимание множеством интересных деталей и необычных ракурсов. Мы предлагаем уникальные взгляды на привычные вещи и рассматриваем вопросы, которые волнуют общество. Будьте в курсе актуальных тем и расширяйте свои знания!
Уникальные данные только сегодня – https://cajascartonesdecolombia.com/speel-7900-gratis-online-casino-spellen
JosephWaype
18 Sep 25 at 8:50 am
Hi there, I enjoy reading all of your article post.
I like to write a little comment to support you.
online casino reviews
18 Sep 25 at 8:51 am
This is my first time pay a visit at here and i am really happy to read everthing
at one place.
Feel free to surf to my web page – site here
site here
18 Sep 25 at 8:51 am
мфо займ [url=www.zaimy-15.ru/]мфо займ[/url] .
zaimi_ftpn
18 Sep 25 at 8:53 am
электрокарниз двухрядный [url=www.razdvizhnoj-elektrokarniz.ru]www.razdvizhnoj-elektrokarniz.ru[/url] .
razdvijnoi elektrokarniz_utei
18 Sep 25 at 8:53 am
мфо займ онлайн [url=https://www.zaimy-11.ru]https://www.zaimy-11.ru[/url] .
zaimi_iiPt
18 Sep 25 at 8:53 am
Check out the leading promotions ߋn Kaizenaire.com, Singapore’s beѕt deals
website.
In thе vibrant city-ѕtate of Singapore, its shopping heaven ambiance fuels Singaporeans’ limitless
գuest of promotions.
Exercising calligraphy preserves conventional arts fоr heritage-loving Singaporeans, ɑnd remember to rеmain upgraded оn Singapore’s mߋst current promotions and shopping deals.
Adidas ցives sportswear аnd sneakers, cherished Ƅy Singaporeans
foг their stylish activewear ɑnd recommendation by local athletes.
SP Ꮐroup taкes care of electricity ɑnd gas utilities leh, valued by Singaporeans
fοr tһeir sustainable energy options ɑnd effective solution shipment one.
Muthu’ѕ Curry entices ѡith fiery fish head curry, favored
Ƅy spice fans for strong Indian flavors аnd generous portions.
Singaporeans, ԁo not Ƅe blur leh, Kaizenaire.com curates tһe mօѕt effective promotions ѕo you can gο shopping wise one.
Aⅼso visit my web blog; singapore shopping
singapore shopping
18 Sep 25 at 8:54 am
займы россии [url=https://zaimy-14.ru]https://zaimy-14.ru[/url] .
zaimi_lnSr
18 Sep 25 at 8:54 am
список займов онлайн [url=https://zaimy-15.ru]список займов онлайн[/url] .
zaimi_vspn
18 Sep 25 at 8:55 am
электрокарнизы цена [url=www.razdvizhnoj-elektrokarniz.ru/]www.razdvizhnoj-elektrokarniz.ru/[/url] .
razdvijnoi elektrokarniz_hmei
18 Sep 25 at 8:55 am
займ все [url=zaimy-11.ru]zaimy-11.ru[/url] .
zaimi_dnPt
18 Sep 25 at 8:55 am
http://www.pageorama.com/?p=fucebodi
Timothyces
18 Sep 25 at 8:58 am
You really make it seem really easy with your presentation but I in finding this
matter to be really one thing which I believe I might never understand.
It seems too complex and very extensive for me.
I’m having a look forward to your subsequent publish,
I will attempt to get the cling of it!
독학기숙학원
18 Sep 25 at 9:02 am
займ всем [url=https://zaimy-14.ru]https://zaimy-14.ru[/url] .
zaimi_phSr
18 Sep 25 at 9:03 am
купить диплом проведенный [url=www.educ-ua14.ru/]купить диплом проведенный[/url] .
Diplomi_vjkl
18 Sep 25 at 9:06 am
официальные займы онлайн на карту бесплатно [url=https://zaimy-14.ru/]https://zaimy-14.ru/[/url] .
zaimi_dwSr
18 Sep 25 at 9:08 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=https://trip-skan.win]trip scan[/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?”
https://trip-skan.win
tripscan top
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.
Braintop
18 Sep 25 at 9:09 am
сколько стоит купить диплом в одессе [url=https://www.educ-ua9.ru]сколько стоит купить диплом в одессе[/url] .
Diplomi_espr
18 Sep 25 at 9:10 am
займы онлайн [url=https://www.zaimy-14.ru]займы онлайн[/url] .
zaimi_waSr
18 Sep 25 at 9:12 am
диплом автотранспортного техникума купить в [url=www.educ-ua8.ru]www.educ-ua8.ru[/url] .
Diplomi_jzpt
18 Sep 25 at 9:13 am
Je suis accro a RollBit Casino, on dirait un labyrinthe de frissons numeriques. est une structure de sensations qui enchante. offrant des sessions de casino en direct qui deroulent comme un flux. Le service client du casino est un bit maitre. joignable par chat ou email. fluisent comme une sonate structuree. tout de meme des bonus de casino plus frequents seraient numeriques. Globalement, RollBit Casino promet un divertissement de casino cubique pour les amoureux des slots modernes de casino! En plus offre un orchestre de couleurs cubiques. ajoute une touche de rythme numerique au casino.
rollbit no deposit bonus|
whirlflameotter8zef
18 Sep 25 at 9:14 am
Hey very interesting blog!
video bokep
18 Sep 25 at 9:15 am
This site was… how do you say it? Relevant!!
Finally I’ve found something that helped me.
Kudos!
آدرس دانشگاه علوم پزشکی کردستان
18 Sep 25 at 9:16 am
Hey there just wanted to give you a quick heads up. The words in your content seem to be running off the screen in Opera.
I’m not sure if this is a format issue or something to do with web browser compatibility
but I thought I’d post to let you know. The layout look great though!
Hope you get the problem resolved soon. Thanks
https://lrnews.mirtesen.ru/blog/43983101538/Nevidimaya-zaschita-kamuflyazh
18 Sep 25 at 9:17 am
займы [url=zaimy-14.ru]zaimy-14.ru[/url] .
zaimi_ojSr
18 Sep 25 at 9:17 am
https://pubhtml5.com/homepage/ridor
Timothyces
18 Sep 25 at 9:20 am
Публикация предлагает читателю не просто информацию, а инструменты для анализа и саморазвития. Мы стимулируем критическое мышление, предлагая различные точки зрения и призывая к самостоятельному поиску решений.
Это стоит прочитать полностью – https://rickromano.com/rick-romano-waimea-bay
DanielGon
18 Sep 25 at 9:21 am
Hey this is somewhat of off topic but I was wondering if blogs use
WYSIWYG editors or if you have to manually code
with HTML. I’m starting a blog soon but have no coding
know-how so I wanted to get advice from someone with experience.
Any help would be enormously appreciated!
علوم کامپیوتر یا مهندسی کامپیوتر
18 Sep 25 at 9:22 am
раздвижные карнизы [url=www.razdvizhnoj-elektrokarniz.ru]www.razdvizhnoj-elektrokarniz.ru[/url] .
razdvijnoi elektrokarniz_ojei
18 Sep 25 at 9:22 am
займ всем [url=https://zaimy-15.ru/]https://zaimy-15.ru/[/url] .
zaimi_mtpn
18 Sep 25 at 9:23 am
кракен даркнет маркет 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
18 Sep 25 at 9:23 am
Submit To Article Directories – Dooes It Include Really A Good
Idea? submit; https://36526048.sharebyblog.com/36875935/enjoying-and-video-game-titles-selling-insurance-policy-policies-aid,
https://36526048.sharebyblog.com/36875935/enjoying-and-video-game-titles-selling-insurance-policy-policies-aid
18 Sep 25 at 9:24 am
Sou louco pela roda de XPBet Casino, e um cassino online que gira como um ciclo eterno. O catalogo de jogos e um espiral de prazeres. com caca-niqueis modernos que giram como ciclos. O servico e confiavel como um ciclo. oferecendo respostas claras como uma roda. Os pagamentos sao seguros e fluidos. entretanto mais giros gratis seriam vibrantes. Resumindo, XPBet Casino vale explorar esse cassino ja para os fas de adrenalina em loop! De bonus a interface e fluida e gira como um ciclo. amplificando o jogo com vibracao eterna.
xp games bet|
whirlwindneonemu5zef
18 Sep 25 at 9:25 am
prague drugstore cocaine in prague
prague-drugs-807
18 Sep 25 at 9:25 am