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!
На каком сайте сейчас заказать то можно дживик ровный
https://731634fadd7fcad384f668cb44.doorkeeper.jp/
Все будет равно чувак!!!!!!!!
RogerCer
11 Sep 25 at 1:25 am
драгон мани официальный сайт
https://ppms-ra.ru/
11 Sep 25 at 1:28 am
1win бонус за установку приложения [url=www.1win12005.ru]www.1win12005.ru[/url]
1win_aool
11 Sep 25 at 1:28 am
Hey would you mind sharing which blog platform you’re using?
I’m looking to start my own blog in the near future
but I’m having a hard time making a decision between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design seems different
then most blogs and I’m looking for something completely unique.
P.S My apologies for being off-topic but I had to ask!
Zeker Montex
11 Sep 25 at 1:29 am
A person necessarily help to make critically articles I would state.
This is the first time I frequented your website page and thus far?
I amazed with the analysis you made to create this particular put up incredible.
Great job!
Lorvantriel
11 Sep 25 at 1:30 am
слот авиатор [url=https://www.aviator-igra-4.ru]https://www.aviator-igra-4.ru[/url] .
aviator igra_aspr
11 Sep 25 at 1:30 am
fast delivery viagra UK online: viagra discreet delivery UK – viagra discreet delivery UK
Jamesmit
11 Sep 25 at 1:30 am
Book Of Anunnaki online
AndrewSeave
11 Sep 25 at 1:30 am
plane crash game online earn money [url=https://aviator-igra-1.ru/]aviator-igra-1.ru[/url] .
aviator igra_xrOn
11 Sep 25 at 1:32 am
Aw, this was an exceptionally good post. Spending some time and actual effort to create a really good article… but what can I say…
I hesitate a whole lot and don’t manage to get nearly anything done.
RexoralFin
11 Sep 25 at 1:32 am
I’ve been browsing online more than 2 hours today, yet I
never found any interesting article like yours. It is pretty worth enough
for me. In my opinion, if all site owners and bloggers made good content as
you did, the internet will be a lot more useful than ever before.
WertalmPro
11 Sep 25 at 1:33 am
J’adore l’eclat de PlazaRoyal Casino, on dirait un palais de plaisirs. Les options de jeu au casino sont riches et somptueuses, proposant des slots de casino a theme royal. Le service client du casino est digne d’un monarque, avec une aide qui rayonne comme une couronne. Les transactions du casino sont simples comme un edit, mais j’aimerais plus de promotions de casino qui eblouissent. En somme, PlazaRoyal Casino est un joyau pour les fans de casino pour les nobles du casino ! En plus l’interface du casino est fluide et eclatante comme un palais, ce qui rend chaque session de casino encore plus majestueuse.
plaza royal casino bonus|
glimmertoad3zef
11 Sep 25 at 1:33 am
авиатор ставки [url=www.aviator-igra-4.ru/]авиатор ставки[/url] .
aviator igra_brpr
11 Sep 25 at 1:34 am
Valuable info. Fortunate me I found your web site accidentally, and I am stunned why this accident didn’t happened earlier!
I bookmarked it.
LucroX AI
11 Sep 25 at 1:35 am
Ich bin suchtig nach NV Casino, es ist ein Online-Casino, das wie ein Blitz einschlagt. Die Spielauswahl im Casino ist wie ein funkelnder Ozean, mit Casino-Spielen, die fur Kryptowahrungen optimiert sind. Der Casino-Kundenservice ist wie ein Leitstern, sorgt fur sofortigen Casino-Support, der verblufft. Casino-Gewinne kommen wie ein Sturm, aber mehr regelma?ige Casino-Boni waren ein Knaller. Alles in allem ist NV Casino ein Online-Casino, das wie ein Sturm begeistert fur die, die mit Stil im Casino wetten! Nebenbei die Casino-Plattform hat einen Look, der wie ein Blitz funkelt, was jede Casino-Session noch aufregender macht.
mirage hotel and casino las vegas nv|
whimsyfrog3zef
11 Sep 25 at 1:35 am
проект перепланировки жилого помещения [url=https://proekt-pereplanirovki-kvartiry8.ru/]проект перепланировки жилого помещения[/url] .
proekt pereplanirovki kvartiri_mvMl
11 Sep 25 at 1:36 am
aviator игра 1win [url=https://aviator-igra-4.ru/]aviator игра 1win[/url] .
aviator igra_vwpr
11 Sep 25 at 1:37 am
Казино X
Rupertnurne
11 Sep 25 at 1:37 am
зайти в мостбет [url=https://mostbet12001.ru/]зайти в мостбет[/url]
mostbet_zdOr
11 Sep 25 at 1:38 am
Мы изготавливаем дипломы любой профессии по выгодным тарифам. Города продажи дипломов — [url=http://kyc-diplom.com/geography.html/]kyc-diplom.com/geography.html[/url]
Cazrcms
11 Sep 25 at 1:41 am
согласование перепланировки квартиры москва [url=https://www.proekt-pereplanirovki-kvartiry8.ru]согласование перепланировки квартиры москва[/url] .
proekt pereplanirovki kvartiri_zwMl
11 Sep 25 at 1:41 am
Казино ПинАп
Robertcok
11 Sep 25 at 1:42 am
электрокарнизы москва [url=https://elektrokarnizy5.ru/]elektrokarnizy5.ru[/url] .
elektrokarnizi_peol
11 Sep 25 at 1:44 am
https://hub.docker.com/u/candetoxblend
Superar un control sorpresa puede ser estresante. Por eso, se ha creado una alternativa confiable probada en laboratorios.
Su mezcla premium combina minerales, lo que sobrecarga tu organismo y oculta temporalmente los trazas de alcaloides. El resultado: una muestra limpia, lista para entregar tranquilidad.
Lo mas notable es su capacidad inmediata de respuesta. A diferencia de detox irreales, no promete limpiezas magicas, sino una solucion temporal que funciona cuando lo necesitas.
Miles de postulantes ya han comprobado su seguridad. Testimonios reales mencionan resultados exitosos en pruebas preocupacionales.
Si quieres proteger tu futuro, esta formula te ofrece tranquilidad.
JuniorShido
11 Sep 25 at 1:45 am
массовое швейное производство [url=nitkapro.ru]nitkapro.ru[/url] .
shveinoe proizvodstvo_kzea
11 Sep 25 at 1:45 am
проект перепланировки квартиры для согласования цена [url=https://www.proekt-pereplanirovki-kvartiry8.ru]https://www.proekt-pereplanirovki-kvartiry8.ru[/url] .
proekt pereplanirovki kvartiri_vlMl
11 Sep 25 at 1:45 am
скачат 1 win [url=https://www.1win12001.ru]скачат 1 win[/url]
1win_zrPi
11 Sep 25 at 1:46 am
aviator игра 1win авиатор игра [url=http://aviator-igra-4.ru]http://aviator-igra-4.ru[/url] .
aviator igra_jmpr
11 Sep 25 at 1:47 am
dark market list darknet drugs tor drug market [url=https://darkmarketlegion.com/ ]nexus market url [/url]
Robertalima
11 Sep 25 at 1:48 am
как получить скидку на тур Отправьтесь в экзотический Таиланд со скидкой! Наши скидки на туры в Таиланд с отелями – это отличная возможность насладиться прекрасным отдыхом в этой удивительной стране. Белоснежные пляжи, лазурное море и экзотическая природа ждут вас!
VictorWal
11 Sep 25 at 1:49 am
Онлайн-сайт для женщин https://mirlady.kyiv.ua красота, стиль, здоровье, дом и семья. Практичные рекомендации, модные идеи, вдохновение и поддержка. Лучший контент для девушек и женщин любого возраста.
Philipskall
11 Sep 25 at 1:49 am
Thanks , I have just been looking for info about this topic for a while and yours is the greatest
I’ve discovered so far. But, what about the bottom line?
Are you positive concerning the supply?
noteworthy
11 Sep 25 at 1:49 am
ну не хочешь – не бери, кто заставляет то Оо Покупают сотни, а отзывы “с критикой” от единиц. Кстати, 307го нет кажется…
https://wirtube.de/a/rrexuwobyryh/video-channels
Будем дальше работать с этим магазином.
RogerCer
11 Sep 25 at 1:49 am
Aiyah, primary math teaches everyday սses including budgeting,
tһerefore guarantee yoᥙr child masters thаt correctly starting yoսng age.
Hey hey, composed pom ρі рi, mathematics іs among of
tһe leading disciplines іn Junior College, laying groundwork іn Α-Level
calculus.
St. Joseph’s Institution Junior College embodies Lasallian customs, emphasizing faith, service, aand intellectual pursuit.
Integrated programs offer smooth development ԝith focus on bilingualism and innovation. Facilities
ⅼike carrying oᥙt arts centers enhance innovative expression. International
immersions ɑnd гesearch chances broaden perspectives. Graduates аrе thoughtful
achievers, mastering universities аnd careers.
Hwa Chong Institution Junior College іs commemorated foг
itѕ seamless integrated program tһat masterfully integrates extensive academic challenges ᴡith extensive character
advancement, cultivating а brand-new generation ⲟf worldwide scholars and ethical leaders
ᴡho are geared սp to deal ԝith complicated global ρroblems.
The organization boasts fіrst-rate infrastructure, including advanced proving ground, bilingual libraries, аnd development incubators,
ᴡhere extremely qualified faculty guide students tоwards quality in fields ⅼike scientific research, entrepreneurial endeavors, аnd cultural
studies. Trainees ɡet invaluable experiences tһrough comprehensive international exchange
programs, worldwide competitions іn mathematics ɑnd sciences, and collective projects tһat broaden tһeir
horizons and refine theiг analytical ɑnd social skills.
Ᏼy emphasizing innovation tһrough initiatives
lіke student-led startups and innovation workshops, аlong ѡith
service-oriented activities that promote social responsibility,
tһe college constructs durability, adaptability, ɑnd a strong
ethical structure іn its students. Τhe huɡe alumni network оf Hwa
Chong Institution Junior College ߋpens paths tο elite universities and influential professions
around the world, underscoring tһe school’ѕ enduring tradition ⲟf
cultivating intelectual prowess аnd principled management.
Parents, competitive mode activated lah, strong primary math гesults to improved scientific understanding ρlus construction goals.
Օһ man, no matter tһough school iѕ fancy,
mathematics іѕ the make-оr-break discipline tо cultivates poise гegarding numbeгѕ.
Aiyah, primary math teaches everyday ᥙses like money management,
tһus ensure уour kid gеts іt correctly bеginning eɑrly.
Aiyah, primary mathematics teaches real-ԝorld applications including financial planning, ѕo
make ѕure yoᥙr kid grasps thiѕ properly frߋm young.
Eh eh, composed pom рi pi, maths is part in the tοp
disciplines during Junior College, establishing foundation іn Α-Level higher calculations.
Аpаrt bеyond establishment amenities, emphasize οn math for prevent frequent mistakes ⅼike sloppy
mistakes іn tests.
Math trains you tο think critically, а must-have in օur fast-paced ԝorld lah.
Folks, fearful of losing style activated lah, strong primary
math гesults to improved scientific grasp ɑs well as construction dreams.
Αlso visit my site :: junior college math tuition
junior college math tuition
11 Sep 25 at 1:50 am
Онлайн-сайт для женщин https://mirlady.kyiv.ua красота, стиль, здоровье, дом и семья. Практичные рекомендации, модные идеи, вдохновение и поддержка. Лучший контент для девушек и женщин любого возраста.
Philipskall
11 Sep 25 at 1:51 am
Онлайн-сайт для женщин https://mirlady.kyiv.ua красота, стиль, здоровье, дом и семья. Практичные рекомендации, модные идеи, вдохновение и поддержка. Лучший контент для девушек и женщин любого возраста.
Philipskall
11 Sep 25 at 1:53 am
I like the valuable info you provide in your articles.
I will bookmark your weblog and check again here regularly.
I’m quite certain I’ll learn plenty of new stuff right here!
Best of luck for the next!
Davida
11 Sep 25 at 1:54 am
https://vc.ru/id5253792/2197140-pochemu-odni-produkty-prinosyat-milliony-a-drugie-terpyat-ubytki-sekret-uspeshnoi-segmentacii-celevoi-auditorii
Walterspafe
11 Sep 25 at 1:54 am
aviator ставки [url=https://aviator-igra-4.ru/]aviator ставки[/url] .
aviator igra_lrpr
11 Sep 25 at 1:55 am
Женский сайт https://lubimoy.com.ua стиль, уход за собой, психология, материнство, работа и хобби. Актуальные статьи, тренды и экспертные советы. Всё самое важное для гармоничной жизни и успеха.
RichardWrery
11 Sep 25 at 1:56 am
Сайт для женщин https://amideya.com.ua портал о красоте, стиле, здоровье, семье и саморазвитии. Ежедневные статьи, полезные рекомендации и вдохновение для современных девушек и женщин.
Donaldtix
11 Sep 25 at 1:56 am
Женский онлайн-журнал https://gracefullady.kyiv.ua свежие статьи о моде, красоте, здоровье и саморазвитии. Практичные советы, вдохновение и позитив для девушек и женщин любого возраста.
Jasondit
11 Sep 25 at 1:57 am
самолетик казино [url=https://aviator-igra-4.ru/]aviator-igra-4.ru[/url] .
aviator igra_btpr
11 Sep 25 at 1:59 am
Женский сайт https://lubimoy.com.ua стиль, уход за собой, психология, материнство, работа и хобби. Актуальные статьи, тренды и экспертные советы. Всё самое важное для гармоничной жизни и успеха.
RichardWrery
11 Sep 25 at 1:59 am
Сайт для женщин https://amideya.com.ua портал о красоте, стиле, здоровье, семье и саморазвитии. Ежедневные статьи, полезные рекомендации и вдохновение для современных девушек и женщин.
Donaldtix
11 Sep 25 at 1:59 am
Женский онлайн-журнал https://gracefullady.kyiv.ua свежие статьи о моде, красоте, здоровье и саморазвитии. Практичные советы, вдохновение и позитив для девушек и женщин любого возраста.
Jasondit
11 Sep 25 at 2:00 am
Женский сайт https://lubimoy.com.ua стиль, уход за собой, психология, материнство, работа и хобби. Актуальные статьи, тренды и экспертные советы. Всё самое важное для гармоничной жизни и успеха.
RichardWrery
11 Sep 25 at 2:00 am
Сайт для женщин https://amideya.com.ua портал о красоте, стиле, здоровье, семье и саморазвитии. Ежедневные статьи, полезные рекомендации и вдохновение для современных девушек и женщин.
Donaldtix
11 Sep 25 at 2:01 am
проект после перепланировки [url=proekt-pereplanirovki-kvartiry8.ru]proekt-pereplanirovki-kvartiry8.ru[/url] .
proekt pereplanirovki kvartiri_xcMl
11 Sep 25 at 2:01 am
My brother suggested I might like this web site. He used to be totally right.
This put up truly made my day. You cann’t imagine just how a lot time I had spent for
this information! Thank you!
Full Report
11 Sep 25 at 2:01 am