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!
Спасение жизни: профессиональное лечение наркотической зависимости — клиника «Призма» предлагает комплексный подход к лечению наркозависимости, включая детоксикацию, психологическую поддержку и реабилитацию. Узнайте больше: milinda.ru Получить дополнительные сведения – http://www.artlib.ru/index.php?id=26&idr=18&idt=50572
Jameslok
16 Sep 25 at 3:48 pm
Captain Rizk Megaways Pin up AZ
EdwardTix
16 Sep 25 at 3:49 pm
киного [url=kinogo-12.top]киного[/url] .
kinogo_hnol
16 Sep 25 at 3:49 pm
В поисках самых свежих трейлеров фильмов 2026 и трейлеров 2026 на русском? Наш портал — это место, где собираются лучшие трейлеры сериалов 2026. Здесь вы можете смотреть трейлер бесплатно в хорошем качестве, будь то громкая премьера лорд трейлер или долгожданный трейлер 3 сезона вашего любимого сериала. Мы тщательно отбираем видео, чтобы вы могли смотреть трейлеры онлайн без спойлеров и в отличном разрешении. Всю коллекцию вы найдете по ссылке ниже: https://lordtrailer.ru/
Stevenbrabs
16 Sep 25 at 3:50 pm
заказать рулонные шторы цена [url=http://avtomaticheskie-rulonnye-shtory5.ru]заказать рулонные шторы цена[/url] .
avtomaticheskie rylonnie shtori_sisr
16 Sep 25 at 3:51 pm
электрокранизы [url=https://karniz-s-elektroprivodom-kupit.ru/]karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_ngEr
16 Sep 25 at 3:53 pm
В поисках самых свежих трейлеров фильмов 2026 и трейлеров 2026 на русском? Наш портал — это место, где собираются лучшие трейлеры сериалов 2026. Здесь вы можете смотреть трейлер бесплатно в хорошем качестве, будь то громкая премьера лорд трейлер или долгожданный трейлер 3 сезона вашего любимого сериала. Мы тщательно отбираем видео, чтобы вы могли смотреть трейлеры онлайн без спойлеров и в отличном разрешении. Всю коллекцию вы найдете по ссылке ниже: трейлер смотреть онлайн бесплатно
Stevenbrabs
16 Sep 25 at 3:53 pm
смотреть боевики [url=https://kinogo-12.top]https://kinogo-12.top[/url] .
kinogo_pmol
16 Sep 25 at 3:54 pm
Hey I know this is off topic but I was wondering if you
knew of any widgets I could add to my blog that
automatically tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe you would have some experience with something like this.
Please let me know if you run into anything.
I truly enjoy reading your blog and I look forward to your new updates.
Legacy Bitfundex
16 Sep 25 at 3:55 pm
Exceptional post however , I was wondering if you could
write a litte more on this topic? I’d be very grateful if you could elaborate
a little bit further. Many thanks!
789p
16 Sep 25 at 3:56 pm
Вы можете просмотреть различные
категории писем, такие как
«Работа», «Продажа», «Личные объявления» и «Услуги», и прочитать возмутительные ответы.
www.tekkaledogaltas.com/rating-safe-online-casinos-how-to-select-best-establishment/
16 Sep 25 at 3:59 pm
шторы на окна купить [url=www.elektricheskie-rulonnye-shtory15.ru]www.elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_ppEi
16 Sep 25 at 3:59 pm
When I originally left a comment I appear to have clicked on the -Notify me when new
comments are added- checkbox and now whenever a comment
is added I receive four emails with the exact same comment.
Is there a way you can remove me from that service?
Many thanks!
نحوه برخورد با دانش آموز متقلب
16 Sep 25 at 3:59 pm
электрический карниз для штор купить [url=www.karniz-s-elektroprivodom-kupit.ru]www.karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_deEr
16 Sep 25 at 4:00 pm
https://novosti.ua/tech/virtualnui-nomer-telefonu-suchasnui-instrument-dla-reestracii-ta-bezpeky-onlain
https://novosti.ua/tech/virtualnui-nomer-telefonu-suchasnui-instrument-dla-reestracii-ta-bezpeky-onlain
16 Sep 25 at 4:02 pm
Pretty! This has been an incredibly wonderful article.
Thanks for supplying this information.
casino BLITZ зеркало
16 Sep 25 at 4:03 pm
1уин [url=www.1win12015.ru]www.1win12015.ru[/url]
1win_piei
16 Sep 25 at 4:03 pm
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Хочешь знать всё? – https://soig.fr/timetable-for-wordpress-sample-3
DavidArike
16 Sep 25 at 4:04 pm
mostbet mobil kirish uz [url=https://mostbet4175.ru]https://mostbet4175.ru[/url]
mostbet_nwmi
16 Sep 25 at 4:04 pm
В Краснодаре решение есть — наркологическая клиника. Здесь помогают людям выйти из запоя без страха и осуждения. Всё анонимно, грамотно и с заботой о каждом пациенте.
Углубиться в тему – [url=https://vyvod-iz-zapoya-krasnodar12.ru/]нарколог на дом цена город краснодар[/url]
Henrynox
16 Sep 25 at 4:05 pm
электрокарнизы [url=https://karniz-s-elektroprivodom-kupit.ru]https://karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_fxEr
16 Sep 25 at 4:05 pm
рольшторы заказать [url=elektricheskie-rulonnye-shtory15.ru]elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_vlEi
16 Sep 25 at 4:06 pm
First of all I would like to say terrific blog!
I had a quick question that I’d like to ask if you don’t mind.
I was interested to find out how you center yourself and clear your head prior to writing.
I have had a hard time clearing my mind in getting my ideas out there.
I truly do take pleasure in writing however it just seems like the first 10 to 15 minutes are lost simply just
trying to figure out how to begin. Any suggestions
or tips? Cheers!
Brightside Light Scapes
16 Sep 25 at 4:08 pm
apotheke online: europa apotheke – apotheke online
Israelpaync
16 Sep 25 at 4:08 pm
В этой статье мы рассматриваем разрушительное влияние зависимости на жизнь человека. Обсуждаются аспекты, такие как здоровье, отношения и профессиональные достижения. Читатели узнают о необходимости обращения за помощью и о путях к восстановлению.
Что скрывают от вас? – [url=https://lux-clinic.ru/stati/narkotiki-vidy-opasnost-upotrebleniya.html]виды курящих наркотиков[/url]
Stevedom
16 Sep 25 at 4:09 pm
плинко казино скачать [url=www.1win12015.ru]www.1win12015.ru[/url]
1win_hcei
16 Sep 25 at 4:11 pm
рулонная штора на заказ цена [url=https://elektricheskie-rulonnye-shtory15.ru]https://elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_tzEi
16 Sep 25 at 4:12 pm
рулонные шторы на балконные окна [url=http://avtomaticheskie-rulonnye-shtory5.ru/]http://avtomaticheskie-rulonnye-shtory5.ru/[/url] .
avtomaticheskie rylonnie shtori_essr
16 Sep 25 at 4:13 pm
https://mobihobby.ru/article/chto_takoe_odnorazovye_virtualnye_nomera_9141161
https://mobihobby.ru/article/chto_takoe_odnorazovye_virtualnye_nomera_9141161
16 Sep 25 at 4:13 pm
фильмы онлайн без подписки [url=http://www.kinogo-12.top]http://www.kinogo-12.top[/url] .
kinogo_oool
16 Sep 25 at 4:14 pm
вывод из запоя круглосуточно
vivod-iz-zapoya-smolensk018.ru
вывод из запоя
narkologiyasmolenskNeT
16 Sep 25 at 4:17 pm
рулонная штора на заказ цена [url=https://avtomaticheskie-rulonnye-shtory5.ru/]рулонная штора на заказ цена[/url] .
avtomaticheskie rylonnie shtori_kwsr
16 Sep 25 at 4:17 pm
Mums and Dads, composed lah, reputable institution combined
ᴡith solid mathematics base means youг child cɑn tackle decimals
plᥙѕ geometry boldly, guiding fоr Ƅetter gеneral academic performance.
Jurong Pioneer Junior College, formed fгom a strategic
merger, ρrovides a forward-thinking education tһаt highlights China readiness
аnd international engagement. Modern schools supply excellent resources fоr commerce, sciences, ɑnd arts, promoting practical skills
ɑnd imagination. Trainees delight in improving programs ⅼike international cooperations and character-building efforts.
Тhe college’s supportive community promotes strength ɑnd
leadership tһrough diverse co-curricular activities. Graduates ɑre weⅼl-equipped fߋr dynamic professions, embodying care ɑnd
constant enhancement.
Victoria Junior College ignites creativity ɑnd cultivates visionary leadership, empowering students tο develop positive modification tһrough a
curriculum tһat stimulates passions ɑnd motivates
vibrant thinking in а stunning seaside campus setting.
Тhе school’s detailed facilities, consisting ᧐f
humanities conversation гooms, science research study suites, ɑnd arts
performance venues, assistance enriched programs іn arts, humanities, and sciences tһat promote
interdisciplinary insights аnd scholastic proficiency.
Strategic alliances ᴡith secondary schools thrߋugh incorporated programs ensure а seamless instructional journey, offering accelerated finding ᧐ut courses and
specialized electives tһat deal with specific strengths and intеrests.
Service-learning efforts аnd global outreach jobs,
ѕuch аs worldwide volunteer expeditions ɑnd
management online forums, build caring dispositions, resilience, and a dedication tߋ
neighborhood welfare. Graduates lead ᴡith undeviating conviction аnd accomplish remarkable success іn universities ɑnd careers,
embodying Victoria Junior College’ѕ legacy οf supporting
creative, principled, ɑnd transformative individuals.
Alas, ԝithout robust maths ɑt Junior College, even toⲣ institution youngsters
ϲould stumble іn secondary equations, so
develop thiѕ pr᧐mptly leh.
Oi oi, Singapore parents, maths гemains pгobably the highly imρortant primary topic,
fostering innovation іn prߋblem-solving іn creative professions.
Hey hey, Singapore folks, math гemains perhaps the mοst imρortant primary subject, promoting innovation tһrough issue-resolving tο creative professions.
Оh man, even whether establishment proves fancy, math іѕ the critical discipline fоr cultivcates assurance rеgarding numbers.
Oh no, primary maths educates everyday implementations including budgeting, tһerefore ensure your
child getѕ it correctly Ьeginning еarly.
Listen up, calm pom pі pi, math remains pɑrt of thе leading subjects ɗuring Junior College, building base fοr A-Level advanced math.
Math trains yߋu to think critically, a must-have in oսr fast-paced worlɗ lah.
Oh, mathematics serves аs thhe groundwork block fߋr primary schooling,
helping kids іn dimensional analysis іn design paths.
Alas, ѡithout solid mathematics іn Junior College,
no matter leading school youngsters mɑy stumble ɑt higһ school equations, tһus develop tһɑt now leh.
Ꮇy blog … singapore math tuition
singapore math tuition
16 Sep 25 at 4:17 pm
фантастика онлайн [url=http://kinogo-12.top/]http://kinogo-12.top/[/url] .
kinogo_srol
16 Sep 25 at 4:18 pm
прогнозы lucky jet [url=https://1win12016.ru/]https://1win12016.ru/[/url]
1win_uwOa
16 Sep 25 at 4:19 pm
рулонные шторы с электроприводом на пластиковые окна [url=https://avtomaticheskie-rulonnye-shtory5.ru]https://avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_srsr
16 Sep 25 at 4:19 pm
Вот это я понимаю СЕРВИС:ok: Превзошло все мои ожидания, доставили раньше обещанного… Магаз ровный (до последнего сомневался, что всё на столько гладко…)
Приобрести кокаин, мефедрон, бошки
в курске есть ваш магаз?
GeorgeOvale
16 Sep 25 at 4:20 pm
сериалы онлайн [url=www.kinogo-12.top]www.kinogo-12.top[/url] .
kinogo_giol
16 Sep 25 at 4:21 pm
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Где можно узнать подробнее? – https://www.genuss-catering.com/how-to-design-the-best-creative-event-concept
FrankCew
16 Sep 25 at 4:21 pm
1вин регистрация на официальном сайте [url=https://1win12016.ru]https://1win12016.ru[/url]
1win_gxOa
16 Sep 25 at 4:23 pm
I’m very happy to uncover this web site.
I need to to thank you for ones time for this wonderful read!!
I definitely really liked every bit of it and I have
you saved to fav to see new stuff on your website.
waspe vape 60000 puffs
16 Sep 25 at 4:26 pm
электрический карниз для штор купить [url=www.karniz-s-elektroprivodom-kupit.ru/]www.karniz-s-elektroprivodom-kupit.ru/[/url] .
karniz s elektroprivodom kypit_vyEr
16 Sep 25 at 4:27 pm
mostbet uz скачать [url=http://mostbet4175.ru/]mostbet uz скачать[/url]
mostbet_ddmi
16 Sep 25 at 4:28 pm
рулонные. шторы. +на. пластиковые. окна. купить. [url=www.avtomaticheskie-rulonnye-shtory5.ru]www.avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_dqsr
16 Sep 25 at 4:30 pm
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Читать далее > – https://voltify4doctors.com/jalbitedrinks-liquor-recipe
ThomasHer
16 Sep 25 at 4:30 pm
автоматические карнизы [url=https://karniz-s-elektroprivodom-kupit.ru/]https://karniz-s-elektroprivodom-kupit.ru/[/url] .
karniz s elektroprivodom kypit_ekEr
16 Sep 25 at 4:31 pm
смотреть фильмы бесплатно [url=www.kinogo-12.top]www.kinogo-12.top[/url] .
kinogo_rgol
16 Sep 25 at 4:31 pm
электрокарниз купить в москве [url=https://karniz-s-elektroprivodom-kupit.ru]https://karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_zgEr
16 Sep 25 at 4:34 pm
автоматические рулонные шторы на окна [url=https://elektricheskie-rulonnye-shtory15.ru]https://elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_jfEi
16 Sep 25 at 4:34 pm
рулонные шторы купить москва недорого [url=https://elektricheskie-rulonnye-shtory15.ru]https://elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_qrEi
16 Sep 25 at 4:38 pm