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!
1xbet latest promo code — https://absoluteservices.in/pages/1xbet_promo_code_india___welcome_bonus_1.html A 1xBet promo code list is a compilation of active promo codes that can be used to claim bonuses on the platform. These lists are often updated regularly to reflect the latest offers and provide users with the best possible value.
DanielSic
30 Oct 25 at 5:48 pm
Great beat ! I would like to apprentice whilst you amend your site, how can i subscribe for a weblog web site?
The account helped me a appropriate deal.
I have been a little bit familiar of this your broadcast offered
brilliant clear concept
my.hiepsiit.com
30 Oct 25 at 5:48 pm
I’ve been exploring for a bit for any high quality articles or blog posts in this kind of house
. Exploring in Yahoo I eventually stumbled upon this web site.
Reading this information So i am satisfied to convey that
I’ve an incredibly just right uncanny feeling I discovered exactly what I needed.
I most indisputably will make certain to do not omit this website and give
it a look regularly.
teslabahis giriş
30 Oct 25 at 5:49 pm
электрокарниз двухрядный [url=https://www.elektrokarniz499.ru]https://www.elektrokarniz499.ru[/url] .
elektrokarniz_soKl
30 Oct 25 at 5:50 pm
онлайн казино
JosephFus
30 Oct 25 at 5:52 pm
купить диплом с записью в реестре [url=https://frei-diplom2.ru/]купить диплом с записью в реестре[/url] .
Diplomi_cgEa
30 Oct 25 at 5:55 pm
Hi there! I know this is somewhat off-topic however I had to ask.
Does operating a well-established website like yours take a lot of
work? I’m completely new to running a blog but I do write in my
diary daily. I’d like to start a blog so I will be able
to share my own experience and feelings online. Please
let me know if you have any suggestions or tips for brand new aspiring bloggers.
Appreciate it!
web site
30 Oct 25 at 5:55 pm
Everyone loves what you guys are usually up too. Such clever work and exposure!
Keep up the fantastic works guys I’ve added
you guys to my own blogroll.
website
30 Oct 25 at 5:59 pm
казино онлайн
JosephFus
30 Oct 25 at 6:03 pm
continuously i used to read smaller posts which also clear their motive, and that is
also happening with this paragraph which I am reading at this
time.
buôn bán nội tạng
30 Oct 25 at 6:05 pm
купить диплом техникума открыто [url=www.frei-diplom8.ru]купить диплом техникума открыто[/url] .
Diplomi_qasr
30 Oct 25 at 6:06 pm
промокоды и фриспины dragon money
JosephFus
30 Oct 25 at 6:06 pm
Oi parents, regardⅼess іf your kid enrolls in a prestigious Junior College in Singapore, wіthout a solid
maths foundation, kids miɡht faϲе difficulties
aɡainst A Levels verbal рroblems аѕ well as
mіss out foг elite neҳt-level positions lah.
Victoria Junior College cultivates imagination ɑnd management, sparking
enthusiasms fⲟr future production. Coastal school facilities support arts,
humanities, ɑnd sciences. Integrated programs ѡith
alliances offer smooth, enriched education. Service аnd
international initiatives construct caring, resistant individuals.
Graduates lead ԝith conviction, attaining impressive success.
Victoria Junior College fires սp creativity and fosters visionary leadership, empowering students tο create
favrable modification tһrough а curriculum that triggers
enthusiasms аnd encourages strong thinking іn а attractive seaside campus setting.
Тhe school’s detailed facilities, including liberal arts discussion spaces,
science гesearch study suites, and arts efficiency ⲣlaces,
assistance enriched programs іn arts, liberal arts, and sciences that promote interdisciplinary insights ɑnd academic mastery.
Strategic alliances ѡith secondary schools tһrough incorporated programs guarantee ɑ seamless academic journey, providing sped ᥙp learning paths аnd specialized electives tһat cater to specific strengths ɑnd іnterests.
Service-learning efforts аnd worldwide outreach
tasks, ѕuch аs global volunteer expeditions аnd leadership forums, build caring dispositions,
durability, ɑnd a commitment to community welfare.
Graduates lead ԝith steady conviction and accomplish extraordinary success іn universities and careers, embodying Victoria Junior College’ѕ tradition of supporting
creative, principled, аnd transformative people.
Aiyo, lacking solid math аt Junior College, еvеn leading school youngsters may stumble at secondary algebra,
tһerefore cultivate thаt immediately leh.
Oi oi, Singapore moms and dads, math гemains ρerhaps the most crucial primary discipline,
promoting innovation tһrough issue-resolving fߋr groundbreaking professions.
Parents, kiasu approach engaged lah, solid primary maths guides tо Ьetter scientific grasp and tech dreams.
Listen ᥙp, composed pom pi pi, mathematics rеmains pаrt
from tһe top subjects at Junior College, building foundation t᧐ A-Level advanced math.
Βesides fгom institution amenities, emphasize on maths to avоid common errors
including inattentive mistakes ɑt assessments.
Kiasu competition fosters innovation іn Math рroblem-solving.
Ⲟh no, primary maths instructs everyday սses liқе money
management, so guarantee your kid gets this properly beginning young age.
Ꮋave a ⅼook ɑt my page; math tutor palo alto for grade school and middle school
math tutor palo alto for grade school and middle school
30 Oct 25 at 6:08 pm
Today, while I was at work, my sister stole my iphone and
tested to see if it can survive a 40 foot drop, just so she can be a youtube sensation. My apple ipad is now
destroyed and she has 83 views. I know this is completely off topic but I
had to share it with someone!
fast withdrawal casinos
30 Oct 25 at 6:08 pm
farmacia viva: Avanafil senza ricetta – farmacia viva
ClydeExamp
30 Oct 25 at 6:10 pm
Мучает зуд и жжение? Геморой – лечение без боли и очередей: диагностика, консервативная терапия, латексное лигирование, склеротерапия, лазер. Приём проктолога, анонимно, в день обращения. Индивидуальный план, быстрое восстановление, понятные цены и поддержка 24/7.
proctofor-359
30 Oct 25 at 6:10 pm
Every weekend i used to pay a visit this website, for the reason that i wish for enjoyment,
as this this web site conations genuinely fastidious funny material too.
web site
30 Oct 25 at 6:11 pm
My developer is trying to convince me to move to .net from PHP.
I have always disliked the idea because of the
expenses. But he’s tryiong none the less. I’ve been using WordPress on various websites for about a year and
am anxious about switching to another platform.
I have heard great things about blogengine.net.
Is there a way I can import all my wordpress posts
into it? Any kind of help would be really appreciated!
آموزش بردکرامب Breadcrumb
30 Oct 25 at 6:13 pm
[url=https://astrolas.ru/]обучение астрологии для начинающих[/url] — это шанс раскрыть тайны судьбы и личного потенциала. В Астрологической Студии вы получите точные индивидуальные прогнозы и персональные рекомендации. Наши астрологи помогут разобраться в личных отношениях, бизнесе и жизненных перспективах. Форум студии создан для тех, кто ищет ответы и поддержку в мире звёздных знаний. Мы публикуем статьи, материалы и аналитические разборы гороскопов для начинающих и практикующих астрологов. Для новичков в мире астрологии мы подготовили доступные курсы и индивидуальные занятия. Мы поддерживаем профессиональное сообщество и поощряем развитие каждого участника. Мы помогаем использовать астрологию как инструмент самопознания и личного роста. Наши специалисты анализируют уникальные положения планет в момент вашего рождения. Мы объединяем традиционные знания и современные подходы. Погрузитесь в мир астрологии и получите ценные ответы на свои вопросы. Запишитесь на консультацию и откройте новые горизонты. Астрологическая Студия приглашает вас в удивительный мир звёзд и планет. Пусть астрология станет вашим инструментом осознанности и внутреннего равновесия. Присоединяйтесь к нашему сообществу и развивайтесь вместе с лучшими астрологами.
https://astrolas.ru/
LouisSpasp
30 Oct 25 at 6:13 pm
промокоды и фриспины dragon money
JosephFus
30 Oct 25 at 6:14 pm
Благодаря последовательной работе врачей и постоянному наблюдению лечение проходит безопасно и эффективно, а пациент получает необходимую поддержку на всех этапах терапии.
Детальнее – http://narkologicheskaya-klinika-v-voronezhe17.ru/chastnaya-narkologicheskaya-klinika-voronezh/
Leslieclews
30 Oct 25 at 6:14 pm
купить диплом в ярославле [url=https://rudik-diplom3.ru]купить диплом в ярославле[/url] .
Diplomi_hiei
30 Oct 25 at 6:15 pm
https://vitalpharma24.com/# diskrete Lieferung per DHL
Davidjealp
30 Oct 25 at 6:15 pm
Vita Homme: Kamagra oral jelly France – Sildenafil générique
RobertJuike
30 Oct 25 at 6:15 pm
VitaHomme: Kamagra sans ordonnance – Vita Homme
RobertJuike
30 Oct 25 at 6:16 pm
Мучает зуд и жжение? Геморой – лечение без боли и очередей: диагностика, консервативная терапия, латексное лигирование, склеротерапия, лазер. Приём проктолога, анонимно, в день обращения. Индивидуальный план, быстрое восстановление, понятные цены и поддержка 24/7.
proctofor-490
30 Oct 25 at 6:17 pm
Мучает зуд и жжение? Геморой – лечение без боли и очередей: диагностика, консервативная терапия, латексное лигирование, склеротерапия, лазер. Приём проктолога, анонимно, в день обращения. Индивидуальный план, быстрое восстановление, понятные цены и поддержка 24/7.
proctofor-64
30 Oct 25 at 6:19 pm
диплом нефтяного техникума купить [url=https://frei-diplom9.ru]диплом нефтяного техникума купить[/url] .
Diplomi_area
30 Oct 25 at 6:19 pm
windows loyalty program even more highlights 1xbet’s commitment to providing a diverse and complete betting environment to each [url=https://solasolempreendimentos.com.br/1bet5/1xbet-thailand-download-app-your-guide-to-mobile-13/]https://solasolempreendimentos.com.br/1bet5/1xbet-thailand-download-app-your-guide-to-mobile-13/[/url].
Austincapse
30 Oct 25 at 6:23 pm
Hello there! Do you use Twitter? I’d like to follow you if that would
be ok. I’m definitely enjoying your blog and look forward to
new updates.
video bokep indonesia
30 Oct 25 at 6:23 pm
Hey there would you mind letting me know which hosting company you’re working
with? I’ve loaded your blog in 3 different web browsers and I must
say this blog loads a lot quicker then most. Can you suggest a good internet hosting provider at a
reasonable price? Many thanks, I appreciate it!
loudness in psychoacoustics
30 Oct 25 at 6:26 pm
dragon money обзор
JosephFus
30 Oct 25 at 6:26 pm
Перед процедурой врач оценивает состояние пациента, измеряет давление, пульс и уровень насыщения крови кислородом. После осмотра подбирается состав инфузии, включающий препараты для дезинтоксикации, восстановления водно-солевого баланса и нормализации работы органов. Введение растворов осуществляется внутривенно, под контролем специалиста. Длительность процедуры — от 40 минут до 1,5 часов.
Подробнее тут – https://kapelnicza-ot-zapoya-v-volgograde17.ru/kapelnicza-ot-pokhmelya-volgograd
Stephenchork
30 Oct 25 at 6:27 pm
Kamagra sans ordonnance: acheter Kamagra en ligne – Sildenafil générique
RobertJuike
30 Oct 25 at 6:28 pm
Kamagra pas cher France: Kamagra oral jelly France – acheter Kamagra en ligne
RichardImmon
30 Oct 25 at 6:32 pm
как купить диплом колледжа [url=https://www.frei-diplom9.ru]https://www.frei-diplom9.ru[/url] .
Diplomi_xyea
30 Oct 25 at 6:32 pm
chery официальный дилер chery 2024
chery-465
30 Oct 25 at 6:32 pm
Because the admin of this website is working, no hesitation very shortly it will
be renowned, due to its feature contents.
packers and movers
30 Oct 25 at 6:34 pm
купить диплом москва с занесением в реестр [url=https://www.frei-diplom2.ru]купить диплом москва с занесением в реестр[/url] .
Diplomi_lpEa
30 Oct 25 at 6:35 pm
Hi there to every one, it’s actually a nice for me to
go to see this site, it consists of valuable Information.
Fundwix Invia
30 Oct 25 at 6:38 pm
Sildenafil générique: Kamagra sans ordonnance – Sildenafil générique
RichardImmon
30 Oct 25 at 6:38 pm
http://farmaciavivait.com/# differenza tra Spedra e Viagra
Davidjealp
30 Oct 25 at 6:40 pm
Slot777 adalah situs slot 777 gacor terbaru dengan jackpot mudah didapat,
aman, dan praktis. Nikmati permainan seru dengan bonus melimpah
situs slot 777
30 Oct 25 at 6:44 pm
рулонные шторы на окно в кухне [url=www.rulonnye-shtory-s-elektroprivodom7.ru/]www.rulonnye-shtory-s-elektroprivodom7.ru/[/url] .
rylonnie shtori s elektroprivodom_epMl
30 Oct 25 at 6:44 pm
each time i used to read smaller articles that also clear their motive,
and that is also happening with this article which I am reading
now.
Klar Bitrow
30 Oct 25 at 6:44 pm
Очень доволен сервисом DRINKIO — всегда пунктуально, аккуратно и быстро. Курьеры приезжают точно в заявленное время, упаковка надёжная. Ассортимент широкий, есть всё необходимое. Сайт простой и удобный, оформление заказа занимает меньше минуты. Радует, что доставка работает 24 часа в сутки. Отличный вариант для заказа алкоголя на дом в Москве – https://drinkio105.ru/
Ronaldskada
30 Oct 25 at 6:45 pm
Доброго!
Купите виртуальный номер телефона навсегда и забудьте о проблемах с доступностью связи. Постоянный виртуальный номер идеально подходит для смс и регистрации в сервисах. Мы предлагаем простые и надежные решения для вашего удобства. Виртуальный номер навсегда – это стабильность и конфиденциальность. Выбирайте лучшее для себя.
Полная информация по ссылке – [url=https://line-landing.by/pochemu-virtualnyj-nomer-nuzhen-dlya-rasshireniya-biznesa-i-monetizaczii/]купить вирт номер навсегда[/url]
купить виртуальный номер навсегда, купить виртуальный номер, купить виртуальный номер
купить постоянный виртуальный номер, постоянный виртуальный номер для смс, купить виртуальный номер для смс навсегда
Удачи и комфорта в общении!!
Nomerpl
30 Oct 25 at 6:46 pm
chery 1.6 chery tiggo 1.6
chery-269
30 Oct 25 at 6:47 pm
This backlink can be from the PBN’s blog site or homepage, but the key is to
avoid repeating the very same process on each domain.
my web blog :: Gsa ser link list
Gsa ser link list
30 Oct 25 at 6:47 pm
рулонные шторы на окна цена [url=http://rulonnye-shtory-s-elektroprivodom7.ru/]рулонные шторы на окна цена[/url] .
rylonnie shtori s elektroprivodom_leMl
30 Oct 25 at 6:48 pm