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!
What’s up all, here every one is sharing such knowledge, so it’s nice to read this webpage, and I used to go to see
this weblog every day.
Köpa Viagra receptfritt
28 Oct 25 at 1:16 am
наркология клиника [url=narkologicheskaya-klinika-28.ru]наркология клиника[/url] .
narkologicheskaya klinika_dqMa
28 Oct 25 at 1:16 am
купить диплом техникума союзной республики [url=frei-diplom8.ru]купить диплом техникума союзной республики[/url] .
Diplomi_rrsr
28 Oct 25 at 1:16 am
гидроизоляция подвала снаружи цена [url=gidroizolyaciya-podvala-cena.ru]gidroizolyaciya-podvala-cena.ru[/url] .
gidroizolyaciya podvala cena_igKt
28 Oct 25 at 1:16 am
купить диплом матроса [url=https://rudik-diplom1.ru/]купить диплом матроса[/url] .
Diplomi_srer
28 Oct 25 at 1:18 am
Oh, maths serves as the foundation stone fоr primary education,
assisting children іn spatial thinking in building routes.
Aiyo, ѡithout solid math in Junior College,
гegardless prestigious school youngsters сould struggle
with neҳt-level equations, ѕo cultivate thіs promptly
leh.
St. Andrew’s Junior College promotes Anglican worths ɑnd holistic development, constructing principled individuals ѡith strong character.
Modern features support quality іn academics, sports, ɑnd arts.
Neighborhood service ɑnd management programs instill compassion ɑnd responsibility.
Diverse ϲo-curricular activities promote teamwork ɑnd
self-discovery. Alumni emerge as ethical leaders, contributing meaningfully tօ society.
Tampines Meridian Junior College, born from tһe lively merger of
Tampines Junior College аnd Meridian Junior
College, delivers ɑn ingenious and culturally
abundant education highlighted Ƅy specialized electives іn drama аnd Malay language, supporting meaningful and multilingual skills in a forward-thinking community.
Ƭhe college’s cutting-edge facilities, incorporating theater
spaces, commerce simulation labs, аnd science development
centers, assistance diverse academic streams tһɑt
encourage interdisciplinary exploration аnd practical skill-building aⅽross arts, sciences, аnd
company. Skill development programs, combined ԝith abroad immersion trips and cultural festivals, foster
strong leadership qualities, cultural awareness, ɑnd versatility to international dynamics.
Ꮤithin a caring and understanding school culture, trainees tаke part in wellness
efforts, peer support ѕystem, аnd co-curricular clubs thаt promoe strength, emotional intelligence, ɑnd
collaborative spirit. Ꭺs a result, Tampines Meridian Junior College’ѕ students attain holistic development
аnd are wеll-prepared to deal ᴡith global
difficulties, Ьecoming positive, flexible individuals ɑll
set for university success аnd bеyond.
Wah, maths serves аs the foundation block of primary education, helping children ᴡith spatial
analysis in architecture careers.
Listen սⲣ, Singapore folks, maths proves ρerhaps tһе most crucial primary discipline, promoting innovation іn pr᧐blem-solving
іn creative professions.
Mums аnd Dads, fearful of losing approach on lah, robust primary math leads tο better
science comprehension plᥙs tech aspirations.
Wah, math іѕ the base block for primary schooling, aiding youngsters fօr dimensional reasoning іn building routes.
Math аt A-levels fosters ɑ growth mindset, crucial fߋr lifelong learning.
Wah lao, гegardless ԝhether establishment
іs fancy, maths iѕ the critical subjecct tօ building assurance in figures.
Alas, primary maths educates practical applications including budgeting, tһerefore guarantee үߋur kid gеts it right begining eɑrly.
Take а look ɑt my blog post: outram secondary school
outram secondary school
28 Oct 25 at 1:19 am
Нарколог на дом в Челябинске — это услуга, которая позволяет получить профессиональную медицинскую помощь при алкогольной или наркотической интоксикации без необходимости посещения клиники. Такой формат особенно востребован в случаях, когда пациент не может самостоятельно прибыть в медицинское учреждение или нуждается в конфиденциальной помощи. Врач-нарколог выезжает по указанному адресу, проводит осмотр, оценивает состояние и подбирает оптимальную терапию. Квалифицированное вмешательство помогает избежать осложнений и стабилизировать состояние уже в течение первых часов после прибытия специалиста.
Получить дополнительные сведения – [url=https://narkolog-na-dom-v-chelyabinske16.ru/]вызов нарколога на дом челябинск[/url]
JosephMep
28 Oct 25 at 1:20 am
I blog frequently and I genuinely appreciate your content.
This article has really peaked my interest. I’m going to bookmark your blog and keep checking for new details about once per week.
I subscribed to your RSS feed as well.
Feel free to visit my page; zinnat02
zinnat02
28 Oct 25 at 1:21 am
обмазочная гидроизоляция цена работы за м2 [url=https://gidroizolyaciya-cena-8.ru]https://gidroizolyaciya-cena-8.ru[/url] .
gidroizolyaciya cena_hqKn
28 Oct 25 at 1:21 am
kraken marketplace
кракен онлайн
Henryamerb
28 Oct 25 at 1:22 am
Ich bin absolut begeistert von Cat Spins Casino, es bietet ein immersives Erlebnis. Die Spiele sind abwechslungsreich und fesselnd, mit Krypto-freundlichen Titeln. Er sorgt fur einen starken Einstieg. Der Kundensupport ist erstklassig. Die Zahlungen sind sicher und zuverlassig, trotzdem haufigere Promos wurden begeistern. Letztlich, Cat Spins Casino ist eine Plattform, die uberzeugt. Nebenbei ist das Design zeitgema? und attraktiv, jeden Augenblick spannender macht. Ein gro?artiges Plus ist das VIP-Programm mit besonderen Vorteilen, individuelle Vorteile liefern.
Tauchen Sie ein|
Nightbearar3zef
28 Oct 25 at 1:22 am
Мы придерживаемся инженерной логики: цель > маркер > окно проверки > отключение модуля. Никаких «сильных коктейлей на всякий случай»: сначала один точный шаг, затем — проверка результата. Именно так формируется прозрачность и доверие: пациент видит причину каждого назначения и понимает момент его завершения. Это уменьшает тревогу, ускоряет восстановление и убирает «инерцию лечения», когда лишние вмешательства продолжаются просто по привычке.
Получить больше информации – [url=https://narkolog-na-dom-v-samare16.ru/]www.domen.ru[/url]
Anthonycashy
28 Oct 25 at 1:22 am
Удобные и стильные [url=https://avtomaticheskie-karnizy-s-pultom.ru/]автоматический карниз для штор Prokarniz[/url] делают управление шторами простым и комфортным.
Эти устройства позволяют управлять шторами с помощью пульта, смартфона или даже голосовых команд.
автоматические карнизы для штор Prokarniz
28 Oct 25 at 1:22 am
kraken client
kraken darknet market
Henryamerb
28 Oct 25 at 1:22 am
sheacentral.com – Bookmarked this immediately, planning to revisit for updates and inspiration.
Louetta Respicio
28 Oct 25 at 1:23 am
гидроизоляция цена работы за м2 [url=http://gidroizolyaciya-cena-8.ru]http://gidroizolyaciya-cena-8.ru[/url] .
gidroizolyaciya cena_ppKn
28 Oct 25 at 1:25 am
J’ai une affection particuliere pour Sugar Casino, on ressent une ambiance festive. Le catalogue de titres est vaste, avec des slots aux designs captivants. Il donne un avantage immediat. Les agents repondent avec efficacite. Les retraits sont fluides et rapides, de temps en temps quelques tours gratuits en plus seraient geniaux. En resume, Sugar Casino merite un detour palpitant. A souligner le site est rapide et style, apporte une touche d’excitation. Egalement super les transactions en crypto fiables, renforce le lien communautaire.
Voir la page|
Lunarfireok3zef
28 Oct 25 at 1:25 am
Thanks for the marvelous posting! I really enjoyed reading it, you might be a great author.
I will remember to bookmark your blog and will
often come back later in life. I want to encourage you continue your great writing, have
a nice weekend!
assignment writers near me
28 Oct 25 at 1:27 am
кракен даркнет маркет
kraken vk6
Henryamerb
28 Oct 25 at 1:27 am
Эти признаки не заменяют очной оценки, но помогают не рисковать временем. Если вы наблюдаете их у близкого или у себя, не откладывайте обращение — чем раньше начнётся управляемое вмешательство, тем меньше вероятность осложнений в первую ночь и на следующие сутки.
Исследовать вопрос подробнее – https://vyvod-iz-zapoya-v-chelyabinske16.ru/vyvod-iz-zapoya-chelyabinsk-anonimno
MichaelPix
28 Oct 25 at 1:29 am
купить диплом в череповце [url=https://rudik-diplom9.ru/]https://rudik-diplom9.ru/[/url] .
Diplomi_jmei
28 Oct 25 at 1:29 am
Howdy! I know this is somewhat off topic but I was wondering which blog platform are
you using for this site? I’m getting tired of WordPress
because I’ve had problems with hackers and I’m looking at alternatives for another platform.
I would be awesome if you could point me in the direction of a good platform.
pet dental care
28 Oct 25 at 1:30 am
https://t.me/s/bs_1Win/603
Georgerah
28 Oct 25 at 1:30 am
номер телефона виртуальный купить
MiguelActic
28 Oct 25 at 1:31 am
наркологическая клиника трезвый выбор [url=http://narkologicheskaya-klinika-28.ru]http://narkologicheskaya-klinika-28.ru[/url] .
narkologicheskaya klinika_lbMa
28 Oct 25 at 1:31 am
номер для смс
MiguelActic
28 Oct 25 at 1:32 am
https://t.me/bs_1Win/714
Georgerah
28 Oct 25 at 1:33 am
kraken онлайн
кракен даркнет маркет
Henryamerb
28 Oct 25 at 1:33 am
гидроизоляция подвала цена за м2 [url=www.gidroizolyaciya-cena-8.ru/]гидроизоляция подвала цена за м2[/url] .
gidroizolyaciya cena_cmKn
28 Oct 25 at 1:36 am
наркологическое отделение наркологии [url=https://narkologicheskaya-klinika-28.ru/]https://narkologicheskaya-klinika-28.ru/[/url] .
narkologicheskaya klinika_rvMa
28 Oct 25 at 1:37 am
Je suis accro a Ruby Slots Casino, ca invite a plonger dans le fun. Les titres proposes sont d’une richesse folle, comprenant des jeux crypto-friendly. Il propulse votre jeu des le debut. Le suivi est d’une precision remarquable. Les transactions sont d’une fiabilite absolue, a l’occasion des bonus plus frequents seraient un hit. En fin de compte, Ruby Slots Casino est une plateforme qui pulse. Ajoutons que le site est fluide et attractif, ce qui rend chaque session plus palpitante. Particulierement attrayant les tournois reguliers pour s’amuser, propose des privileges sur mesure.
Savoir plus|
toxickingen6zef
28 Oct 25 at 1:39 am
Чтобы сделать процесс понятным и управляемым, каждый шаг сопровождается измеримыми маркерами безопасности и эффективности. Корректировки — точечные, по правилу «одного изменения», что позволяет видеть вклад каждого действия и сохранять переносимость.
Подробнее тут – [url=https://narkologicheskaya-pomoshh-v-kazani16.ru/]вызов наркологической помощи казань[/url]
PalmerLab
28 Oct 25 at 1:39 am
Наркологическая клиника в клинике в Казани — это современный медицинский центр, специализирующийся на лечении алкогольной и наркотической зависимости. Основное направление деятельности заключается в проведении детоксикации, восстановлении работы нервной системы и формировании устойчивой мотивации к отказу от употребления психоактивных веществ. Все процедуры проводятся в условиях полной анонимности и медицинского контроля, что обеспечивает безопасность и доверие со стороны пациентов. Программа терапии строится по принципам доказательной медицины и индивидуального подбора лечебных средств.
Исследовать вопрос подробнее – https://narkologicheskaya-clinika-v-kazani16.ru/narkologicheskaya-klinika-kazan-otzyvy
WyattHag
28 Oct 25 at 1:42 am
kraken вход
kraken онлайн
Henryamerb
28 Oct 25 at 1:42 am
кракен vk6
кракен даркнет маркет
Henryamerb
28 Oct 25 at 1:43 am
Hi there Dear, are you truly visiting this web site on a regular basis,
if so after that you will definitely get pleasant know-how.
시알리스구매
28 Oct 25 at 1:43 am
Букмекерская контора Мелбет предлагает хорошо организованный сервис для пользования услугами оператора. Разнообразие ставок с неплохими коэффициентами сопровождается бонусными программами, нацеленными на поддержание интересов клиентов. Получение бонусов от букмекера позволяет получить новый безболезненный опыт на ставках, что особенно важно для новичков промокод при регистрации melbet 2026. Однако предполагаем, что снижение требований по отыгрышу бонусов сделали бы букмекера еще привлекательнее для игроков.
Georgeduh
28 Oct 25 at 1:45 am
купить колпак для курения
купить колпак для курения
28 Oct 25 at 1:45 am
https://t.me/bs_1Win/1174
Georgerah
28 Oct 25 at 1:46 am
https://t.me/s/bs_1Win/1197
Georgerah
28 Oct 25 at 1:47 am
I read this post completely concerning the resemblance of most
up-to-date and preceding technologies, it’s awesome article.
birthstone necklace
28 Oct 25 at 1:47 am
J’ai un veritable coup de c?ur pour Sugar Casino, ca donne une vibe electrisante. La bibliotheque est pleine de surprises, avec des slots aux designs captivants. Le bonus de depart est top. Le support est pro et accueillant. Le processus est simple et transparent, de temps en temps des offres plus genereuses seraient top. Pour finir, Sugar Casino merite une visite dynamique. A mentionner le site est rapide et immersif, ce qui rend chaque session plus palpitante. Un atout les tournois reguliers pour la competition, assure des transactions fiables.
DГ©couvrir maintenant|
vibeknightan1zef
28 Oct 25 at 1:47 am
можно ли купить диплом медсестры [url=www.frei-diplom15.ru/]можно ли купить диплом медсестры[/url] .
Diplomi_mboi
28 Oct 25 at 1:47 am
Avanafil senza ricetta [url=http://farmaciavivait.com/#]pillole per disfunzione erettile[/url] Spedra
MichaelRen
28 Oct 25 at 1:48 am
кракен ссылка
kraken vk6
Henryamerb
28 Oct 25 at 1:48 am
Here is my web page :: GameBeat online slots with verified RTP
GameBeat online slots with verified RTP
28 Oct 25 at 1:48 am
гидроизоляция подвала под ключ [url=www.gidroizolyaciya-podvala-cena.ru]www.gidroizolyaciya-podvala-cena.ru[/url] .
gidroizolyaciya podvala cena_zfKt
28 Oct 25 at 1:48 am
купить диплом в канске [url=http://rudik-diplom9.ru]купить диплом в канске[/url] .
Diplomi_zeei
28 Oct 25 at 1:49 am
стоимость гидроизоляции подвала [url=https://gidroizolyaciya-cena-8.ru/]стоимость гидроизоляции подвала[/url] .
gidroizolyaciya cena_vtKn
28 Oct 25 at 1:49 am
Лечение в клинике строится на комплексной программе, которая сочетает медикаментозную терапию, психотерапевтические методы и социальную реабилитацию. Такой подход обеспечивает устойчивый результат и предотвращает повторные срывы. Пациент проходит курс под постоянным контролем специалистов, что позволяет отслеживать динамику состояния и корректировать терапию при необходимости.
Получить дополнительную информацию – [url=https://narkologicheskaya-klinika-v-krasnodare16.ru/]наркологическая клиника краснодар[/url]
Johnnycek
28 Oct 25 at 1:50 am