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!
I’m really enjoying the theme/design of your weblog.
Do you ever run into any browser compatibility
issues? A small number of my blog audience have complained about
my blog not working correctly in Explorer but looks great in Chrome.
Do you have any solutions to help fix this issue?
سایت تاییدیه و سوابق تحصیلی دیپلم
18 Oct 25 at 8:30 pm
Alas, ѡithout robust maths аt Junior College, no matter leading institution children mіght
falter at hіgh school equations, tһerefore develop
this immediately leh.
Eunoia Junior College represents modern innovation іn education, wіth its һigh-rise campus
integrating neighborhood spaces fοr collaborative knowing
ɑnd development.Τhe college’ѕ emphasis on stunning thinking fosters intellectual іnterest and goodwill,
supported Ƅy vibrant programs іn arts, sciences,
and management. State-оf-the-art centers, consisting of carrying
օut arts locations, ɑllow students tο check oսt enthusiasms ɑnd establish skills holistically.
Partnerships ԝith esteemed institutions supply improving opportunities fοr reseaгch and international exposure.
Students emerge аѕ thoughtful leaders, ready tо contrikbute positively tⲟ ɑ diverse world.
Dunman High School Junior College differentiates іtself through its remarkable multilingual education structure,
ѡhich expertly merges Eastern cultural knowledge ԝith Western analytical techniques, supporting students іnto
flexible, culturally delicate thinkers ᴡho are proficient at bridging diverse
viewpoints іn a globalized world. Thе school’s incorporated six-year program
mаkes ѕure a smooth and enriched shift, including specialized curricula іn STEM fields ѡith access tߋ advanced lab
аnd in humanities with immersive language immersion modules,
ɑll designed to promote intellectual depth ɑnd innovative analytical.
Ιn a nurturing and unified school environment, students actively participate іn management
functions, innovative endeavors ⅼike debate ϲlubs
and cultural celebrations, ɑnd neighborhood jobs tһat
improve their social awareness аnd collaborative skills.
Ƭһе college’ѕ robust international immersion initiatives, consisting ᧐f
trainee exchanges witһ partner schools in Asia ɑnd
Europe, in aɗdition to global competitors, supply
hands-ⲟn experiences tһat sharpen cross-cultural competencies аnd prepare students fоr growing in multicultural settings.
Ꮤith a constant record of impressive scholastic efficiency, Dunman Ηigh School Junior College’ѕ
graduates protected placements іn premier universities worldwide, exhibiting tһe institution’s commitment t᧐ promoting scholastic
rigor, individual quality, аnd a lifelong enthusiasm fоr learning.
Αpart beyond school resources, emphasize ᧐n mathematics in order tօ stop common pitfalls including sloppy mistakes ԁuring tests.
Folks, kiasu approach оn lah, strong primary maths guides іn superior STEM comprehension plսs tech dreams.
Ꭺvoid play play lah, pair а reputable Junior College ᴡith mathematics excellence іn order to assure superior A
Levels scores ɑnd effortless shifts.
Alas, lacking robust math ɗuring Junior College, no matter tоp school kids could struggle in hіgh school equations, tһus develop it now
leh.
Practicing Math papers religiously helps build resilience fօr real-world problem-solving.
Oh no, primary maths educates everyday implementations ѕuch as financial planning, therefore guarantee yοur child gets tһat correctly fгom y᧐ung age.
junior college
18 Oct 25 at 8:31 pm
I loved as much as you will receive carried out right here.
The sketch is attractive, your authored material stylish.
nonetheless, you command get got an shakiness over that you wish be delivering the
following. unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you shield
this increase.
Rolex Replica,Replica Watch
18 Oct 25 at 8:34 pm
где заказать проект перепланировки квартиры [url=http://proekt-pereplanirovki-kvartiry16.ru]http://proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_ndMl
18 Oct 25 at 8:35 pm
сколько стоит узаконить перепланировку в квартире в москве [url=https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru]https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_onet
18 Oct 25 at 8:37 pm
перепланировка цена [url=https://proekt-pereplanirovki-kvartiry17.ru]перепланировка цена[/url] .
proekt pereplanirovki kvartiri_rnml
18 Oct 25 at 8:37 pm
согласование перепланировки квартиры [url=https://soglasovanie-pereplanirovki-kvartiry14.ru/]soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _yoEl
18 Oct 25 at 8:37 pm
Если вы ищете надежную клинику для вывода из запоя, обратитесь в «Детокс» в Краснодаре. Услуга вызова нарколога на дом доступна круглосуточно. Врачи приедут к вам в течение 1–2 часов и окажут необходимую помощь.
Получить больше информации – [url=https://narkolog-na-dom-krasnodar28.ru/]нарколог на дом круглосуточно цены краснодар[/url]
JosephNAINI
18 Oct 25 at 8:38 pm
classyhomegoods – Excellent customer service, got quick help with an order question.
Sheena Broccolo
18 Oct 25 at 8:38 pm
мелбет войти [url=http://melbetbonusy.ru]http://melbetbonusy.ru[/url] .
melbet_brOi
18 Oct 25 at 8:39 pm
регистрация перепланировки [url=https://soglasovanie-pereplanirovki-kvartiry11.ru/]soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _akMi
18 Oct 25 at 8:39 pm
сколько стоит проект перепланировки квартиры [url=http://proekt-pereplanirovki-kvartiry17.ru]сколько стоит проект перепланировки квартиры[/url] .
proekt pereplanirovki kvartiri_uvml
18 Oct 25 at 8:40 pm
согласование проекта перепланировки квартиры [url=http://www.soglasovanie-pereplanirovki-kvartiry14.ru]http://www.soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _zhEl
18 Oct 25 at 8:41 pm
перепланировка согласование [url=https://soglasovanie-pereplanirovki-kvartiry4.ru]перепланировка согласование[/url] .
soglasovanie pereplanirovki kvartiri _leOr
18 Oct 25 at 8:41 pm
В клинике в Самаре устраняют симптомы интоксикации, оказывают поддержку организму и помогают восстановиться после тяжёлых запоев.
Получить больше информации – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]стационар вывод из запоя[/url]
GilbertCoeby
18 Oct 25 at 8:41 pm
Hi, after reading this remarkable paragraph i am also glad to share my experience here with
colleagues.
https://play-chumbacasino.com
18 Oct 25 at 8:44 pm
услуги по согласованию перепланировки квартиры [url=www.soglasovanie-pereplanirovki-kvartiry3.ru]www.soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _oqPi
18 Oct 25 at 8:44 pm
купить диплом в мытищах [url=rudik-diplom6.ru]купить диплом в мытищах[/url] .
Diplomi_dtKr
18 Oct 25 at 8:46 pm
перепланировка офиса [url=www.soglasovanie-pereplanirovki-kvartiry11.ru/]www.soglasovanie-pereplanirovki-kvartiry11.ru/[/url] .
soglasovanie pereplanirovki kvartiri _umMi
18 Oct 25 at 8:46 pm
сколько стоит узаконить перепланировку квартиры [url=https://zakazat-proekt-pereplanirovki-kvartiry11.ru/]https://zakazat-proekt-pereplanirovki-kvartiry11.ru/[/url] .
zakazat proekt pereplanirovki kvartiri_aeet
18 Oct 25 at 8:47 pm
digital stream
MichaelSig
18 Oct 25 at 8:47 pm
услуги по согласованию перепланировки [url=https://soglasovanie-pereplanirovki-kvartiry4.ru/]услуги по согласованию перепланировки[/url] .
soglasovanie pereplanirovki kvartiri _wcOr
18 Oct 25 at 8:47 pm
With simulated exams with encouraging comments, OMT constructs durability іn mathematics, fostering love
ɑnd motivation for Singapore students’ examination triumphs.
Founded іn 2013 bү Мr. Justin Tan, OMT Math Tuition һas helped
mɑny trainees ace exams like PSLE, O-Levels, and A-Levels ѡith tested ⲣroblem-solving methods.
Offered tһɑt mathematics plays ɑ pivotal function іn Singapore’s financial development ɑnd progress, buying specialized math
tuition equips trainees ԝith the analytical abilities required tߋ grow
in a competitive landscape.
primary school tuition іs crucial fօr PSLE as it useѕ restorative assistance fоr topics ⅼike wһole numbeгs and
measurements, guaranteeing no fundamental weaknesses
continue.
Secondary math tuition lays а strong foundation for post-О Level researches, ѕuch as A Levels оr polytechnic courses, by succeeding іn fundamental subjects.
Tuition ѕhows mistake analysis techniques, assisting junior university
student stay сlear of usual mistakes іn A Level computations аnd proofs.
OMT’ѕ one-of-a-kіnd mathematics program matches tһe MOE educational program ƅy including exclusive study thаt use mathematics to
real Singaporean contexts.
Professional ideas іn videos offer shortcuts lah, helping you
fix questions faster and rack ᥙp a lot more іn tests.
Tuition programs track progress meticulously, motivating Singapore pupils ᴡith visible renovations Ƅring abojt exam objectives.
Feel free tⲟ surf tо my website: Kaizenare math Tuition
Kaizenare math Tuition
18 Oct 25 at 8:48 pm
куплю диплом младшей медсестры [url=frei-diplom14.ru]frei-diplom14.ru[/url] .
Diplomi_unoi
18 Oct 25 at 8:48 pm
сколько стоит разрешение на перепланировку квартиры [url=https://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/]https://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_vhPt
18 Oct 25 at 8:51 pm
successnetworkgroup – The articles were relevant and practical, not just theory—very nice.
Gladys Schlegel
18 Oct 25 at 8:51 pm
цена ремонта с перепланировкой [url=http://www.zakazat-proekt-pereplanirovki-kvartiry11.ru]http://www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_gfet
18 Oct 25 at 8:53 pm
помощь в согласовании перепланировки квартиры [url=https://www.soglasovanie-pereplanirovki-kvartiry11.ru]https://www.soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _ecMi
18 Oct 25 at 8:54 pm
стоимость перепланировки квартиры [url=proekt-pereplanirovki-kvartiry17.ru]стоимость перепланировки квартиры[/url] .
proekt pereplanirovki kvartiri_scml
18 Oct 25 at 8:54 pm
план перепланировки [url=www.proekt-pereplanirovki-kvartiry16.ru]www.proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_kvMl
18 Oct 25 at 8:54 pm
стоимость согласования перепланировки в москве [url=stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_twPt
18 Oct 25 at 8:55 pm
компании занимащиеся офицально перепланировками квартир [url=https://soglasovanie-pereplanirovki-kvartiry14.ru/]https://soglasovanie-pereplanirovki-kvartiry14.ru/[/url] .
soglasovanie pereplanirovki kvartiri _myEl
18 Oct 25 at 8:56 pm
Выход есть: эффективные способы преодоления зависимости в Саратове, проверенные клиники и советы специалистов — читайте на Noprost. Ознакомиться с деталями – http://chesskomi.borda.ru/?1-9-0-00000237-000-0-0-1756816219
Crystaldum
18 Oct 25 at 8:56 pm
mostbet uz [url=http://mostbet4182.ru]http://mostbet4182.ru[/url]
mostbet_uz_nikt
18 Oct 25 at 8:56 pm
услуги по согласованию перепланировки квартиры [url=https://soglasovanie-pereplanirovki-kvartiry11.ru]https://soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _efMi
18 Oct 25 at 8:57 pm
мелбет фрибет за регистрацию условия [url=https://melbetbonusy.ru/]мелбет фрибет за регистрацию условия[/url] .
melbet_ljOi
18 Oct 25 at 8:58 pm
afrik foot pronostic info foot africain
parifoot-917
18 Oct 25 at 8:59 pm
We stumbled over here from a different web address and thought
I might as well check things out. I like what I see so now i’m following you.
Look forward to looking into your web page again.
https://ispidercyber.com
18 Oct 25 at 9:00 pm
В автомобиле находятся:
Получить больше информации – https://narkologicheskaya-klinika-rostov13.ru/psikhiatricheskaya-narkologicheskaya-klinika-v-rostove/
JosephNoirl
18 Oct 25 at 9:02 pm
Да, действительно. Это было и со мной. Давайте обсудим этот вопрос. Здесь или в PM.
Рейтинг магазин спеллсмелл отзывы составляет 4.8 из пяти на веб-ресурсе irecommend, [url=https://www.google.com/storepages?q=spellsmell.ru&c=RU]https://www.google.com/storepages?q=spellsmell.ru&c=RU[/url] которые удостоверяет высочайшем уровне удовлетворенности клиентов.
Britneyscuth
18 Oct 25 at 9:04 pm
где сделать проект перепланировки [url=https://proekt-pereplanirovki-kvartiry16.ru/]proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_jrMl
18 Oct 25 at 9:06 pm
по согласованию [url=http://www.soglasovanie-pereplanirovki-kvartiry3.ru]http://www.soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _cyPi
18 Oct 25 at 9:07 pm
согласовать перепланировку квартиры [url=www.soglasovanie-pereplanirovki-kvartiry4.ru]согласовать перепланировку квартиры[/url] .
soglasovanie pereplanirovki kvartiri _fxOr
18 Oct 25 at 9:08 pm
по согласованию [url=http://soglasovanie-pereplanirovki-kvartiry11.ru]http://soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _xsMi
18 Oct 25 at 9:08 pm
https://potenzvital.shop/# Cialis Preisvergleich Deutschland
LarryArrix
18 Oct 25 at 9:09 pm
согласование перепланировки квартиры цена [url=www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/]www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_qoPt
18 Oct 25 at 9:09 pm
диплом медсестры с аккредитацией купить [url=http://frei-diplom14.ru/]диплом медсестры с аккредитацией купить[/url] .
Diplomi_bcoi
18 Oct 25 at 9:11 pm
сколько стоит перепланировка квартиры в москве [url=www.zakazat-proekt-pereplanirovki-kvartiry11.ru]www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_pxet
18 Oct 25 at 9:11 pm
I am not sure where you are getting your information, but great topic.
I needs to spend some time learning more or understanding more.
Thanks for great info I was looking for this information for my mission.
options platform MEXQuick
18 Oct 25 at 9:12 pm
мелбет букмекерская контора [url=http://melbetbonusy.ru]мелбет букмекерская контора[/url] .
melbet_yzOi
18 Oct 25 at 9:13 pm