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!
Нужна дезинфекция квартир от клещей на участке.
дезинсекция предприятий
KennethceM
25 Oct 25 at 2:39 pm
скачать мостбет [url=https://mostbet12031.ru/]https://mostbet12031.ru/[/url]
mostbet_kg_keMa
25 Oct 25 at 2:40 pm
Где вызвать дезинфекция после животного круглосуточно? Время позднее.
обработка детского сада
KennethceM
25 Oct 25 at 2:41 pm
Good God! if you had seen the man who thus capitulated for hissafety,your surprise would have been boundless.ロボット セックス
ダッチワイフ
25 Oct 25 at 2:41 pm
It is actually a nice and useful piece of information. I
am happy that you just shared this helpful information with us.
Please stay us informed like this. Thank
you for sharing.
Extra resources
25 Oct 25 at 2:41 pm
gute wett tipps
Check out my web blog :: quote bei Wetten dass [https://corseda.Com/archivos/25901]
https://corseda.Com/archivos/25901
25 Oct 25 at 2:44 pm
ラブドール 激安No one knewhis name.Meanwhile Raskolnikov had squeezed in and stooped closer over him.
ダッチワイフ
25 Oct 25 at 2:44 pm
сегодня в 16:25 на почте получен конверт ,в нем было вещество лимоного цвета 0,3 г , сохнет ,позже подробно опишу https://promo2025magnit.ru Доберус до пк выложу скрины, магазин угрожает говорит что заплатит за подставу в общем очень взбесился когда я сказал что свои сомнения выложу в паблик, прямо как с катушек слетел, хотя я сначала сказал либо кидок аля лига 12, либо взлом.сразу мат срач угрозы ипр что никогда не сделал бы приличный шоп
LeonardHOX
25 Oct 25 at 2:45 pm
in spite of his pedantry and ungracious address.I have oftenmet with a crab-apple in a hedge,ラブドール 最新
ダッチワイフ
25 Oct 25 at 2:47 pm
Undeniably believe that which you said. Your
favourite justification seemed to be on the web the easiest factor to be aware of.
I say to you, I certainly get annoyed at the same time as folks think about concerns that they just don’t understand about.
You controlled to hit the nail upon the top and also defined out the whole thing with
no need side-effects , other folks can take a signal.
Will likely be back to get more. Thank you
Urine Treatment Service
25 Oct 25 at 2:47 pm
зайти в мостбет [url=https://www.mostbet12032.ru]https://www.mostbet12032.ru[/url]
mostbet_kg_zcmt
25 Oct 25 at 2:49 pm
kraken онлайн
кракен вход
JamesDaync
25 Oct 25 at 2:50 pm
ラブドール えろindeed! I did not know of anyreason why we shouldn,t.
ダッチワイフ
25 Oct 25 at 2:50 pm
catherinewburton.com – I’d love to see more testimonials or client stories to deepen connection.
Jean Metelko
25 Oct 25 at 2:52 pm
the wind was nearlycalm,ロボット セックスand being bound down the river,
ダッチワイフ
25 Oct 25 at 2:53 pm
уничтожение клопов цена для офиса, посоветуйте проверенных.
санобработка
KennethceM
25 Oct 25 at 2:54 pm
купить диплом инженера электрика [url=https://www.rudik-diplom4.ru]купить диплом инженера электрика[/url] .
Diplomi_bqOr
25 Oct 25 at 2:55 pm
https://mediuomo.com/# pillole per disfunzione erettile
Hermanereli
25 Oct 25 at 2:56 pm
мостбет кыргызстан [url=https://mostbet12031.ru]https://mostbet12031.ru[/url]
mostbet_kg_wyMa
25 Oct 25 at 2:56 pm
Отзывы о санэпидемстанция круглосуточно реальные? Делитесь.
обработка от клопов частного дома
KennethceM
25 Oct 25 at 2:57 pm
I’m extremely impressed together with your writing talents and also with the format
to your weblog. Is that this a paid subject or did you customize
it your self? Either way keep up the excellent high quality writing, it’s uncommon to
look a great blog like this one these days..
site link
25 Oct 25 at 2:59 pm
What i do not realize is if truth be told how you
are now not actually much more neatly-liked than you may be right now.
You are so intelligent. You know therefore considerably in the case of this topic, made me
in my opinion imagine it from a lot of numerous angles. Its like
women and men are not interested except it is something to do with
Girl gaga! Your personal stuffs great. At all times care for it up!
мартин казино зеркало
25 Oct 25 at 3:02 pm
vsmphotography.com – Great first impression: clean design and very easy to navigate.
Carlton Villalta
25 Oct 25 at 3:02 pm
kraken обмен
kraken darknet market
JamesDaync
25 Oct 25 at 3:03 pm
Simply want to say your article is as surprising.
The clarity on your post is just excellent and i can suppose
you’re knowledgeable on this subject. Fine along with your permission allow me
to grab your RSS feed to keep up to date with imminent post.
Thanks one million and please keep up the gratifying work.
Apparels Bond clothing manufacturer
25 Oct 25 at 3:05 pm
Как использовать регистрационные промо-купоны: короткие подсказки по вводу кода, пополнению счёта и требованиям по отыгрышу; в середине инструкции даём ссылку на https://bergkompressor.ru/news/artcles/?1xbet_promokod_pri_registracii_bonus_5.html, чтобы новичок мог сразу перейти к подробной инструкции. Обращаем внимание, что важно соблюдать правила ответственной игры.
PatrickDrymn
25 Oct 25 at 3:08 pm
Плесень ушла после обработка от тараканов стоимость, спасибо!
дезинсекция цена
KennethceM
25 Oct 25 at 3:09 pm
Playamo online gaming hub features a premium gaming journey with greater than 3K high-end spinning games, casino classics, and live dealer games from premier game developers. If you like rotating games on new video slots, trying blackjack strategies, or experiencing live dealer authenticity, Playamo delivers options for every player. The portal’s modern, convenient framework ensures flawless usage through both desktop and mobile devices, letting you to enjoy your top titles on your schedule.
Playamo
AlfredLog
25 Oct 25 at 3:09 pm
toddstarnesbooktour.com – It would be great to see more interactive content like video invites or live Q&A info.
Ramona Meckel
25 Oct 25 at 3:09 pm
Target is in trouble. And while it’s easy to get lost in the company’s recent (poor) handling of American culture war narratives that cast it as too “woke” or too willing to cave to online fascists, the root of Target’s problems runs deep.
[url=https://tripsca43.win]tripskan[/url]
Don’t get me wrong – the massive consumer boycotts from Black organizers have done damage. And there are probably folks on the far right who think even Target’s toned-down, overwhelmingly beige Pride merch this year was still too loud.
https://tripsca43.win
трипскан вход
But its stock is in the gutter and sales have been falling for two years because of good ol’ business fundamentals. It overstocked. It lost the pulse of its customers. It went up against Amazon Prime with… actually, does anyone know what Target’s Amazon Prime competitor is called?
The brand we petite bourgeoisie once playfully referred to as Tar-zhay has lost its spark. The company reported a decline in sales for a third-straight quarter, part of a broader trend of falling or flat sales for two years. Employees have lost confidence in the company’s direction. And 2025 has been a particularly rough financially, as Black shoppers organized a boycott over Target’s decision to cave to right-wing pressure on diverse hiring goals.
Shares were down 10% Wednesday.
It’s not to say the new guy, Michael Fiddelke, is unqualified. He’s been at Target since he started as an intern more than 20 years ago, after all. But Wall Street is clearly concerned that Target’s leadership is underestimating the severity of the need for a significant change— just as President Donald Trump’s tariffs on imported goods threaten the entire retail industry.
Appointing a company lifer “does not necessarily remedy the problems of entrenched groupthink and the inward-looking mindset that have plagued Target for years,” Neil Saunders, an analyst at GlobalData Retail, said in a note to clients Wednesday.
Missing the mark
In its 2010s heyday, Target became a go-to for consumers who liked a bargain but didn’t necessarily like bargain-hunting. The shelves felt well-curated. You’d go to Target because it had one thing you needed and 12 things you didn’t know you needed. It was stocked with Millennial cringe long before Gen Z gave us the term Millennial cringe.
Target’s sales held strong through the pandemic as remote workers set up home offices and stocked up on essentials. Months of lockdown also benefited the store as people began refreshing their spaces because they didn’t really have much else to do and they were staring at the same walls all the time.
Michaelgidge
25 Oct 25 at 3:10 pm
Срочно нужна уничтожение клопов в диване, тараканы достали!
дератизация предприятия
KennethceM
25 Oct 25 at 3:11 pm
mostbet kg [url=https://www.mostbet12031.ru]https://www.mostbet12031.ru[/url]
mostbet_kg_ziMa
25 Oct 25 at 3:13 pm
I have been surfing online more than 2 hours today, yet I never found any interesting article like yours.
It is pretty worth enough for me. In my opinion, if all webmasters and bloggers made good content as you
did, the internet will be a lot more useful than ever before.
79KING
25 Oct 25 at 3:14 pm
”This point being settled,they moved forwards to Mons,ラブドール 無 修正
ラブドール
25 Oct 25 at 3:15 pm
Клопы в мебели? дезинфекция после умерших поможет.
уничтожение клопов цена
KennethceM
25 Oct 25 at 3:17 pm
createandgrow.shop – The layout appears clean and user-friendly; nice visual clarity.
Eloy Hielscher
25 Oct 25 at 3:17 pm
кракен
kraken СПб
JamesDaync
25 Oct 25 at 3:18 pm
Спасибо за уничтожение муравьев! Всё чисто и безопасно.
уничтожение рыжих тараканов
KennethceM
25 Oct 25 at 3:18 pm
exploreopportunitiesnow.shop – The branding is consistent and gives the store a polished identity.
Christian Kudelka
25 Oct 25 at 3:19 pm
to wisebusiness.click
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
to wisebusiness.click
25 Oct 25 at 3:19 pm
Marvelous, what a webpage it is! This blog provides useful
information to us, keep it up.
jihad group website
25 Oct 25 at 3:20 pm
Every weekend i used to pay a visit this site, because
i wish for enjoyment, since this this web site conations really pleasant funny stuff too.
ev99.com
25 Oct 25 at 3:20 pm
”Serafina undertook this office with pleasure,ラブドール 無 修正because she had reason tothink his addresses would not be disagreeable to Madam Clement; andthat same night made the Count acquainted with the nature of hercommission.
ラブドール
25 Oct 25 at 3:21 pm
Автоподбор под ключ Авто под заказ в Магнитогорске – это индивидуальный подход к выбору автомобиля, максимально соответствующего вашим потребностям и предпочтениям. Мы поможем вам определиться с маркой, моделью, комплектацией и бюджетом, а также организуем поиск и проверку различных вариантов, чтобы вы могли сделать осознанный выбор.
Justinnox
25 Oct 25 at 3:22 pm
ラブドール 販売instructing,and entertaining.
ラブドール
25 Oct 25 at 3:24 pm
The scale of these recent attacks means Ukraine needs any help it can get to minimize the impacts – and volunteers are playing an increasingly important role in the defensive mix.
[url=https://kra44at.com ]kra45 сс[/url]
Civilians are forming units tasked with shooting down smaller drones with machine guns or, most recently, specially developed interceptor drones.
[url=https://kra49at.cc ]kra46 at[/url]
The chief of staff of one of Kyiv’s volunteer formation legions, Andriy, whose call-sign is Stolyar, said his unit is composed of people from all walks of life – from construction workers to businessmen to poets.
He told CNN the training for his legion lasts for about six weeks and includes basic knowledge, simulator practice and topography lessons. Andriy asked for his last name not to be published for security reasons.
“A person must understand how to operate an aircraft. Drones are becoming increasingly complex – this is aviation, and it requires constant attention, knowledge, and skills,” he said.
kra49 сс
https://kra40.at-kra40.cc
JamesPycle
25 Oct 25 at 3:25 pm
купить диплом в уссурийске [url=https://rudik-diplom10.ru]https://rudik-diplom10.ru[/url] .
Diplomi_agSa
25 Oct 25 at 3:25 pm
Oh, mathematics serves as the foundation pillar fօr primary education, assisting youngsters ᴡith dimensional reasoning in design routes.
Alas, ԝithout robust mathematics аt Junior College, еven prestigious
establishment youngsters ⅽould struggle ѡith secondary
equations, tһerefore develop tһat now leh.
Millennia Institute supplies а special three-yeaг pathway tߋ А-Levels, usіng
versatility and depth іn commerce, arts, and sciences f᧐r varied students.
Ӏts centralised method еnsures personalised support аnd holistic
development tһrough innovative programs. Ꮪtate-of-the-art centers and dedicated personnel create an intereѕting environment fоr
academic and personal development. Students tɑke advantage
of partnerships ѡith industries fοr real-wօrld experiences and scholarships.Alumni succeed іn universities аnd occupations,
highlighting tһe institute’s dedication tο lifelong learning.
Hwa Chong Institution Junior College іs commemorated foг іts smooth integrated program tһat masterfully combines strenuous scholastic difficulties ѡith profound character advancement, cultivating а brand-new generation օf global scholars
aand ethical leaders ѡho are geared սp tο deal ԝith intricate
worldwide probⅼems. The organization boasts fiгst-rate infrastructure,
including innovative гesearch study centers, bilingual libraries, and development incubators, ԝhere extremely qualified faculty guide trainees tօwards quality in fields ⅼike scientific resеarch, entrepreneurial endeavors,
ɑnd cultural studies. Trainees gain invaluable experiences tһrough substantial international exchange programs, global competitions іn mathematics and
sciences, and collective projects tһat broaden tһeir
horizons ɑnd improve tһeir analytical and social skills.
Βу highlighting development thrоugh initiatives ⅼike student-led startups ɑnd innovation workshops, alongside service-oriented activities tһat promote social duty, tһe college develops strength,
flexibility, ɑnd a strong moral structure іn itѕ learners.
The vast alumni network оf Hwa Chong Institution Junior College opens paths t᧐ elite universities and prominent careers aгound the world, highlighting the school’s
sustaining tradition of promoting intellectual expertise аnd principled management.
Listen ᥙp, steady pom pі pi, maths is amߋng of thee top
disciplines in Junior College, establishing groundwork tⲟ A-Level
advanced math.
Hey hey, Singapore folks, mathematics proves ⲣrobably tһe
highly crucial primary topic, fostering creativity f᧐r problem-solving fоr groundbreaking careers.
Parents, kiasu mode օn lah, strong primary math гesults to bеtter science understanding aѕ well as construction goals.
Math equips уoս with analytical skills that
employers in finance and tech crave.
Оһ, mathematics acts lіke the groundwork block fⲟr
primary education, aiding kids fοr dimensional analysis
in design routes.
Ⲟh dear, mіnus strong math Ԁuring Junior College, even prestigious institution kids
ϲould struggle with next-level equations, ѕo cultivate tһat immediatеly leh.
Check out my website – singapore math tuition agency
singapore math tuition agency
25 Oct 25 at 3:26 pm
Всё самое новое тут: https://institutocea.com
RandyTus
25 Oct 25 at 3:26 pm
When someone writes an article he/she retains the thought of a
user in his/her brain that how a user can understand it.
So that’s why this article is great. Thanks!
web site
25 Oct 25 at 3:28 pm