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 giri? [url=www.1xbet-giris-9.com]1xbet giri?[/url] .
1xbet giris_wzon
24 Oct 25 at 11:05 am
[url=https://ltdton.ru/brand/ls-is/]LS IS[/url]
CesarBat
24 Oct 25 at 11:06 am
1xbet ?yelik [url=http://www.1xbet-giris-3.com]http://www.1xbet-giris-3.com[/url] .
1xbet giris_xoMi
24 Oct 25 at 11:08 am
Fantastic goods from you, man. I have understand your stuff
previous to and you are just extremely great. I actually like what you’ve acquired here, certainly like what
you are stating and the way in which you say it. You make it enjoyable and you still care for to keep it sensible.
I can not wait to read far more from you. This is
really a terrific website.
Take a look at my blog post :: автосервис митсубиси
автосервис митсубиси
24 Oct 25 at 11:08 am
1xbet resmi giri? [url=https://1xbet-giris-10.com/]1xbet resmi giri?[/url] .
1xbet giris_kvka
24 Oct 25 at 11:08 am
купить диплом в обнинске [url=http://rudik-diplom14.ru]http://rudik-diplom14.ru[/url] .
Diplomi_dzea
24 Oct 25 at 11:09 am
Капельница от запоя и детоксикация – ключевые подходы в лечении алкогольной зависимости. В владимире услуги по лечению запоя включают в себя капельницы, которые способствуют быстро вывести токсины из организма. Капельница включает препараты для восстановления водно-электролитного баланса и облегчения симптомов абстиненции, что поддерживает лечение запоя. лечение запоя владимир Детоксикация же является многогранным процессом, который включает не только физическую очистку, но также психологическую помощь пациентов. В центрах по лечению алкоголизма в владимире применяют оба метода: капельницы для острого состояния и программы реабилитации после запоя. Это помогает в избавлении от зависимости и восстановлении здоровья. Помните, что профессиональная помощь в этом аспекте крайне важна для эффективного лечения.
izzapoyavladimirNeT
24 Oct 25 at 11:10 am
https://t.me/bs_1xbet/40
https://t.me/s/bs_1xbet/51
24 Oct 25 at 11:10 am
https://herengezondheid.shop/# goedkope Viagra tabletten online
Hermanereli
24 Oct 25 at 11:11 am
BJ39 한국에서 플레이하고 최고의 온라인 도박
경험을 즐기세요: 슬롯, 라이브 카지노, 스포츠북, 그리고 매일 풍성한 보너스가 제공됩니다.
BJ39 – 한국 1위 온라인 도박 사이트
24 Oct 25 at 11:11 am
https://t.me/s/bs_1xbet/5
https://t.me/bs_1xbet/33
24 Oct 25 at 11:11 am
1xbet [url=http://1xbet-giris-7.com]1xbet[/url] .
1xbet giris_snKn
24 Oct 25 at 11:12 am
Подбираете в Москве центр для детей с психологической помощью и реабилитацией? Ищете коррекция речевых нарушений? Посетите сайт Центра здоровья Юрия Титова — titov.center — семейный центр, посвящённый здоровью, развитию и социальной реабилитации детей и подростков. Узнайте о наших методиках и команде профессионалов, а также о диагнозах, с которыми мы работаем. Мы предлагаем обширный набор индивидуальных программ реабилитации. Читать подробнее на сайте.
yisonapoft
24 Oct 25 at 11:12 am
Learn more on the website: https://tuikhoeconban.com
JamesCiGma
24 Oct 25 at 11:14 am
1xbet giri? linki [url=https://www.1xbet-giris-8.com]1xbet giri? linki[/url] .
1xbet giris_uiPn
24 Oct 25 at 11:15 am
1 xbet giri? [url=https://1xbet-giris-10.com]1 xbet giri?[/url] .
1xbet giris_wuka
24 Oct 25 at 11:15 am
1xbet t?rkiye [url=https://www.1xbet-giris-7.com]1xbet t?rkiye[/url] .
1xbet giris_xkKn
24 Oct 25 at 11:15 am
1xbet giri? linki [url=www.1xbet-giris-9.com]1xbet giri? linki[/url] .
1xbet giris_qnon
24 Oct 25 at 11:16 am
https://t.me/bs_1xbet/24
https://t.me/s/bs_1xbet/22
24 Oct 25 at 11:17 am
https://t.me/bs_1xbet/26
https://t.me/s/bs_1xbet/12
24 Oct 25 at 11:17 am
1x bet giri? [url=http://1xbet-9.com/]http://1xbet-9.com/[/url] .
1xbet_qmSn
24 Oct 25 at 11:19 am
The latest and most relevant: https://totalfratmove.com
Charleswargy
24 Oct 25 at 11:19 am
The best is only here: https://speech-language-therapy.com
Anthonyquila
24 Oct 25 at 11:19 am
erectiepillen discreet bestellen [url=https://herengezondheid.shop/#]veilige online medicijnen Nederland[/url] online apotheek zonder recept
Davidduese
24 Oct 25 at 11:21 am
1xbet t?rkiye [url=https://1xbet-giris-3.com/]1xbet t?rkiye[/url] .
1xbet giris_hqMi
24 Oct 25 at 11:22 am
1xbet giri?i [url=http://www.1xbet-giris-8.com]1xbet giri?i[/url] .
1xbet giris_rrPn
24 Oct 25 at 11:24 am
1 x bet giri? [url=1xbet-4.com]1xbet-4.com[/url] .
1xbet_qjol
24 Oct 25 at 11:25 am
xbet giri? [url=1xbet-giris-10.com]xbet giri?[/url] .
1xbet giris_gpka
24 Oct 25 at 11:26 am
1xbet giris [url=www.1xbet-giris-7.com/]1xbet giris[/url] .
1xbet giris_tnKn
24 Oct 25 at 11:27 am
1xbet ?yelik [url=www.1xbet-giris-9.com]1xbet ?yelik[/url] .
1xbet giris_slon
24 Oct 25 at 11:28 am
Hey parents, even if yoᥙr child attends аt
a leading Junior College іn Singapore, minus a robust maths foundation,
tһey could struggle ԝith A Levels text-based challenges ɑs well aѕ lose opportunities ⲟn premium hіgh school spots lah.
Anderson Serangoon Junior College іs a lively
institution born fгom the merger of two renowned colleges, promoting ɑn encouraging
environment that stresses holistic development ɑnd
scholastic excellence. Τhе college boasts modern-Ԁay facilities, including
advanced labs аnd collective areаs, maқing it pоssible
for students to engage deeply in STEM аnd innovation-driven projects.
Ԝith a strong focus οn management ɑnd
character structure, trainees gain fгom diverse c᧐-curricular activities tһat cultivate strength ɑnd teamwork.
Ӏts dedication to worldwide рoint ߋf views throuɡh exchange programs expands horizons ɑnd prepares students
f᧐r an interconnected ѡorld. Graduates frequently protected ρlaces in leading universities, refvlecting tһe college’s commitment to nurturing positive, ѡell-rounded
individuals.
River Valley Нigh School Junior College seamlessly integrates bilingual education ᴡith a
strong dedication tо ecological stewardship, nurturing eco-conscious leaders ѡhօ possess sharp worldwide perspectives ɑnd a devotion tօ sustainable practices in an sіgnificantly interconnected
ѡorld. Thе school’s innovative labs, green innovation centers, ɑnd environment-friendly school designs support pioneering learning іn sciences, humanities,
аnd environmental studies, motivating students tߋ participate
іn hands-on experiments ɑnd ingenious options to
real-worⅼd obstacles. Cultural immersion programs, such ɑs language exchanges ɑnd
heritage trips, integrated ԝith neighborhood service
projects focused ᧐n conservation, boost trainees’ empathy, cultural
intelligence, ɑnd practical skills fօr positive social effect.
Withіn a harmonious and helpful community, participation іn sports teams, arts societies, ɑnd
management workshops promotes physical wellness, team effort, ɑnd
durability, producing healthy individuals prepared fоr future ventures.
Graduates fгom River Valley Ꮋigh School Junior College ɑre preferably
positioned for success іn leading universities ɑnd
professions, embodying tһe school’ѕ core values of perseverance,
cultural acumen, аnd a proactive method to international
sustainability.
Wah lao, no matter tһough institution remaіns һigh-end, maths іs tһe mɑke-or-break subject tο developing confidence гegarding calculations.
Alas, primary maths teaches real-ѡorld uses likе money management, so ensure your
child masters thаt correctly begіnning eaгly.
Goodness, regardless wһether school гemains atas,
math acts ⅼike thе decisive topic іn developing confidence гegarding
figures.
Aiyo, ᴡithout strong math аt Junior College,
no matter leading institution children сould struggle аt high school
equations, tһerefore develop tһat promрtly leh.
Failing to dօ well in A-levels mіght mеan retaking оr ցoing poly, bսt
JC route iѕ faster іf yoᥙ score һigh.
Eh eh, steady pom ρi pi, math іs one from the leading disciplines at
Junior College, layinng base іn A-Level hіgher calculations.
Apɑrt beyond school facilities, focus ᥙpon mathematics in order tⲟ
stoⲣ typical errors including sloppy errors іn assessments.
Parents, competitive mode engaged lah, solid primary
maths гesults t᧐ improved science comprehension аnd tech dreams.
Нere is my web paɡe: Raffles Institution Junior College
Raffles Institution Junior College
24 Oct 25 at 11:31 am
xbet giri? [url=1xbet-giris-8.com]xbet giri?[/url] .
1xbet giris_fbPn
24 Oct 25 at 11:34 am
1xbet g?ncel adres [url=http://1xbet-giris-3.com]1xbet g?ncel adres[/url] .
1xbet giris_otMi
24 Oct 25 at 11:35 am
1xbet tr [url=http://www.1xbet-giris-9.com]1xbet tr[/url] .
1xbet giris_moon
24 Oct 25 at 11:37 am
1 x bet giri? [url=https://www.1xbet-giris-10.com]1 x bet giri?[/url] .
1xbet giris_efka
24 Oct 25 at 11:40 am
https://t.me/s/bs_1xbet/13
https://t.me/bs_1xbet/47
24 Oct 25 at 11:40 am
Je suis epate par BassBet Casino, ca offre un plaisir energique. Il y a un flot de jeux captivants, offrant des sessions live immersives. Amplifiant l’excitation du jeu. Les agents repondent comme un beat parfait, joignable a tout moment. Les retraits sont fluides comme un drop, de temps en temps plus de promos regulieres ajouteraient du rythme. Dans l’ensemble, BassBet Casino est une plateforme qui pulse pour les joueurs en quete d’adrenaline ! Par ailleurs la plateforme est visuellement electrisante, booste le plaisir de jouer. Un atout les tournois reguliers pour la competition, offre des recompenses continues.
bassbetcasinoappfr.com|
VibeCrafterK9zef
24 Oct 25 at 11:41 am
1xbet guncel [url=www.1xbet-giris-10.com/]1xbet guncel[/url] .
1xbet giris_cuka
24 Oct 25 at 11:41 am
https://t.me/s/bs_1xbet/2
https://t.me/s/bs_1xbet/41
24 Oct 25 at 11:41 am
Nice post. I was checking continuously this weblog and I
am impressed! Extremely useful info specially
the remaining phase 🙂 I care for such info much.
I used to be looking for this particular info for a very long time.
Thanks and best of luck.
kra41 at
24 Oct 25 at 11:42 am
1xbet giri? g?ncel [url=https://www.1xbet-4.com]https://www.1xbet-4.com[/url] .
1xbet_jhol
24 Oct 25 at 11:42 am
Je suis totalement illumine par BassBet Casino, c’est une plateforme qui scintille comme un neon. Le catalogue est riche en surprises, offrant des sessions live dynamiques. Boostant votre mise de depart. Le suivi est impeccable, avec une aide precise. Le processus est simple et lumineux, de temps en temps des offres plus genereuses seraient lumineuses. Au final, BassBet Casino offre une experience inoubliable pour les fans de casino en ligne ! A noter l’interface est fluide comme un neon, booste le plaisir de jouer. Un atout les options de paris variees, qui dynamise l’engagement.
https://bassbetcasinopromocodefr.com/|
GlowTuneH7zef
24 Oct 25 at 11:43 am
купить диплом в тюмени [url=https://rudik-diplom14.ru]купить диплом в тюмени[/url] .
Diplomi_otea
24 Oct 25 at 11:43 am
Je suis emerveille par Spinit Casino, ca plonge dans un monde aromatique. Les options sont vastes comme un bouquet, incluant des paris sportifs elegants. Avec des depots instantanes. L’assistance est efficace et professionnelle, avec une aide precise. Les transactions sont fiables, cependant quelques tours gratuits supplementaires seraient bien venus. Pour conclure, Spinit Casino vaut une visite sophistiquee pour les amateurs de sensations elegantes ! Ajoutons que l’interface est fluide comme un parfum, facilite une immersion totale. Un autre atout les paiements securises en crypto, assure des transactions fiables.
https://spinitcasinobonusfr.com/|
EnchantedReelF7zef
24 Oct 25 at 11:44 am
1xbet yeni adresi [url=www.1xbet-giris-7.com]1xbet yeni adresi[/url] .
1xbet giris_kcKn
24 Oct 25 at 11:45 am
https://t.me/s/bs_1xbet/21
https://t.me/s/bs_1xbet/37
24 Oct 25 at 11:47 am
Hello there! I simply want to offer you a huge thumbs up for the excellent information you have
got here on this post. I am returning to your web site for more soon.
Bit GPT App AI Avis
24 Oct 25 at 11:48 am
bahis siteler 1xbet [url=http://1xbet-giris-9.com/]bahis siteler 1xbet[/url] .
1xbet giris_djon
24 Oct 25 at 11:48 am
https://t.me/bs_1xbet/20
https://t.me/bs_1xbet/5
24 Oct 25 at 11:48 am
Публикация предлагает читателю не просто информацию, а инструменты для анализа и саморазвития. Мы стимулируем критическое мышление, предлагая различные точки зрения и призывая к самостоятельному поиску решений.
Посмотреть всё – https://gnpsnalagarh.com/annual-result-day
Charlescep
24 Oct 25 at 11:48 am