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.medicinskoe–oborudovanie.ru]медицинская аппаратура[/url] .
medicinskoe oborydovanie_thei
27 Oct 25 at 11:15 am
купить vip диплом техникума ссср [url=www.frei-diplom10.ru]купить vip диплом техникума ссср[/url] .
Diplomi_bpEa
27 Oct 25 at 11:18 am
kraken vk5
kraken зеркало
Henryamerb
27 Oct 25 at 11:19 am
наркологическая помощь [url=https://www.narkologicheskaya-klinika-24.ru]наркологическая помощь[/url] .
narkologicheskaya klinika_etSr
27 Oct 25 at 11:19 am
What’s up, yeah this piece of writing is really
nice and I have learned lot of things from it on the topic of blogging.
thanks.
طراحی سایت نوبت دهی سالن زیبایی
27 Oct 25 at 11:19 am
Hey! I’m at work browsing your blog from my new apple iphone!
Just wanted to say I love reading your blog and look forward to all your posts!
Keep up the superb work!
Here is my web site :: zinnat02
zinnat02
27 Oct 25 at 11:19 am
Как купить Лсд в Кургане?Как думаете, нормально ли заказывать у https://lordfilmsh24.ru
? Цены хорошие, доставку обещают. Но переживаю насчет качества.
Stevenref
27 Oct 25 at 11:21 am
купить диплом переводчика [url=https://rudik-diplom12.ru]купить диплом переводчика[/url] .
Diplomi_vpPi
27 Oct 25 at 11:24 am
не в курсе купить онлайн мефедрон, экстази, бошки В скайпе ответил что вопрос решаеться,будем надеяться на лучшее,а насчёт красной темы-даже думать не хочеться.Всем мир!!!
RichardDring
27 Oct 25 at 11:25 am
кракен vk3
кракен обмен
Henryamerb
27 Oct 25 at 11:27 am
I’m gone to tell my little brother, that he should also go to see this web site on regular basis to get updated from latest news update.
https://confortvgb.com.ar/obzor-bukmekerskoy-kontory-melbet-2025/
LewisGuatt
27 Oct 25 at 11:27 am
kraken vk3
кракен зеркало
Henryamerb
27 Oct 25 at 11:28 am
аппараты медицинские [url=https://medicinskoe–oborudovanie.ru/]https://medicinskoe–oborudovanie.ru/[/url] .
medicinskoe oborydovanie_uzei
27 Oct 25 at 11:28 am
В обзорной статье вы найдете собрание важных фактов и аналитики по самым разнообразным темам. Мы рассматриваем как современные исследования, так и исторические контексты, чтобы вы могли получить полное представление о предмете. Погрузитесь в мир знаний и сделайте шаг к пониманию!
А что дальше? – https://rtowndiner.com/product/bacon-cheese-fries
Michaelzex
27 Oct 25 at 11:29 am
где купить диплом [url=http://www.rudik-diplom12.ru]где купить диплом[/url] .
Diplomi_lhPi
27 Oct 25 at 11:31 am
наркологическая клиника [url=https://www.narkologicheskaya-klinika-24.ru]наркологическая клиника[/url] .
narkologicheskaya klinika_wkSr
27 Oct 25 at 11:33 am
kraken ссылка
kraken СПб
Henryamerb
27 Oct 25 at 11:33 am
где купить диплом железнодорожного техникума [url=https://frei-diplom10.ru]где купить диплом железнодорожного техникума[/url] .
Diplomi_auEa
27 Oct 25 at 11:38 am
платный наркологический диспансер москва [url=www.narkologicheskaya-klinika-28.ru]www.narkologicheskaya-klinika-28.ru[/url] .
narkologicheskaya klinika_kpMa
27 Oct 25 at 11:38 am
E28BET میں خوش آمدید – ایشیا پیسیفک کی نمبر 1 آن لائن
جوئے کی سائٹ۔ بونس، دلچسپ گیمز، اور قابل
اعتماد آن لائن بیٹنگ کے تجربے کا لطف اٹھائیں۔
E28BET - ایشیا پیسیفک کی نمبر 1 آن لائن جوئے کی سائٹ
27 Oct 25 at 11:38 am
кракен даркнет
kraken зеркало
Henryamerb
27 Oct 25 at 11:39 am
https://www.sibc.nd.edu/post/godsee-joy?commentId=9c230f5c-3887-4303-a88c-7693a26a8a4a
MichaelWoode
27 Oct 25 at 11:39 am
купить диплом автомобильного техникума [url=http://frei-diplom7.ru/]купить диплом автомобильного техникума[/url] .
Diplomi_vjei
27 Oct 25 at 11:40 am
worldcityexpo.com – Color palette felt calming, nothing distracting, just focused, thoughtful design.
Fidela Macmaster
27 Oct 25 at 11:42 am
linked internet page
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
linked internet page
27 Oct 25 at 11:42 am
медицинское оборудование для больниц [url=https://medicinskoe–oborudovanie.ru/]medicinskoe–oborudovanie.ru[/url] .
medicinskoe oborydovanie_qzei
27 Oct 25 at 11:43 am
психолог нарколог в москве [url=http://www.narkologicheskaya-klinika-24.ru]http://www.narkologicheskaya-klinika-24.ru[/url] .
narkologicheskaya klinika_fsSr
27 Oct 25 at 11:44 am
more tips here
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
more tips here
27 Oct 25 at 11:45 am
This post gives clear idea in support of the new visitors of
blogging, that in fact how to do running a blog.
best cat bubble backpack 2025
27 Oct 25 at 11:45 am
kraken tor
kraken vk6
Henryamerb
27 Oct 25 at 11:48 am
Pretty nice post. I simply stumbled upon your
blog and wished to mention that I’ve really enjoyed browsing your weblog
posts. In any case I will be subscribing for your rss feed and I am hoping you write again soon!
Thuốc kích dục
27 Oct 25 at 11:48 am
kraken сайт
кракен зеркало
Henryamerb
27 Oct 25 at 11:48 am
Juggling the demands of the fiat and crypto ecosystems has always been a major pain point for many in the GSA community.
The constant friction and opaque processes between fiat and crypto platforms can severely slow down vital transactions.
This is precisely why the Paybis fintech platform is worth a closer
look. They aren’t just another crypto exchange;
they’ve built a remarkably fluid gateway that masterfully consolidates both fiat
and cryptocurrency banking. Imagine managing treasury across
USD, EUR, and a vast selection of major digital assets—all
from a single, secure dashboard. Their focus on robust security measures means you
can transact with confidence. A brief comment can’t possibly do justice
to the full scope of their offerings, especially their advanced tools
for high-volume traders. To get a complete picture of how Paybis is solving
the fiat-crypto problem, you absolutely need to read the detailed analysis in the
full article. It breaks down their KYC process, supported regions, and API integration in a
way that is incredibly insightful. I highly recommend check out the piece to see if their platform aligns with your operational requirements.
It’s a comprehensive overview for anyone in our field looking to stay ahead
of the curve. The link is in the main post—it’s well worth your time.
website
27 Oct 25 at 11:49 am
right here on befine.click
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
right here on befine.click
27 Oct 25 at 11:51 am
педагогический колледж купить диплом [url=http://frei-diplom7.ru/]педагогический колледж купить диплом[/url] .
Diplomi_jiei
27 Oct 25 at 11:51 am
Купить диплом любого ВУЗа можем помочь. Купить диплом бакалавра в Сургуте – [url=http://diplomybox.com/kupit-diplom-bakalavra-v-surgute/]diplomybox.com/kupit-diplom-bakalavra-v-surgute[/url]
Cazruuy
27 Oct 25 at 11:52 am
аппараты медицинские [url=https://medicinskoe–oborudovanie.ru]https://medicinskoe–oborudovanie.ru[/url] .
medicinskoe oborydovanie_urei
27 Oct 25 at 11:53 am
I’m really enjoying the design and layout of your website.
It’s a very easy on the eyes which makes it much more
pleasant for me to come here and visit more often. Did you hire out a developer to create your theme?
Exceptional work!
VixgenAi Erfahrungen
27 Oct 25 at 11:53 am
kraken
кракен Москва
Henryamerb
27 Oct 25 at 11:53 am
Great post! We are linking to this great article on our website.
Keep up the good writing.
Elevato Monvex Recensione
27 Oct 25 at 11:54 am
Excellent beat ! I would like to apprentice even as you amend your website,
how could i subscribe for a weblog site? The account aided me a appropriate deal.
I had been a little bit acquainted of this your broadcast provided vivid clear idea
먹튀
27 Oct 25 at 11:55 am
частная клиника наркологическая [url=www.narkologicheskaya-klinika-24.ru]www.narkologicheskaya-klinika-24.ru[/url] .
narkologicheskaya klinika_gaSr
27 Oct 25 at 11:56 am
https://t.me/s/jw_1xbet/13
Georgerah
27 Oct 25 at 11:56 am
[url=https://promodj.com/zenitbet/tracks/7801688/Melbet_zerkalo_rabochiy_dostup_k_saytu_Melbet_na_segodnya]melbet зеркало рабочее[/url] — мой go-to, когда основной домен «в тени». Работает стабильно, без перебоев, и главное — безопасно. Никаких фишингов, никаких «введите пароль повторно». Всё шифруется, всё под защитой. Ставлю в лайве, кэшаутю, вывожу — всё как по маслу. Для тех, кто ценит время и нервы — идеальный вариант.
скачать приложение melbet
27 Oct 25 at 11:56 am
By celebrating small triumphes underway tracking, OMT nurtures а favorable connection ԝith
mathematics, inspiring trainees fоr exam
quality.
Founded in 2013 by Mr. Justin Tan, OMT Math Tuition hаѕ assisted countless students ace tests ⅼike PSLE, O-Levels, and
A-Levels ԝith tested analytical methods.
Ꭲhe holistic Singapore Math technique, ᴡhich constructs multilayered analytical capabilities,
highlights ѡhy math tuition іs essential
for mastering thе curriculum ɑnd getting ready fоr future professions.
Ϝor PSLE success, tuition ρrovides tailored assistance tⲟ weak aгeas,
liҝе ratio and portion issues, preventing common risks tһroughout
the test.
Tuition promotes innovative analytic skills, vital fоr resolving tһe facility, multi-step concerns tһat define O Level
math difficulties.
Junior college math tuition іs essential for A Levels ɑs
it gгows understanding օf advanced calculus subjects ⅼike
assimilation techniques ɑnd differential formulas,
ԝhich aгe main to the examination curriculum.
OMT attracts attention ѡith its syllabus ⅽreated to sustain MOE’s by including mindfulness techniques t᧐ lower mathematics stress ɑnd anxiety durіng researches.
Unlimited retries on tests sіa, perfect for mastering subjects ɑnd
achieving those А grades in math.
Ꮤith mathematics scores affeсting secondary school positionings,
tuition іs essential for Singapore primary trainees ցoing for elite establishments tһrough PSLE.
My site: coronation plaza math tuition
coronation plaza math tuition
27 Oct 25 at 11:57 am
https://t.me/s/jw_1xbet/594
Georgerah
27 Oct 25 at 11:59 am
I got this website from my pal who shared with me about this website and
at the moment this time I am browsing this site
and reading very informative content at this place.
Cashinvenix
27 Oct 25 at 11:59 am
лечение зависимостей [url=https://www.narkologicheskaya-klinika-25.ru]лечение зависимостей[/url] .
narkologicheskaya klinika_vxPl
27 Oct 25 at 12:00 pm
kraken обмен
кракен зеркало
Henryamerb
27 Oct 25 at 12:00 pm
An outstanding share! I’ve just forwarded this onto a friend who has been doing a little homework on this.
And he in fact ordered me dinner simply because I found it for him…
lol. So allow me to reword this…. Thanks for
the meal!! But yeah, thanks for spending the time to talk about this matter here on your website.
39bet
27 Oct 25 at 12:01 pm