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://educ-ua20.ru/]купить диплом документы[/url] .
Diplomi_xgEn
17 Sep 25 at 1:20 pm
In today’s fast-evolving financial landscape, it’s rare to find a platform that seamlessly bridges
both crypto and fiat operations, especially for large-scale operations.
However, I came across this forum topic that dives deep into a website which supports everything from buying Bitcoin to managing fiat payments,
and it’s especially recommended for big businesses.
The recommendation shared by users in the discussion made
it clear that this platform is more than just a simple exchange – it’s a full-fledged financial ecosystem for both individuals and companies.
What’s particularly valuable is the level of detail provided in the forum
topic, including the pros and cons, user reviews, and case studies showing how enterprises have integrated the platform into their operations.
I’ve rarely come across such a balanced opinion that addresses both crypto-savvy users
and traditional finance professionals, especially in the context of
business-scale needs.
It’s a long read, but this forum topic offers some of the
most detailed opinions on using crypto platforms for corporate
and fiat operations alike. Definitely worth digging
into this website.
website
17 Sep 25 at 1:20 pm
сколько стоит купить диплом в киеве [url=educ-ua5.ru]сколько стоит купить диплом в киеве[/url] .
Diplomi_hrKl
17 Sep 25 at 1:21 pm
купить диплом института с реестром [url=www.arus-diplom33.ru/]купить диплом института с реестром[/url] .
Diplomi_ziSa
17 Sep 25 at 1:22 pm
купить диплом старого образца [url=www.educ-ua4.ru]купить диплом старого образца[/url] .
Diplomi_ykPl
17 Sep 25 at 1:23 pm
фильмы в хорошем качестве [url=http://kinogo-13.top]http://kinogo-13.top[/url] .
kinogo_gqMl
17 Sep 25 at 1:23 pm
как купить диплом с реестром [url=https://educ-ua13.ru]как купить диплом с реестром[/url] .
Diplomi_lrpn
17 Sep 25 at 1:24 pm
Hi, its nice article regarding media print, we all know media is a wonderful source of information.
Part time work from home jobs
17 Sep 25 at 1:25 pm
купить диплом с регистрацией киев [url=https://educ-ua18.ru/]https://educ-ua18.ru/[/url] .
Diplomi_nmPi
17 Sep 25 at 1:26 pm
CandyDigital — ваш полный цикл digital маркетинга: от стратегии и брендинга до трафика и аналитики. Запускаем кампании под ключ, настраиваем конверсионные воронки и повышаем LTV. Внедрим сквозную аналитику и CRM, чтобы каждый лид окупался. Узнайте больше на https://candydigital.ru/ — разберём вашу нишу, предложим гипотезы роста и быстро протестируем. Гарантируем прозрачные метрики, понятные отчеты и результат, который видно в деньгах. Оставьте заявку — старт за 7 дней.
XitagnyUtelo
17 Sep 25 at 1:27 pm
Хотите интерьер, который отражает ваш характер и привычки? Я разрабатываю удобные и выразительные интерьеры и веду проект до результата. Посмотрите портфолио и услуги на https://lipandindesign.ru – здесь реальные проекты и понятные этапы работы. Контроль сроков, смет и подрядчиков беру на себя, чтобы вы спокойно шли к дому мечты.
OscarRooms
17 Sep 25 at 1:28 pm
In today’s fast-evolving financial landscape, it’s rare to find a platform that seamlessly bridges both crypto and fiat operations, especially
for large-scale operations. However, I came across this
forum topic that dives deep into a platform which supports everything from buying Bitcoin to
managing fiat payments, and it’s especially recommended for corporate
accounts.
The opinion shared by users in the discussion made it clear that this platform is more than just
a simple exchange – it’s a full-fledged financial ecosystem for both
individuals and companies.
What’s particularly valuable is the level of detail
provided in the forum topic, including the pros and cons, user reviews, and case studies showing how enterprises
have integrated the platform into their operations.
I’ve rarely come across such a balanced discussion that addresses
both crypto-savvy users and traditional finance professionals, especially in the context
of business-scale needs.
It’s a long read, but this forum topic offers some of
the most detailed opinions on using crypto platforms for corporate and fiat operations alike.
Definitely worth digging into this website.
forum topic
17 Sep 25 at 1:30 pm
Hi, everything is going fine here and ofcourse every
one is sharing information, that’s in fact excellent, keep up writing.
web page
17 Sep 25 at 1:31 pm
купить аттестат за 11 класс 2010 года [url=http://arus-diplom25.ru]купить аттестат за 11 класс 2010 года[/url] .
Diplomi_azot
17 Sep 25 at 1:32 pm
I have read so many content on the topic of the blogger lovers except
this piece of writing is truly a pleasant post, keep it up.
my link
17 Sep 25 at 1:33 pm
Hmm is anyone else experiencing problems with the images on this blog
loading? I’m trying to find out if its a problem on my end
or if it’s the blog. Any responses would be greatly appreciated.
online casino zonder cruks
17 Sep 25 at 1:33 pm
купить диплом с реестром цена [url=http://arus-diplom33.ru]купить диплом с реестром цена[/url] .
Diplomi_ngSa
17 Sep 25 at 1:34 pm
сколько стоит купить диплом магистра [url=http://educ-ua5.ru/]сколько стоит купить диплом магистра[/url] .
Diplomi_beKl
17 Sep 25 at 1:34 pm
купить диплом с реестром [url=http://educ-ua13.ru/]купить диплом с реестром[/url] .
Diplomi_wvpn
17 Sep 25 at 1:34 pm
Купить диплом колледжа в Одесса [url=https://educ-ua7.ru/]Купить диплом колледжа в Одесса[/url] .
Diplomi_vzEr
17 Sep 25 at 1:35 pm
фильмы hd 1080 смотреть бесплатно [url=http://kinogo-14.top]http://kinogo-14.top[/url] .
kinogo_jqEl
17 Sep 25 at 1:35 pm
фильмы hd 1080 смотреть бесплатно [url=http://kinogo-15.top/]http://kinogo-15.top/[/url] .
kinogo_fisa
17 Sep 25 at 1:35 pm
займы россии [url=http://zaimy-11.ru/]http://zaimy-11.ru/[/url] .
zaimi_hgPt
17 Sep 25 at 1:35 pm
купить диплом о высшем образовании ссср [url=https://educ-ua18.ru]купить диплом о высшем образовании ссср[/url] .
Diplomi_yaPi
17 Sep 25 at 1:39 pm
купить свидетельство браке киев [url=https://www.educ-ua2.ru]https://www.educ-ua2.ru[/url] .
Diplomi_cdOt
17 Sep 25 at 1:41 pm
диплом о среднем профессиональном образовании с занесением в реестр купить [url=www.vsegda-pomnim.com/user/vadyymemelnvv/]диплом о среднем профессиональном образовании с занесением в реестр купить[/url] .
Bistro kypit diplom VYZa!_nrkt
17 Sep 25 at 1:42 pm
кино онлайн [url=https://www.kinogo-14.top]кино онлайн[/url] .
kinogo_qmEl
17 Sep 25 at 1:42 pm
все микрозаймы на карту [url=https://zaimy-11.ru/]https://zaimy-11.ru/[/url] .
zaimi_plPt
17 Sep 25 at 1:42 pm
кинопоиск смотреть онлайн [url=http://www.kinogo-15.top]кинопоиск смотреть онлайн[/url] .
kinogo_nfsa
17 Sep 25 at 1:42 pm
купить диплом в днепропетровске [url=http://www.educ-ua4.ru]купить диплом в днепропетровске[/url] .
Diplomi_xsPl
17 Sep 25 at 1:43 pm
что такое ваучер в 1win [url=https://1win12014.ru/]https://1win12014.ru/[/url]
1win_nsOl
17 Sep 25 at 1:44 pm
мостбет скачать [url=https://www.mostbet12014.ru]https://www.mostbet12014.ru[/url]
mostbet_woKl
17 Sep 25 at 1:45 pm
купить диплом о высшем образовании с реестром [url=http://educ-ua13.ru]купить диплом о высшем образовании с реестром[/url] .
Diplomi_ripn
17 Sep 25 at 1:45 pm
Заказать диплом о высшем образовании!
Мы предлагаеммаксимально быстро приобрести диплом, который выполняется на оригинальной бумаге и заверен печатями, штампами, подписями должностных лиц. Диплом пройдет лубую проверку, даже с использованием профессионального оборудования. Решите свои задачи быстро и просто с нашей компанией- [url=http://w98804oc.beget.tech/2025/08/09/kupit-diplom-bystro-ot-1-dnya.html/]w98804oc.beget.tech/2025/08/09/kupit-diplom-bystro-ot-1-dnya.html[/url]
Jariorscq
17 Sep 25 at 1:48 pm
https://linktr.ee/candetoxblend
Enfrentar un test preocupacional ya no tiene que ser un problema. Existe un suplemento de última generación que actúa rápido.
El secreto está en su mezcla, que sobrecarga el cuerpo con proteínas, provocando que la orina oculte los rastros químicos. Esto asegura un resultado confiable en solo 2 horas, con ventana segura para rendir tu test.
Lo mejor: es un plan de emergencia, diseñado para candidatos en entrevistas laborales.
Miles de clientes confirman su efectividad. Los entregas son confidenciales, lo que refuerza la seguridad.
Cuando el examen no admite errores, esta solución es la elección inteligente.
JuniorShido
17 Sep 25 at 1:48 pm
kraken сайт зеркала 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
17 Sep 25 at 1:49 pm
Ставьте осознанно и хладнокровно. Останавливайтесь на автоматах с простыми механиками и изучайте таблицу выплат до старта. В середине сессии остановитесь и оцените банкролл, а затем продолжайте игру. Ищете казино бонус на первый депозит в рублях? Подробнее смотрите на сайте super-spin5.online/ — найдете топ-провайдеров и актуальные акции. Не забывайте: игры — для удовольствия, а не путь к доходу.
Dylegdirty
17 Sep 25 at 1:51 pm
kraken darknet 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
17 Sep 25 at 1:52 pm
It’s an awesome piece of writing in favor of all the
web viewers; they will obtain advantage from it I am sure.
جدول رشته های بدون کنکور دانشگاه آزاد
17 Sep 25 at 1:52 pm
все микрозаймы онлайн [url=https://zaimy-11.ru/]https://zaimy-11.ru/[/url] .
zaimi_szPt
17 Sep 25 at 1:53 pm
фильмы hd 1080 смотреть бесплатно [url=http://kinogo-14.top/]http://kinogo-14.top/[/url] .
kinogo_fmEl
17 Sep 25 at 1:53 pm
купить диплом о высшем образовании недорого [url=https://educ-ua20.ru]купить диплом о высшем образовании недорого[/url] .
Diplomi_dhEn
17 Sep 25 at 1:53 pm
смотреть сериалы новинки [url=https://kinogo-15.top/]смотреть сериалы новинки[/url] .
kinogo_bnsa
17 Sep 25 at 1:53 pm
Мы готовы предложить документы университетов, которые расположены на территории всей Российской Федерации. Купить диплом ВУЗа:
[url=http://spaceoffreedom.net/read-blog/60_kupit-attestat-posle-9-klassa.html/]купить бланк аттестата за 11 класс[/url]
Diplomi_sqPn
17 Sep 25 at 1:55 pm
Kaizenaire.com unites Singapore’s ideal promotions, positioning іtself аs tһe
go-to site fоr deals and occasions.
Singapore stands pleased ɑѕ a shopping utopia, ᴡhere deals ignite Singaporean interest.
Capturing blockbuster films аt Cineleisure is а
timeless entertainment choice fоr Singaporeans, ɑnd rejember tߋ stay updated on Singapore’ѕ
most recent promotions and shopping deals.
Bigo ⲣrovides real-time streaming ɑnd social enjoyment apps, delighted іn by Singaporeans
fοr theiг interactive content ɑnd community engagement.
Mapletree buys realty аnd property management one,
preferred Ьy Singaporeans for their modern-ɗay growths
and investment opportunities mah.
Aalst Chocolate crafts Belgian-inspired chocolates, loved fоr
smooth, indulgent bars ɑnd regional technologies.
Ꮶeep refreshing ѕia, fоr Kaizenaire.сom’ѕ most recent lor.
my web blog singapore promos
singapore promos
17 Sep 25 at 1:56 pm
купить диплом техникума украина [url=www.educ-ua5.ru/]www.educ-ua5.ru/[/url] .
Diplomi_waKl
17 Sep 25 at 1:56 pm
официальные займы онлайн на карту бесплатно [url=www.zaimy-11.ru/]www.zaimy-11.ru/[/url] .
zaimi_yvPt
17 Sep 25 at 1:57 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best at
bs2best.at blacksprut marketplace Official
CharlesNarry
17 Sep 25 at 1:57 pm
сериалы тнт онлайн [url=www.kinogo-14.top/]www.kinogo-14.top/[/url] .
kinogo_mvEl
17 Sep 25 at 1:57 pm
аниме смотреть онлайн [url=https://kinogo-15.top]аниме смотреть онлайн[/url] .
kinogo_arsa
17 Sep 25 at 1:57 pm