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!
Click to learn more: https://www.europneus.es
Davidbedly
25 Oct 25 at 3:28 pm
Читайте больше на сайте: https://actual-cosmetology.ru
WalterRok
25 Oct 25 at 3:28 pm
В кафе тараканы? Вызовите уничтожение тараканов холодным туманом!
дезинфекция медицинских учреждений
KennethceM
25 Oct 25 at 3:29 pm
Then he desired to beleft in private with a certain clergyman,who regulated the concerns ofhis soul,ラブドール 無 修正
ラブドール
25 Oct 25 at 3:29 pm
Нужна уничтожение клопов в общежитии с гарантией, посоветуйте компанию.
уничтожение клопов горячим туманом
KennethceM
25 Oct 25 at 3:30 pm
code promo 1xbet pour l’inscription More specific searches include “code promo 1xBet valide” and “code promo 1xBet 130€,” demonstrating a need for verified codes offering substantial bonuses. “Code promotionnel 1xBet pour nouveaux utilisateurs” is a common inquiry, reflecting the importance of welcome bonuses. Beyond general bonuses: some seek a “1xbet code promo tours gratuits.”
Ronaldjocum
25 Oct 25 at 3:30 pm
Вызвать уничтожение тараканов горячим туманом на дом, кто знает номер?
обработка от клопов
KennethceM
25 Oct 25 at 3:31 pm
For latest information you have to go to see world-wide-web and
on world-wide-web I found this website as a most excellent web site for most up-to-date updates.
fastest payout online casinos
25 Oct 25 at 3:32 pm
Inevitably, OMT’ѕ extensive services weave happiness іnto mathematics education аnd learning,
helping trainees faⅼl deeply crazy аnd rise іn theіr exams.
Oρen your child’s completе capacity in mathematics ԝith OMT
Math Tuition’ѕ expert-led classes, tailored
tߋ Singapore’s MOE curriculum foг primary, secondary,
and JC students.
Іn Singapore’s rigorous education ѕystem, where mathematics is mandatory and takes in аrօund 1600
hours of curriculum tіme in primary and secondary schools, math tuition Ƅecomes іmportant to heⅼp trainees copnstruct а strong structure fⲟr lifelong success.
Ꮤith PSLE math contributing ѕubstantially to gеneral ratings, tuition offers extra resources ⅼike model responses fоr pattern acknowledgment and algebraic thinking.
Ԝith tһe O Level mathematics syllabus ѕometimes evolving, tuition maintains pupils upgraded ᧐n modifications, guaranteeing tһey
are well-prepared foг existing formats.
Tuition рrovides аpproaches foг time management duгing
the prolonged A Level mathematics examinations,
allowing trainees tο allocate initiatives successfulⅼy ɑcross areas.
OMTsticks oout ѡith its curriculum mɑde to support MOE’s Ƅy including mindfulness
techniques tο reduce mathematics stress аnd anxiety dᥙring studies.
OMT’s system tracks yoᥙr improvement in tіme sia,
motivating you tо intend greater in mathematics qualities.
Math tuition grows willpower, assisting Singapore pupils tackle marathon examination sessions ԝith sustained emphasis.
mу web blog – Maths Ηome Tuition In Bangalore – Grok.Com,
Grok.Com
25 Oct 25 at 3:32 pm
купить диплом техникума в красноярске [url=https://www.frei-diplom8.ru]купить диплом техникума в красноярске[/url] .
Diplomi_gosr
25 Oct 25 at 3:33 pm
mostbet официальный сайт [url=mostbet12031.ru]mostbet12031.ru[/url]
mostbet_kg_uqMa
25 Oct 25 at 3:33 pm
Нужна обработка от клопов с гарантией для автомобиля, посоветуйте.
уничтожение грызунов
KennethceM
25 Oct 25 at 3:34 pm
findwhatyoulove.shop – Overall a positive impression; user-friendly and credible website.
Emelina Friedli
25 Oct 25 at 3:35 pm
После санэпидемстанция цены дом безопасный для детей.
дезинфекция автомобиля после умершего
KennethceM
25 Oct 25 at 3:36 pm
«УралДетокс Центр» выстраивает выездную помощь так, чтобы вывести из запоя безопасно, деликатно и без лишних стрессов. Наша выездная бригада приезжает с портативным оборудованием, запускает персонализированную инфузионную терапию, контролирует витальные показатели и сопровождает пациента до стабилизации состояния. Мы не используем «универсальные коктейли» — каждый компонент подбирается под текущие симптомы и сопутствующие заболевания, а эффективность оценивается по заранее оговорённым маркерам: частота пульса, артериальное давление, выраженность тремора, тошнота, сон и дневная ясность.
Детальнее – [url=https://vyvod-iz-zapoya-pervouralsk0.ru/]вывод из запоя вызов на дом[/url]
Curtiscleva
25 Oct 25 at 3:36 pm
startsomethinggreat.shop – The visuals are inviting and the interface feels smooth.
Rayna Levell
25 Oct 25 at 3:36 pm
кракен тор
kraken tor
JamesDaync
25 Oct 25 at 3:37 pm
Explore Riyo Gems, a leading 925 sterling
silver jewelry producer in Jaipur, India. We specialize in eco-friendly handmade gemstone jewelry, personalized creations,
and wholesale gemstone supply. Partner with our trusted factory for finest silver, semi-precious, and loose gemstone jewelry production.
Silver Gemstones Jewelry
25 Oct 25 at 3:39 pm
theperfectgiftshop.com – The minimal design helps focus on the products without distraction.
Demetrius Booton
25 Oct 25 at 3:39 pm
bahis sitesi 1xbet [url=http://1xbet-15.com]bahis sitesi 1xbet[/url] .
1xbet_nppl
25 Oct 25 at 3:42 pm
1xbet ?yelik [url=https://1xbet-10.com]https://1xbet-10.com[/url] .
1xbet_lfea
25 Oct 25 at 3:42 pm
Ресторан чистый после дезинсекция предприятий.
дезинсекция цена
KennethceM
25 Oct 25 at 3:43 pm
Hurrah, that’s what I was searching for, what a material!
present here at this web site, thanks admin of this website.
казино вулкан24 отзывы
25 Oct 25 at 3:43 pm
купить диплом вуза с реестром [url=https://www.frei-diplom3.ru]купить диплом вуза с реестром[/url] .
Diplomi_sfKt
25 Oct 25 at 3:43 pm
https://confiafarmacia.shop/# Viagra sin prescripcion medica
Hermanereli
25 Oct 25 at 3:43 pm
можно ли купить легальный диплом [url=http://frei-diplom2.ru/]http://frei-diplom2.ru/[/url] .
Diplomi_puEa
25 Oct 25 at 3:44 pm
shopandsmilealways.shop – Navigation seems intuitive; I found the main sections easily.
Sheldon Walson
25 Oct 25 at 3:46 pm
мостбет вход через соцсети [url=http://mostbet12031.ru/]http://mostbet12031.ru/[/url]
mostbet_kg_bzMa
25 Oct 25 at 3:47 pm
xbet giri? [url=www.1xbet-13.com/]www.1xbet-13.com/[/url] .
1xbet_zwKa
25 Oct 25 at 3:49 pm
Hello, just wanted to tell you, I loved this blog
post. It was practical. Keep on posting!
Spot Exelon Xp Reseña
25 Oct 25 at 3:51 pm
This piece of writing is actually a pleasant one it helps new internet people,
who are wishing in favor of blogging.
Amazon Fulfilment Services
25 Oct 25 at 3:51 pm
Если дома действительно шумно (ремонт, маленькие дети, вечерние гости) или состояние нестабильно, предложим короткое наблюдение в клинике: отдельный вход, «тихий коридор», камерные посты, затем — возвращение домой и продолжение амбулаторного маршрута. Важен не формат, а предсказуемый результат: степень облегчения должна соответствовать целям этапа, а не множеству случайных факторов среды.
Исследовать вопрос подробнее – http://vyvod-iz-zapoya-nizhnij-tagil0.ru
ClaudeTwilm
25 Oct 25 at 3:52 pm
each time i used to read smaller articles or reviews which as
well clear their motive, and that is also happening with this article which I am
reading at this place.
web site
25 Oct 25 at 3:52 pm
simplybestchoice.shop – Overall a positive impression; user-friendly and credible website.
Cathrine Shorts
25 Oct 25 at 3:53 pm
1xbet ?yelik [url=https://1xbet-12.com/]1xbet-12.com[/url] .
1xbet_gySr
25 Oct 25 at 3:53 pm
купить легальный диплом техникума [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_ojea
25 Oct 25 at 3:54 pm
Discover exceptional gaming at Playamo casino with more than 3,000 top-quality slots, classic games, and live casino games from renowned software companies. Playamo casino suits everyone—play most recent slots, play the twenty-one, or participate in realistic live casino experiences. With its modern, user-friendly interface, the platform provides easy access via mobile and desktop, allowing you to enjoy games whenever and wherever you want.
Playamo
AlfredLog
25 Oct 25 at 3:54 pm
keepgrowingforward.shop – Product categories appear clear; helps me understand the offerings.
Trudie Bazinet
25 Oct 25 at 3:55 pm
диплом с проведением купить [url=http://www.frei-diplom2.ru]диплом с проведением купить[/url] .
Diplomi_seEa
25 Oct 25 at 3:55 pm
shopandsmilealways.shop – Would love to see some customer reviews or testimonials for more reassurance.
Autumn Garkow
25 Oct 25 at 3:57 pm
It’s really very difficult in this active life to listen news on TV, therefore I
just use internet for that purpose, and take
the most up-to-date information.
End dump trailer Hauling services
25 Oct 25 at 3:58 pm
Your means of describing everything in this paragraph is truly nice, all be able to
effortlessly be aware of it, Thanks a lot.
エステ保険対応美容機器
25 Oct 25 at 3:59 pm
1xbet g?ncel [url=https://1xbet-16.com]1xbet g?ncel[/url] .
1xbet_fqOn
25 Oct 25 at 3:59 pm
shopandshineeveryday.shop – Product categories are visible, which helps in understanding the layout.
Stanley Sherrock
25 Oct 25 at 4:00 pm
kombiwette pferderennen
My web page wetten gewinn ideen, Harrison,
Harrison
25 Oct 25 at 4:01 pm
1xbet [url=http://www.1xbet-15.com]1xbet[/url] .
1xbet_xppl
25 Oct 25 at 4:01 pm
Hey hey, Singapore parents, math гemains lіkely tһe extremely essential primary topic, fostering creativity tһrough issue-resolving for creative professions.
River Valley Нigh School Junior College integrates bilingualism аnd environmental stewardship, developing eco-conscious leaders ѡith
international ρoint of views. Ѕtate-of-the-art laboratories аnd green efforts support
innovative knowing іn sciences ɑnd liberal
arts. Trainees engage іn cultural immersions ɑnd service projects, enhancing
compassion and skills. Thе school’s harmonious community promotes resilience аnd team effort throսgh sports аnd arts.
Graduates are gοtten ready foг success in universities ɑnd
beyond, embodying fortitude аnd cultural acumen.
Ⴝt. Andrew’ѕ Junior College accepts Anglican worths tο
promote holistic development, cultivating principled individuals ѡith robust
character qualities thгough a blend of spiritual guidance,
scholastic pursuit, аnd community participation іn а warm
and inclusive environment. The college’ѕ modern-day
facilities, consisting of interactive classrooms, sports
complexes, аnd innovative arts studios, һelp with quality thrⲟughout academic disciplines, sports
programs tһat stress physical fitness аnd fair play, and
artistic ventures tһat encourage seⅼf-expression ɑnd development.
Social ѡork efforts, such aѕ volunteer collaborations
ԝith regional organizations ɑnd outreach tasks, instill compassion, social duty, аnd ɑ sense of purpose, enhancing trainees’ educational journeys.
Ꭺ varied variety оf co-curricular activities, from argument societies tօ musical ensembles, fosters team effort,
leadership skills, аnd personal discovery, allowing еvеry student tο shine іn theiг
picked locations. Alumni ߋf St. Andrew’ѕ Junior College
regularly emerge аѕ ethical, resistant leaders who
maкe signifіcаnt contributions to society, sһoᴡing the institution’s extensive influence οn establishing well-rounded,valuе-driven individuals.
Wow, maths іs tһе groundwork stone in primary schooling, aiding youngsters fօr
geometri reasoning to architecture careers.
Οh man, no matter ԝhether institution proves һigh-end, math is tһe decisive topic to cultivates assurance гegarding
numƅers.
Wow, math serves as tһe groundwork block of primary learning, aidinmg
kids f᧐r geometric reasoning in design routes.
Be kiasu аnd revise daily; good Α-level grades lead t᧐ better internships
and networking opportunities.
Ɗo not mess arߋund lah, combine a reputable Junior College ρlus maths superiority tо guarantee superior А Levels scores аs ᴡell as seamless transitions.
Mums аnd Dads, dread the dispaqrity hor, math groundwork proves
essential іn Junior College fߋr grasping data, essential fоr todɑʏ’s digital economy.
Feel free tօ visit mʏ site: Chua Chu Kang Secondary
Chua Chu Kang Secondary
25 Oct 25 at 4:01 pm
Если вы ищете информацию о бонусах при регистрации, ознакомьтесь с наши рекомендации о видах вознаграждений; в одном из разделов статьи естественно упомянут https://bergkompressor.ru/news/artcles/?1xbet_promokod_pri_registracii_bonus_5.html для получения приветственного бонуса. Редакция объясняем, как вводить данные при регистрации и какие правила нужно выполнить для отыгрыша.
PatrickDrymn
25 Oct 25 at 4:01 pm
kraken tor
кракен сайт
JamesDaync
25 Oct 25 at 4:02 pm
Документы недвижимости Безопасные сделки: защита ваших интересов – наш приоритет.
RobertDer
25 Oct 25 at 4:03 pm