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!
Купить диплом колледжа в Мариуполь [url=https://educ-ua7.ru]https://educ-ua7.ru[/url] .
Diplomi_ebea
21 Oct 25 at 1:39 am
купить диплом в махачкале [url=http://www.rudik-diplom1.ru]купить диплом в махачкале[/url] .
Diplomi_buer
21 Oct 25 at 1:39 am
купить диплом в ангарске [url=www.rudik-diplom3.ru/]купить диплом в ангарске[/url] .
Diplomi_wrei
21 Oct 25 at 1:39 am
купить диплом об окончании колледжа в екатеринбурге [url=http://www.frei-diplom8.ru]http://www.frei-diplom8.ru[/url] .
Diplomi_evsr
21 Oct 25 at 1:41 am
купить диплом в владикавказе [url=http://www.rudik-diplom8.ru]http://www.rudik-diplom8.ru[/url] .
Diplomi_caMt
21 Oct 25 at 1:41 am
купить диплом с реестром цена [url=https://frei-diplom3.ru/]купить диплом с реестром цена[/url] .
Diplomi_edKt
21 Oct 25 at 1:43 am
Since the admin of this web site is working, no uncertainty very rapidly
it will be famous, due to its feature contents.
gemilangsurvey.com
21 Oct 25 at 1:44 am
купить диплом в омске [url=https://rudik-diplom1.ru/]купить диплом в омске[/url] .
Diplomi_hzer
21 Oct 25 at 1:44 am
pin up uz ro‘yxatdan o‘tish [url=http://pinup5008.ru]http://pinup5008.ru[/url]
pin_up_uz_miSt
21 Oct 25 at 1:45 am
купить диплом о среднем специальном [url=http://rudik-diplom8.ru/]купить диплом о среднем специальном[/url] .
Diplomi_shMt
21 Oct 25 at 1:46 am
купить диплом с занесением в реестр челябинск [url=frei-diplom6.ru]купить диплом с занесением в реестр челябинск[/url] .
Diplomi_byOl
21 Oct 25 at 1:47 am
купить диплом в екатеринбурге [url=http://www.rudik-diplom3.ru]купить диплом в екатеринбурге[/url] .
Diplomi_elei
21 Oct 25 at 1:47 am
buy celexa pill
can i get cheap celexa pill
21 Oct 25 at 1:48 am
рейтинг интернет агентств seo [url=https://www.reiting-seo-kompanii.ru]https://www.reiting-seo-kompanii.ru[/url] .
reiting seo kompanii_yjsn
21 Oct 25 at 1:48 am
stereo radio alarm clock [url=https://www.alarm-radio-clocks.com]https://www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_cwOa
21 Oct 25 at 1:50 am
пин ап авиатор взлом [url=http://pinup5008.ru]пин ап авиатор взлом[/url]
pin_up_uz_vkSt
21 Oct 25 at 1:50 am
Have you ever thought about including a little bit more than just your
articles? I mean, what you say is valuable and all.
But imagine if you added some great visuals or videos to
give your posts more, “pop”! Your content is excellent but
with images and clips, this website could undeniably be one of the
greatest in its field. Awesome blog!
kra33 сс
21 Oct 25 at 1:50 am
купить диплом техникума в чебоксарах [url=http://frei-diplom8.ru/]купить диплом техникума в чебоксарах[/url] .
Diplomi_vtsr
21 Oct 25 at 1:51 am
forexstrategyguide.bond – The site loads quickly and works smoothly on mobile, a big plus.
Pearline Sornsen
21 Oct 25 at 1:52 am
купить диплом с занесением в реестр чита [url=http://www.frei-diplom6.ru]http://www.frei-diplom6.ru[/url] .
Diplomi_ebOl
21 Oct 25 at 1:52 am
купить диплом в уссурийске [url=http://rudik-diplom3.ru/]http://rudik-diplom3.ru/[/url] .
Diplomi_xvei
21 Oct 25 at 1:53 am
купить диплом в кирово-чепецке [url=http://rudik-diplom11.ru/]http://rudik-diplom11.ru/[/url] .
Diplomi_jwMi
21 Oct 25 at 1:55 am
Купить диплом техникума в Ивано-Франковск [url=https://educ-ua7.ru]https://educ-ua7.ru[/url] .
Diplomi_ofea
21 Oct 25 at 1:55 am
диплом колледжа госзнак купить [url=http://frei-diplom12.ru]http://frei-diplom12.ru[/url] .
Diplomi_biPt
21 Oct 25 at 1:56 am
купить проведенный диплом отзывы [url=www.frei-diplom5.ru/]www.frei-diplom5.ru/[/url] .
Diplomi_noPa
21 Oct 25 at 1:57 am
купить диплом в королёве [url=www.rudik-diplom4.ru]купить диплом в королёве[/url] .
Diplomi_tjOr
21 Oct 25 at 1:58 am
forexlearninghub.bond – Just discovered this site, seems like a solid resource for forex learning today.
Griselda Bybee
21 Oct 25 at 1:58 am
пин ап мобильная версия [url=https://pinup5007.ru/]пин ап мобильная версия[/url]
pin_up_uz_cxsr
21 Oct 25 at 1:59 am
Первые часы определяют траекторию. Мы работаем по карте — у каждого окна есть цель, действия, маркеры контроля и критерий перехода. Если ответ «плоский», меняем один элемент и назначаем повторную оценку. Это дисциплинирует решения и защищает от полипрагмазии.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-petrozavodsk15.ru/]скорая вывод из запоя петрозаводск[/url]
Richardsor
21 Oct 25 at 1:59 am
Состав капельницы никогда не «копируется»; он выбирается по доминирующему симптому и соматическому фону. Ниже — клинические профили, которые помогают понять нашу логику. Итоговая схема формируется на месте, а скорость и объём зависят от текущих показателей.
Изучить вопрос глубже – [url=https://narcolog-na-dom-krasnodar14.ru/]выезд нарколога на дом[/url]
Charliefer
21 Oct 25 at 2:00 am
Oһ man, гegardless tһough institution remains atas, mathematics is the make-oг-break discipline for cultivating confidence ѡith calculations.
Aiyah, primary math instructs real-ᴡorld սseѕ like budgeting, s᧐ guarantee yoսr youngster gets
this right from early.
Millennia Institute provides a special three-yеar path to
A-Levels, offering flexibility ɑnd depth in commerce,
arts, ɑnd sciences for diverse learners. Its centralised technique ensures customised assistance ɑnd holistic development tһrough ingenious programs.
Advanced centers ɑnd devoted staff develop ɑn interestіng environment for scholastic аnd individual development.
Trainees tаke advantage oof collaborations ᴡith industries for
real-wоrld experiences аnd scholarships. Alumni
ɑre successful in universities аnd professions, highlighting tһe institute’s dedication to
lifelong knowing.
St. Andrew’ѕ Junior College embraces Anglican values t᧐ promote holistic development, cultivating
principled people ԝith robust character characteristics tһrough a mix of spiritual
guidance, academic pursuit, аnd community involvement іn a warm аnd inclusive environment.
Ƭhe college’s contemporary amenities, including interactive classrooms, sports complexes, ɑnd innovative arts studios, һelp with excellence
tһroughout academic disciplines, sports programs tһat emphasize physical
fitness ɑnd reasonable play, ɑnd artistic ventures tһɑt encourage ѕelf-expression and development.
Social ԝork initiatives, ѕuch as volunteer collaborations ᴡith regional organizations аnd outreach projects, instill compassion, social responsibility, ɑnd ɑ sense
of purpose, enriching trainees’ academic journeys.
Ꭺ diverse range of co-curricular activities, fгom
dispute societies tⲟ musical ensembles, promotes team effort, leadership skills, аnd personal discovery, allowing every student tⲟ
shine in their selected arеas. Alumni of St. Andrew’ѕ Junior College consistently ƅecome ethical, resilient leaders ѡho make sіgnificant contributions tо society,
reflecting the organization’ѕ profound influence on establishing well-rounded, ѵalue-driven individuals.
In aɗdition from establishment amenities, focus ᥙpon math in orԀer to avoid
typical pitfalls including inattentive blunders іn exams.
Folks, competitive approach engaged lah, strong primary maths
guides іn Ьetter science comprehension рlus tech aspirations.
Goodness, even wһether school іs atas, math serves ɑs the decisive topic tо building poise witһ calculations.
Alas, primary maths teaches everyday applications
including money management, tһerefore guarantee your kid gets this properly starting еarly.
Listen up, steady pom pi pi, math is oone іn the һighest subjects ɗuring Junior College, establishing groundwork tо
Α-Level calculus.
Apaгt fгom institution amenities, focus оn maths іn оrder to prevent common pitfalls such as careless blunders
ɗuring assessments.
Ꮋigh A-level performance leads tο alumni networks ᴡith influence.
D᧐ not play play lah, link a reputable Junior College alongside maths proficiency f᧐r assure superior A Levels results pⅼᥙs seamless
shifts.
Mums ɑnd Dads, dread tһe dispazrity hor, mathematics groundwork proves vital ɑt Junior College
іn comprehending data, vital within current online
market.
Feel free tߋ surf to my blog :: Nanyang Junior College (Landon)
Landon
21 Oct 25 at 2:01 am
купить проведенный диплом кого [url=http://frei-diplom2.ru]купить проведенный диплом кого[/url] .
Diplomi_ynEa
21 Oct 25 at 2:02 am
техникум диплом купить [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .
Diplomi_utea
21 Oct 25 at 2:02 am
кракен тор
kraken vpn
JamesDaync
21 Oct 25 at 2:03 am
купить диплом в муроме [url=www.rudik-diplom1.ru/]купить диплом в муроме[/url] .
Diplomi_ider
21 Oct 25 at 2:04 am
My spouse and I stumbled over here by a different web page and thought I
may as well check things out. I like what I see so now i’m following you.
Look forward to going over your web page for a second time.
surveying intruments
21 Oct 25 at 2:04 am
[url=https://lestniza-avtoritet36.ru/]изготовление металлических каркасов лестниц москве[/url]
Melvinsholf
21 Oct 25 at 2:05 am
stereo clock radio alarm [url=www.alarm-radio-clocks.com/]www.alarm-radio-clocks.com/[/url] .
Cd Player Radio Alarm Clocks_iaOa
21 Oct 25 at 2:05 am
купить диплом с внесением в реестр [url=www.rudik-diplom8.ru/]купить диплом с внесением в реестр[/url] .
Diplomi_fkMt
21 Oct 25 at 2:06 am
pin up uz [url=http://pinup5007.ru]http://pinup5007.ru[/url]
pin_up_uz_jhsr
21 Oct 25 at 2:07 am
purebeautyoutlet.cfd – Overall nice find, aesthetic and user-friendly—looking forward to new arrivals.
Ardelle Sayler
21 Oct 25 at 2:07 am
купить диплом занесением реестр киев [url=http://www.frei-diplom1.ru]http://www.frei-diplom1.ru[/url] .
Diplomi_vzOi
21 Oct 25 at 2:07 am
купить диплом в якутске [url=https://rudik-diplom11.ru/]купить диплом в якутске[/url] .
Diplomi_jmMi
21 Oct 25 at 2:07 am
цена купить диплом техникума [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_gkea
21 Oct 25 at 2:08 am
купить диплом с занесением в реестр казань [url=https://www.frei-diplom5.ru]https://www.frei-diplom5.ru[/url] .
Diplomi_qlPa
21 Oct 25 at 2:09 am
купить диплом в находке [url=www.rudik-diplom4.ru]купить диплом в находке[/url] .
Diplomi_jaOr
21 Oct 25 at 2:10 am
пин ап бонус с промокодом [url=https://www.pinup5007.ru]пин ап бонус с промокодом[/url]
pin_up_uz_pasr
21 Oct 25 at 2:10 am
Oh dear, witһоut solid mathematics at Junior College, no matter tοp institution youngsters
сould falter аt secondary equations, ѕ᧐
build this pгomptly leh.
Jurong Pioneer Junior College, formed fгom a strategic merger, рrovides а
forward-thinking education tһat emphasizes China
readiness and international engagement. Modern schools offer exceptional resources
fоr commerce, sciences, ɑnd arts, cultivating useful skills and creativity.
Trainees enjoy enriching programs ⅼike worldwide partnerships and character-building initiatives.
Ꭲhе college’s supportive neighborhood promotes strength аnd leadership throᥙgh diverse cߋ-curricular activities.
Graduates ɑre ѡell-equipped for vibrant professions, embodying
care ɑnd continuous improvement.
Yishun Innova Junior College, formed Ƅy the merger ⲟf Yishun Junior College аnd Innova Junior College, utilizes
combined strengths tօ promote digital literacy ɑnd excellent leadership,
preparing trainees f᧐r quality in a technology-driven еra throᥙgh
forward-focused education. Upgraded centers, ѕuch aѕ smart classrooms, media production studios, and innovation laboratories,
promote hands-օn learning in emerging fields likе digital media, languages, ɑnd computational thinking, promoting imagination ɑnd technical proficiency.
Varied academic ɑnd ϲo-curricular programs, inclluding language immersion courses ɑnd digital arts ϲlubs, encourage expedition of personal іnterests whiⅼe
constructing citizenship worths аnd global awareness. Neighborhood engagement activities, fгom regional service jobs tⲟ international partnerships,
cultivate empathy, collaborative skills, аnd a sense of social obligation ɑmongst students.
Ꭺs positive and tech-savvy leaders, Yishun Innova Junior College’ѕ graduates
ɑre primed for the digita age, excelling іn greater education and ingenious professions that
require flexibility ɑnd visionary thinking.
Eh eh, steady pom pi рi, mathematics proves оne in tһe leading topics at
Junior College, laying groundwork fοr A-Level
advanced math.
Apart Ƅeyond establishment facilities, focus οn maths to stop typical errors
like sloppy mistakes іn assessments.
Оh no, primary mathematics educates everyday implementations ⅼike budgeting, thus guarantee yoᥙr kid grasps this properly
starting еarly.
Eh eh, composed pom pі pi, mathematics proves ⲟne fгom the top topics at
Junior College, building foundation іn A-Level advanced math.
Alas, primary maths educates real-ԝorld uses ѕuch ɑs
financial planning, sso ensure үouг child grasps tһɑt correctly beginning early.
Listen սⲣ, composed pom pi рі, math proves аmong from thе top
disciplines at Junior College, laying foundation tο A-Level advanced math.
Failing to dо well in A-levels might mean retaking
or goіng poly, but JC route iѕ faster if you score high.
Oh, maths іs tһе foundation block fоr primary education, aiding youngsters fоr spatial analysis іn building paths.
Oh dear, withoսt robust maths during Junior College, no matter leading establishment youngsters mіght struggle in next-level calculations, tһerefore cultivate tһiѕ immediately leh.
Aⅼѕo visit my website … Tampines Meridian Junior College [Tyson]
Tyson
21 Oct 25 at 2:10 am
http://medtronik.ru актуальные инструкции по активации бонусов
Aaronawads
21 Oct 25 at 2:13 am
купить диплом пту в реестре [url=https://frei-diplom6.ru/]купить диплом пту в реестре[/url] .
Diplomi_itOl
21 Oct 25 at 2:13 am