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!
Kamagra online kaufen: Kamagra Oral Jelly Deutschland – Kamagra online kaufen
ThomasCep
30 Oct 25 at 2:51 am
Erfahrungen mit Kamagra 100mg: Potenzmittel ohne ärztliches Rezept – Kamagra Wirkung und Nebenwirkungen
ThomasCep
30 Oct 25 at 2:52 am
Whoa! This blog looks just like my old one! It’s on a completely different topic but it
has pretty much the same layout and design. Excellent choice of
colors!
BO
30 Oct 25 at 2:53 am
this site
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
this site
30 Oct 25 at 2:53 am
https://t.me/s/Best_promocode_rus/2556
RouletteRogue
30 Oct 25 at 2:53 am
курсы по seo [url=http://kursy-seo-11.ru/]курсы по seo[/url] .
kyrsi seo_ptEl
30 Oct 25 at 2:55 am
Способ создание сайта с ценами довольно много, начиная от бесплатной регистрации в каталогах и заканчивая покупками многих тысяч ссылок на специализированных биржах.
Ну а теперь давайте рассмотрим все способы в отдельности.
Самое нетяжелое это «регистрация в каталогах«.
На сегодняшний день существует большое количество каталогов от 5000 до 15000 тыс.
создания сайта екатеринбург
30 Oct 25 at 2:56 am
The Betnaija promotion code this November
2025 is YOHAIG.
Breaking Down the Statistical Edge of BetNaija’s November Promotion
When approaching the betting landscape for November 2025, strategic wagerers should pay close attention to the current bet9ja promotion code YOHAIG
and its potential ROI.
Based on comprehensive analysis, the YOHAIG code provides a measurable advantage for both first-time players and strategic players looking for positive expected value.
Measuring the Sign-up Value
Upon entering YOHAIG during registration, new players receive a sign-up offer of
up to ₦100,000 with a minimal minimum deposit of ₦100.
From a statistical standpoint, this bet9ja welcome bonus translates to a measurable wagering power
enhancement of potentially 100% of your initial investment.
For maximizing the bonus utilization, analyze these critical metrics:
Wager with odds of at least 3.00
Verify your wagers satisfy the minimum ₦100 threshold
Complete the wagering conditions in the specified timeframe
Free Prediction Game: Mathematical Expectation
Beyond the sign-up offer, the free prediction game presents a compelling expected return.
Weekly, this no-cost competition allows you to predict correct scores
for curated fixtures, with the opportunity to claim up to ₦1 billion in the payout
structure.
In terms of expected value, even with a realistic hit percentage of 0.0001%, the
expected value remains advantageous given the free participation.
Real-time Market Approach
BetNaija delivers robust in-play wagering functionalities that provide
edge to informed bettors.
When leveraging the betting application for real-time betting, evaluate these high-value strategies:
Prioritize betting opportunities with pricing discrepancies
Apply performance indicators beyond conventional numbers
Utilize a capital allocation approach calibrated to probabilistic edge
Soccer Value Hunting
November 2025 showcases marquee major football games with
particularly favorable betting conditions.
When analyzing these sporting events, the registration code unlocks
specialized betting markets.
Based on historical data, this month historically shows a measurable enhancement in market inefficiencies across specialized prop
markets.
Transaction Options: Efficiency Analysis
An efficient approach to deposit and withdrawal involves utilizing the most efficient banking option.
The platform offers numerous payment solutions with distinct completion durations:
Card transactions: typically same day
Digital wallets: Instant to 15 minutes
Telephone banking: Instant completion
Based on data, electronic transfers offer the highest efficiency-to-fee ratio for active players.
Bonus Requirements: Strategic Interpretation
Like all betting promotion, the terms and
conditions demand thorough evaluation.
Essential components to consider include:
Playthrough conditions: Multiple bet requirement
the bonus amount
Betting minimum: 3.00 for qualifying bets
Completion window: 14 days to complete all conditions
Mathematically speaking, these requirements indicate a 37.8% promotion worth for disciplined bettors.
Conclusion
The registration code YOHAIG for this period represents a mathematically sound offering for market participants.
Through implementing disciplined wagering methodologies, this promotional opportunity can contribute to positive expected value across your betting portfolio.
Remember that sustainable betting success needs patience and mathematical approach rather than emotional decisions.
Employ the bet9ja promotion code as one element in a comprehensive edge-finding methodology for the coming month and beyond.
bet9ja promotion code
30 Oct 25 at 2:56 am
курс seo [url=https://kursy-seo-11.ru/]kursy-seo-11.ru[/url] .
kyrsi seo_szEl
30 Oct 25 at 2:59 am
В Ростове-на-Дону мы гарантируем полную анонимность и конфиденциальность на всех этапах лечения, без постановки на учёт. Клиника в Ростове-на-Дону работает круглосуточно, обеспечивая доступность помощи в любое время дня и ночи.
Узнать больше – [url=https://vyvod-iz-zapoya-rostov111.ru/]вывод из запоя вызов на дом ростов-на-дону[/url]
Anthonysic
30 Oct 25 at 3:03 am
купить диплом колледжа в нижнем тагиле [url=frei-diplom12.ru]frei-diplom12.ru[/url] .
Diplomi_rxPt
30 Oct 25 at 3:03 am
В жизни крупных городов часто возникают ситуации, когда стрессы и быстрый ритм жизни приводят к развитию зависимости. Когда проблема становится очевидной, важно незамедлительно обратиться за помощью. В таких случаях вызов нарколога на дом может стать не только удобным, но и наиболее эффективным вариантом. Это позволяет получить квалифицированное лечение в привычной обстановке, сохраняя при этом полную анонимность и конфиденциальность.
Ознакомиться с деталями – [url=https://narcolog-na-dom-moskva55.ru/]вызов нарколога на дом[/url]
Stephenwably
30 Oct 25 at 3:04 am
обучение продвижению сайтов [url=www.kursy-seo-11.ru]обучение продвижению сайтов[/url] .
kyrsi seo_ljEl
30 Oct 25 at 3:04 am
Kamagra pas cher France: VitaHomme – acheter Kamagra en ligne
RobertJuike
30 Oct 25 at 3:05 am
seo онлайн [url=http://www.kursy-seo-11.ru]seo онлайн[/url] .
kyrsi seo_edEl
30 Oct 25 at 3:08 am
You actually make it seem so easy with your presentation but I find this topic to
be actually something that I think I would never understand.
It seems too complex and very broad for me. I’m looking forward for your next post, I’ll try
to get the hang of it!
buy a small business
30 Oct 25 at 3:08 am
купить диплом в химках [url=https://rudik-diplom6.ru]купить диплом в химках[/url] .
Diplomi_asKr
30 Oct 25 at 3:09 am
курсы seo [url=www.kursy-seo-11.ru]курсы seo[/url] .
kyrsi seo_csEl
30 Oct 25 at 3:09 am
chrishallforjudge.com – Overall a polished site, I’ll keep following updates and posts here.
Bev Flewelling
30 Oct 25 at 3:09 am
Excellent blog here! Also your web site loads up very fast!
What web host are you using? Can I get your affiliate link to
your host? I wish my website loaded up as fast as yours
lol
my webpage A片
A片
30 Oct 25 at 3:13 am
czarni w Polsce
Williamgon
30 Oct 25 at 3:13 am
Kamagra 100mg bestellen: Kamagra 100mg bestellen – vitalpharma24
ThomasCep
30 Oct 25 at 3:14 am
Everyone loves it whenever people come together and share
opinions. Great website, continue the good work!
memek cobel
30 Oct 25 at 3:14 am
leki Polska
Williamgon
30 Oct 25 at 3:14 am
гей порно
Jeromeeleri
30 Oct 25 at 3:14 am
Hi my friend! I wish to say that this post is awesome,
nice written and include almost all vital infos. I’d like to see extra posts
like this .
Balance Qyral
30 Oct 25 at 3:16 am
seo с нуля [url=http://kursy-seo-11.ru]http://kursy-seo-11.ru[/url] .
kyrsi seo_hiEl
30 Oct 25 at 3:16 am
обучение продвижению сайтов [url=https://www.kursy-seo-12.ru]обучение продвижению сайтов[/url] .
kyrsi seo_gpor
30 Oct 25 at 3:17 am
где купить диплом техникума всеми [url=https://www.frei-diplom12.ru]где купить диплом техникума всеми[/url] .
Diplomi_mxPt
30 Oct 25 at 3:18 am
Why viewers still make use of to read news papers when in this technological world all
is available on net?
Fenice Bitvexa
30 Oct 25 at 3:19 am
https://mannvital.shop/# Viagra reseptfritt Norge
Davidjealp
30 Oct 25 at 3:21 am
orourkeforphilly.com – I like the candidate’s messaging about community issues, feels rooted and relevant.
Glen Denny
30 Oct 25 at 3:22 am
купить диплом в балаково [url=http://rudik-diplom6.ru]купить диплом в балаково[/url] .
Diplomi_zqKr
30 Oct 25 at 3:22 am
обучение seo [url=kursy-seo-11.ru]обучение seo[/url] .
kyrsi seo_thEl
30 Oct 25 at 3:23 am
купить диплом техникума ссср в астрахани [url=http://frei-diplom12.ru/]купить диплом техникума ссср в астрахани[/url] .
Diplomi_fePt
30 Oct 25 at 3:25 am
диплом о высшем образовании с занесением в реестр купить [url=frei-diplom3.ru]диплом о высшем образовании с занесением в реестр купить[/url] .
Diplomi_mqKt
30 Oct 25 at 3:25 am
Kamagra Wirkung und Nebenwirkungen: Kamagra Wirkung und Nebenwirkungen – diskrete Lieferung per DHL
RichardImmon
30 Oct 25 at 3:25 am
школа seo [url=https://kursy-seo-11.ru/]kursy-seo-11.ru[/url] .
kyrsi seo_mhEl
30 Oct 25 at 3:26 am
Заказать диплом о высшем образовании поможем. Купить диплом магистра в Твери – [url=http://diplomybox.com/kupit-diplom-magistra-v-tveri/]diplomybox.com/kupit-diplom-magistra-v-tveri[/url]
Cazrqpk
30 Oct 25 at 3:28 am
nataliakerbabian.com – Overall a thoughtful site that highlights preservation in a modern, artistic way.
Lang Heidebrink
30 Oct 25 at 3:28 am
It’s amazing designed for me to have a website, which is
valuable designed for my know-how. thanks admin
Feel free to visit my web blog – zinnat02
zinnat02
30 Oct 25 at 3:29 am
smyrnafestival.com – Social media updates are frequent, which helps stay informed and excited.
Oliver Mariello
30 Oct 25 at 3:30 am
Does your website have a contact page? I’m having a tough time locating it but,
I’d like to shoot you an email. I’ve got some suggestions for your
blog you might be interested in hearing. Either way, great blog and
I look forward to seeing it develop over time.
no deposit bonus casino
30 Oct 25 at 3:30 am
Регистрация в 2026 году — подробно о бонусам и предложениям. Посмотрите, как правильно активировать приветственные предложения, и в середине процесса обратите внимание на https://sushikim.ru/image/pgs/1xbet-besplatnuy-promokod-pri-registracii.html как вариант получения дополнительного вознаграждения. Часто задаваемые вопросы помогут быстро разобраться с верификацией и получением бонусов.
LouisIgnig
30 Oct 25 at 3:31 am
seo интенсив [url=www.kursy-seo-11.ru]www.kursy-seo-11.ru[/url] .
kyrsi seo_zkEl
30 Oct 25 at 3:31 am
Hello there I am so grateful I found your webpage, I
really found you by mistake, while I was browsing on Yahoo for something else, Regardless I am
here now and would just like to say cheers for a marvelous post
and a all round interesting blog (I also love the theme/design), I don’t have
time to go through it all at the moment but I have saved it and also added in your RSS feeds, so when I have time I will be back to read a lot more, Please do keep
up the great work.
Laser Treatments services
30 Oct 25 at 3:33 am
купить диплом техникума и поступить в вуз [url=https://frei-diplom12.ru/]купить диплом техникума и поступить в вуз[/url] .
Diplomi_gaPt
30 Oct 25 at 3:34 am
Очень удобный обзор нейросетей для изображений с подробными характеристиками каждого инструмента. Выбрал пару вариантов под свои задачи, результат превзошёл ожидания. Рекомендую всем: сервисы для генерации картинок
MichaelPrion
30 Oct 25 at 3:34 am
Erfahrungen mit Kamagra 100mg: diskrete Lieferung per DHL – Kamagra online kaufen
RichardImmon
30 Oct 25 at 3:34 am
Nice post. I learn something totally new and challenging on blogs I
stumbleupon every day. It’s always interesting to read content from other
writers and use a little something from other sites.
Immediate App Ai
30 Oct 25 at 3:36 am