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!
kraken darknet
kraken РФ
Henryamerb
28 Oct 25 at 11:58 pm
комплексное продвижение сайтов москва [url=optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru]комплексное продвижение сайтов москва[/url] .
optimizaciya i seo prodvijenie saitov moskva_ibPi
28 Oct 25 at 11:59 pm
cd player alarm [url=https://www.alarm-radio-clocks.com]https://www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_voOa
28 Oct 25 at 11:59 pm
Very soon this web page will be famous amid all blog visitors, due
to it’s fastidious articles or reviews
Arbivex Erfahrungen
28 Oct 25 at 11:59 pm
устранение протечек в подвале [url=www.gidroizolyaciya-cena-8.ru/]устранение протечек в подвале[/url] .
gidroizolyaciya cena_jgKn
28 Oct 25 at 11:59 pm
маркетинг в интернете блог [url=https://statyi-o-marketinge7.ru]https://statyi-o-marketinge7.ru[/url] .
stati o marketinge _kykl
29 Oct 25 at 12:00 am
мелбет [url=www.melbetofficialsite.ru/]мелбет[/url] .
bk melbet_fuEa
29 Oct 25 at 12:01 am
услуги гидроизоляции подвала [url=https://www.gidroizolyaciya-podvala-cena.ru]https://www.gidroizolyaciya-podvala-cena.ru[/url] .
gidroizolyaciya podvala cena_tmKt
29 Oct 25 at 12:01 am
seo аудит веб сайта [url=https://www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru]seo аудит веб сайта[/url] .
optimizaciya i seo prodvijenie saitov moskva_xnPi
29 Oct 25 at 12:02 am
Oh, mathematics acts ⅼike the base block іn primary learning,
assisting children іn spatial reasoning to building routes.
Oh dear, minus strong maths іn Junior College, no matter tօp establishment children mіght falter at
secondary algebra, tһuѕ build this promрtly leh.
Anglo-Chinese Junior College stands аs a beacon of balanced
education, blending strenuous academics ѡith a
nurturing Christian principles tһat motivates moral integrity
ɑnd individual development. Тhe college’ѕ ѕtate-of-the-art facilities and skilled professors support outstanding performance іn ƅoth arts and sciences, wіth
trainees often attaining ttop awards. Througһ іtѕ focus on sports аnd performing arts, trainees establish discipline, camaraderie, аnd a passion for excellence
beуond the classroom. International collaborations and exchange chances
enhance tһe learning experience, fostering worldwide awareness аnd cultural gratitude.
Alumni flourish іn varied fields, testimony to tһе college’s role in shaping principled leaders ɑll set to contribute favorably tⲟ society.
St. Joseph’ѕ Institution Junior College upholds treasured Lasallian traditions оf faith, service, and
intellectual curiosity, developing ɑn empowering environment wheгe trainees pursue understanding
ԝith passion and dedicate tһemselves tߋ uplifting otһers
thгough thoughtful actions. Ꭲhе incorporated program ensures а fluid development
frоm secondary to pre-university levels, ԝith a concentrate on bilingual proficiency аnd innovative curricula supported Ƅy facilities ⅼike state-of-thе-art carrying ⲟut arts centers and science
research study labs that motivate imaginative ɑnd analytical excellence.
Global immersion experiences, consisting ⲟf worldwide service trips ɑnd cultural exchange programs,
widen students’ horizons, enhance linguistic skills, аnd
cultivate ɑ deep appreciation fοr diverse worldviews.
Opportunities f᧐r innovative research, leadership functions іn student companies, аnd mentorship from accomplished faculty
develop confidence, vital thinking, аnd a commitment to
long-lasting learning. Graduates ɑrе understood for their empathy and higһ accomplishments, protecting рlaces in prominent universities
ɑnd standing out in professions tһat line up with tһe college’ѕ
values of service and intellectual rigor.
Ⅾon’t take lightly lah, link a reputable Junior College alongside
mathematics excellence fⲟr guarantee superior
A Levels marks ɑnd effortless chаnges.
Parents, worry ɑbout the disparity hor, mathematics foundation proves critical аt
Junior College to comprehending іnformation, crucial f᧐r today’ѕ online market.
Listen ᥙp, Singapore folks, mathematics іs perhaps the mߋst essential primary
topic, fostering imagination throuցh problem-solving to groundbreaking careers.
Wah lao, еvеn whetһer establishment rekains
hіgh-end, math serves аs the make-or-break topic fⲟr building poise witһ calculations.
Aiyah, primary math educates everyday applications liкe budgeting, tһus ensure yօur child ցets it correctly ƅeginning earⅼʏ.
Withⲟut Math proficiency, options fοr economics majors shrink dramatically.
Ⅾon’t take lightly lah, pair a gooɗ Junior College witһ
math proficiency іn order to guarantee һigh А Levels resuⅼts аs weⅼl as effortless сhanges.
Look ɑt my web site secondary school
secondary school
29 Oct 25 at 12:03 am
кракен обмен
кракен даркнет маркет
Henryamerb
29 Oct 25 at 12:03 am
аудит продвижения сайта [url=https://www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]аудит продвижения сайта[/url] .
optimizaciya i seo prodvijenie saitov moskva_dpel
29 Oct 25 at 12:04 am
купить колпак для курения
купить колпак для курения
29 Oct 25 at 12:07 am
руководства по seo [url=http://statyi-o-marketinge6.ru/]руководства по seo[/url] .
stati o marketinge _bmkn
29 Oct 25 at 12:07 am
Greetings! I’ve been following your website for some
time now and finally got the bravery to go ahead and give you
a shout out from Kingwood Tx! Just wanted to say keep up the excellent
job!
Stokes Professionals Inc.
29 Oct 25 at 12:08 am
seo partner [url=https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru/]optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru[/url] .
optimizaciya i seo prodvijenie saitov moskva_eeel
29 Oct 25 at 12:09 am
торкретирование цена [url=http://torkretirovanie-1.ru/]торкретирование цена[/url] .
torkretirovanie_yken
29 Oct 25 at 12:09 am
When I initially left a comment I seem to have clicked on the
-Notify me when new comments are added- checkbox and now each time
a comment is added I receive 4 emails with the same comment.
Perhaps there is a way you can remove me from that service?
Appreciate it!
smart dog collar test
29 Oct 25 at 12:09 am
kraken вход
kraken РФ
Henryamerb
29 Oct 25 at 12:09 am
top clock radio [url=https://alarm-radio-clocks.com]https://alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_cyOa
29 Oct 25 at 12:11 am
[url=https://ocean-finance.pl/leasing/maszyny/]https://ocean-finance.pl/leasing/maszyny/[/url] can take up to placement, is quite accessible . Just click on picture of the game where you desire play, and find between demo mode and the game for real funds.
EdithLag
29 Oct 25 at 12:11 am
seo partners [url=https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru]https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru[/url] .
optimizaciya i seo prodvijenie saitov moskva_zaPi
29 Oct 25 at 12:11 am
comprare medicinali online legali: Spedra prezzo basso Italia – FarmaciaViva
Jamesaleds
29 Oct 25 at 12:11 am
Hi there! I know this is somewhat off topic but I was wondering if
you knew where I could locate a captcha plugin for my comment form?
I’m using the same blog platform as yours and I’m having trouble finding one?
Thanks a lot!
تعمیر ماشین لباسشویی بلومبرگ
29 Oct 25 at 12:12 am
гидроизоляция цена за рулон [url=www.gidroizolyaciya-cena-8.ru/]гидроизоляция цена за рулон[/url] .
gidroizolyaciya cena_glKn
29 Oct 25 at 12:12 am
торкретирование стен цена [url=https://torkretirovanie-1.ru/]https://torkretirovanie-1.ru/[/url] .
torkretirovanie_aaen
29 Oct 25 at 12:13 am
Operation Game Canada: A classic, fun-filled board game where players test their precision by removing ailments from the patient without triggering the buzzer: Operation game tips and tricks
GabrielLyday
29 Oct 25 at 12:16 am
https://t.me/s/Official_mellstroy_casino/30
Calvindreli
29 Oct 25 at 12:17 am
продвижения сайта в google [url=www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru/]продвижения сайта в google[/url] .
optimizaciya i seo prodvijenie saitov moskva_jiel
29 Oct 25 at 12:18 am
kraken vk5
kraken 2025
Henryamerb
29 Oct 25 at 12:18 am
гидроизоляция подвала под ключ [url=www.gidroizolyaciya-podvala-cena.ru]www.gidroizolyaciya-podvala-cena.ru[/url] .
gidroizolyaciya podvala cena_ecKt
29 Oct 25 at 12:19 am
https://t.me/s/Official_mellstroy_casino/15
Calvindreli
29 Oct 25 at 12:19 am
best cd alarm clock radio [url=https://alarm-radio-clocks.com/]https://alarm-radio-clocks.com/[/url] .
Cd Player Radio Alarm Clocks_zvOa
29 Oct 25 at 12:20 am
magnificent issues altogether, you simply won a new reader.
What might you recommend in regards to your submit that you made some days ago?
Any positive?
easy dog trick guide
29 Oct 25 at 12:21 am
мелбет онлайн [url=https://melbetofficialsite.ru]мелбет онлайн[/url] .
bk melbet_bqEa
29 Oct 25 at 12:22 am
кракен вход
kraken qr code
Henryamerb
29 Oct 25 at 12:23 am
торкретирование стен цена за м2 [url=https://torkretirovanie-1.ru]https://torkretirovanie-1.ru[/url] .
torkretirovanie_snen
29 Oct 25 at 12:24 am
Одним из главных преимуществ автоматических жалюзи является их способность регулировать уровень света в помещении. С помощью таких жалюзи можно контролировать попадающий свет в зависимости от времени суток. Это особенно важно для людей, работающих на удаленке. Это обеспечивает комфортные условия как для работы, так и для отдыха.
[url=https://avtomaticheskie-zhalyuzi-s-privodom.ru/]электрические жалюзи на окна внутренние Прокарниз[/url] обеспечивают удобство и стиль в вашем доме, позволяя управлять светом одним нажатием кнопки.
Автоматические жалюзи на окна с электроприводом становятся все более популярными. Эти изделия обеспечивают высокий уровень комфорта и функциональности для любого интерьера. Такие жалюзи могут управляться с помощью пульта дистанционного управления или смартфона. Это значительно упрощает процесс их использования.
Еще одним важным аспектом является экономия энергии. С правильной эксплуатацией этих жалюзи можно значительно уменьшить расходы на обогрев и кондиционирование. С автоматическими жалюзи будет проще контролировать температуру в помещении. Таким образом, они не только удобны, но и экономически оправданы.
Установка автоматических жалюзи может проводиться как опытными мастерами, так и самостоятельно. Вам решать, устанавливать ли жалюзи самостоятельно или обратиться к специалистам. Для самостоятельной установки необходимо точно придерживаться рекомендаций производителей. Следуя инструкциям, вы сможете избежать ошибок и гарантировать корректное функционирование системы.
электрожалюзи для квартиры Prokarniz
29 Oct 25 at 12:24 am
I want to to thank you for this excellent read!! I certainly loved every bit of it.
I have you bookmarked to look at new things you post…
turkey visa for australian
29 Oct 25 at 12:24 am
seo network [url=www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]seo network[/url] .
optimizaciya i seo prodvijenie saitov moskva_rsel
29 Oct 25 at 12:25 am
Hey There. I found your blog using msn. This is an extremely well written article.
I will make sure to bookmark it and come back to read more of your
useful information. Thanks for the post. I’ll certainly return.
Composite Veneers thailand
29 Oct 25 at 12:27 am
купить диплом в каспийске [url=www.rudik-diplom14.ru/]www.rudik-diplom14.ru/[/url] .
Diplomi_jmea
29 Oct 25 at 12:28 am
торкретирование москва [url=https://www.torkretirovanie-1.ru]https://www.torkretirovanie-1.ru[/url] .
torkretirovanie_sken
29 Oct 25 at 12:29 am
kraken 2025
кракен Россия
Henryamerb
29 Oct 25 at 12:29 am
Valuable info. Lucky me I discovered your web site
by accident, and I am surprised why this twist of fate didn’t took place earlier!
I bookmarked it.
Travel Agencies In Dubai From USA
29 Oct 25 at 12:30 am
hd tabletop radio [url=http://alarm-radio-clocks.com/]http://alarm-radio-clocks.com/[/url] .
Cd Player Radio Alarm Clocks_baOa
29 Oct 25 at 12:30 am
https://t.me/s/Official_mellstroy_casino/53
Calvindreli
29 Oct 25 at 12:30 am
Расташоп
Расташоп
29 Oct 25 at 12:30 am
технического аудита сайта [url=http://optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru/]http://optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru/[/url] .
optimizaciya i seo prodvijenie saitov moskva_etel
29 Oct 25 at 12:32 am
компании занимающиеся продвижением сайтов [url=https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru]компании занимающиеся продвижением сайтов[/url] .
optimizaciya i seo prodvijenie saitov moskva_rePi
29 Oct 25 at 12:33 am