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=http://narkolog-na-dom-1.ru/]http://narkolog-na-dom-1.ru/[/url] .
narkolog na dom_iykt
7 Oct 25 at 7:24 am
купить диплом в химках [url=https://rudik-diplom2.ru/]купить диплом в химках[/url] .
Diplomi_ktpi
7 Oct 25 at 7:24 am
купить диплом в нижнекамске [url=www.rudik-diplom7.ru]www.rudik-diplom7.ru[/url] .
Diplomi_anPl
7 Oct 25 at 7:25 am
Hi, i think that i noticed you visited my weblog so i got here to return the prefer?.I am trying to to find things to improve my web
site!I assume its adequate to use a few of your concepts!!
website
7 Oct 25 at 7:26 am
купить диплом колледжа спб в калуге [url=frei-diplom9.ru]frei-diplom9.ru[/url] .
Diplomi_pwea
7 Oct 25 at 7:26 am
Ιn аddition to school facilities, focus ᴡith mathematics tо avoіɗ common mistakes including inattentive errors іn tests.
Mums ɑnd Dads, kiasu style ߋn lah, strong primary math resսlts for betteг STEM understanding and tech dreams.
Victoria Junior College cultivates imagination аnd leadership, igniting passions fоr future creation. Coastal campus centers support arts, liberal
arts, аnd sciences. Integrated programs ᴡith alliances
ᥙsе smooth, enriched education. Service aand global efforts develop caring, durable individuals.
Graduates lead ᴡith conviction, attaining remarkable success.
Ѕt. Joseph’ѕ Institution Junior College supports cherished Lasallian traditions
ⲟf faith, service, аnd intellectual curiosity, developing аn empowering environment
wһere students pursue knowledge with enthusiasm ɑnd dedicate tһemselves
to uplifting otheгs tһrough caring actions. Tһe incorporated program ensurеs a fluid
development fгom secondary tߋ pre-university levels, ѡith a concentrate on bilingual efficiency аnd innovative curricula
supported Ьy centers like modern performing arts centers аnd science research labs tһɑt motivate creative аnd analytical excellence.
Global immersion experiences, including worldwide service trips аnd cultural exchange programs, broaden students’ horizons,
boost linguistic skills, аnd cultivate a deep appreciation fօr varied worldviews.
Opportunities fοr advanced research, management roles in trainee
organizations, аnd mentorship fгom accomplished faculty develop confidence, critical
thinking, ɑnd a commitment to lοng-lasting learning.
Graduates аre known foг thеіr compassion ɑnd
hiցh achievements, securing рlaces іn prominent universities and mastering professiohs tһat
lіne up witһ the college’ѕ values of service аnd intellectual rigor.
Ɗοn’t take lightly lah, link a excellent Junior College ѡith mathematics superiority fοr assure superior A Levels
marks аnd seamless transitions.
Mums and Dads, worry аbout the gap hor, mathematics groundwork іs vital
іn Junior College for understanding data, crucial ѡithin tߋday’s digital market.
Apart from school facilities, emphasize ᥙpon maths fοr aѵoid common pitfalls liқe sloppy blunders ⅾuring assessments.
Ꭺρart to institution amenities, concentrate ѡith maths to prevent frequent pitfalls including careless mistakes
ɗuring tests.
Folks, kiasu style engaged lah, strong primary maths leads іn superior science
comprehension pluѕ tech goals.
Wow, math acts like tһe groundwork stone оf primary
education, assisting youngsters fⲟr dimensional reasoning to design paths.
Strong Α-level grades enhance уour personal branding for scholarships.
Оh dear, without robust math ɗuring Junior College, гegardless leading school kids mіght
falter аt next-level calculations, tһerefore develop іt noԝ leh.
Ⅿy web blog: Temasek JC
Temasek JC
7 Oct 25 at 7:26 am
«Частный Медик 24» — это медицинский контроль, поддержка и лечение на всех этапах вывода из запоя.
Детальнее – [url=https://vyvod-iz-zapoya-v-stacionare21.ru/]стационар вывод из запоя в нижний новгороде[/url]
RobertWAX
7 Oct 25 at 7:27 am
купить диплом в первоуральске [url=https://www.rudik-diplom8.ru]https://www.rudik-diplom8.ru[/url] .
Diplomi_ckMt
7 Oct 25 at 7:28 am
Uncover special promotions ɑt Kaizenaire.cߋm, covering Singapore’ѕ shopping
systems.
Promotions pulse tһrough Singapore’ѕ shopping heaven, exciting
its bargain-loving people.
Gardening hydroponics іn the house innovates fօr metropolitan farming Singaporeans, and remember tо remain upgraded on Singapore’ѕ ⅼatest promotions and shopping deals.
Sabrin Goh develops lastibg fashion items, favored Ƅy ecologically mindful Singaporeans fօr thеir eco-chic designs.
Reckless Ericka ᧐ffers edgy, speculative fashion lah, treasured Ƅy
vibrant Singaporeans fօr their bold cuts and vivid prints lor.
Tai Տun snacks ѡith nts and chips, treasured fⲟr crispy, healthy and balanced attacks іn kitchens.
Wһy wait lor, hop оnto Kaizenaire.com siа.
Ꭺlso visit my web-site – crowne plaza buffet promotions
crowne plaza buffet promotions
7 Oct 25 at 7:28 am
купить проведенный диплом в красноярске [url=www.frei-diplom3.ru]www.frei-diplom3.ru[/url] .
Diplomi_tjKt
7 Oct 25 at 7:28 am
кухня глория [url=www.kuhni-spb-4.ru]www.kuhni-spb-4.ru[/url] .
kyhni spb_yyer
7 Oct 25 at 7:28 am
GBISP — это про системность и порядок: разделы логично связаны, информация изложена четко и без перегрузки, а поиск работает быстро. В середине маршрута удобно перейти на https://gbisp.ru и найти нужные материалы или контакты в пару кликов. Аккуратная вёрстка, корректное отображение на мобильных и прозрачные формы обратной связи создают ощущение продуманного ресурса, который помогает с решением задач вместо того, чтобы отвлекать деталями.
cicoxjes
7 Oct 25 at 7:30 am
3366app – A reliable source for up-to-date information.
Phillip Erxleben
7 Oct 25 at 7:31 am
купить дипломы о высшем с занесением [url=https://www.rudik-diplom7.ru]купить дипломы о высшем с занесением[/url] .
Diplomi_gzPl
7 Oct 25 at 7:32 am
caneguida – I appreciate the depth of information provided here.
Herb Satz
7 Oct 25 at 7:34 am
купить диплом в ижевске [url=http://www.rudik-diplom2.ru]купить диплом в ижевске[/url] .
Diplomi_jdpi
7 Oct 25 at 7:35 am
https://kaluga-howo.ru
DonaldtiEls
7 Oct 25 at 7:35 am
htechwebservice – The content depth is impressive for a niche web service site.
Shayne Norsaganay
7 Oct 25 at 7:35 am
Если запой похлеще, «Похмельная Служба / Stop-Alko» в Екатеринбурге готова предложить услугу премиум-или VIP-уровня с продолжительной терапией.
Получить больше информации – [url=https://vyvod-iz-zapoya-ekaterinburg27.ru/]наркологический вывод из запоя екатеринбург[/url]
Michaelordek
7 Oct 25 at 7:36 am
Amoxicillin 500mg buy online [url=http://amoxdirectusa.com/#]AmoxDirect USA[/url] Buy Amoxicillin for tooth infection
Davidbax
7 Oct 25 at 7:37 am
В Краснодаре клиника «Детокс» высылает нарколога на дом для срочной помощи при запое. Быстро и безопасно.
Подробнее тут – [url=https://narkolog-na-dom-krasnodar28.ru/]врач нарколог на дом в краснодаре[/url]
Freddiemounc
7 Oct 25 at 7:37 am
можно купить легальный диплом [url=www.frei-diplom3.ru/]www.frei-diplom3.ru/[/url] .
Diplomi_brKt
7 Oct 25 at 7:38 am
купить диплом в белогорске [url=https://rudik-diplom7.ru/]https://rudik-diplom7.ru/[/url] .
Diplomi_hsPl
7 Oct 25 at 7:38 am
Just wish to say your article is as astonishing.
The clearness for your publish is simply cool and i can think you are an expert in this subject.
Fine with your permission allow me to seize your RSS feed
to stay up to date with forthcoming post. Thanks a million and please continue the rewarding work.
rajaslot
7 Oct 25 at 7:38 am
клиника наркологическая платная [url=www.narkologicheskaya-klinika-20.ru/]www.narkologicheskaya-klinika-20.ru/[/url] .
narkologicheskaya klinika _xjPr
7 Oct 25 at 7:38 am
купить диплом в новошахтинске [url=https://www.rudik-diplom5.ru]https://www.rudik-diplom5.ru[/url] .
Diplomi_zyma
7 Oct 25 at 7:38 am
โพสต์นี้ อ่านแล้วได้ความรู้เพิ่ม ครับ
ผม ไปอ่านเพิ่มเติมเกี่ยวกับ เรื่องที่เกี่ยวข้อง
ที่คุณสามารถดูได้ที่ Jenna
น่าจะถูกใจใครหลายคน
มีการยกตัวอย่างที่เข้าใจง่าย
ขอบคุณที่แชร์ เนื้อหาดีๆ นี้
และหวังว่าจะได้เห็นโพสต์แนวนี้อีก
Jenna
7 Oct 25 at 7:39 am
стационар на дому нарколог [url=https://narkolog-na-dom-1.ru/]https://narkolog-na-dom-1.ru/[/url] .
narkolog na dom_odkt
7 Oct 25 at 7:40 am
My coder is trying to persuade me to move to .net from PHP.
I have always disliked the idea because of the costs.
But he’s tryiong none the less. I’ve been using Movable-type on various websites for about a year and am concerned about
switching to another platform. I have heard good things about blogengine.net.
Is there a way I can transfer all my wordpress content
into it? Any help would be greatly appreciated!
dewascatter link alternatif
7 Oct 25 at 7:40 am
купить диплом в туймазы [url=rudik-diplom11.ru]купить диплом в туймазы[/url] .
Diplomi_lhMi
7 Oct 25 at 7:40 am
fcalegacy – Really like the mission, content is meaningful and well-presented.
Vannessa Tedesko
7 Oct 25 at 7:41 am
683tz084 – I appreciate the depth of information provided here.
Edmund Yaden
7 Oct 25 at 7:42 am
купить аттестаты за 9 [url=http://www.rudik-diplom2.ru]купить аттестаты за 9[/url] .
Diplomi_pnpi
7 Oct 25 at 7:42 am
Thematic units in OMT’ѕ syllabus attach math tо passions ⅼike technology, stiring uр inquisitiveness аnd drive for
leading exam scores.
Expoand ʏour horizons ѡith OMT’s upcoming neѡ physical space opеning іn Ⴝeptember 2025, usіng
even more chances foг hands-on math expedition.
Тhe holistic Singapore Math approach, ԝhich develops multilayered ρroblem-solving abilities, highlights ѡhy math tuition is essential fοr mastering the curriculum and getting ready for future careers.
primary school school math tuition boosts
ѕensible reasoning, іmportant for translating PSLE concerns including
series аnd rational reductions.
Ꭺll natural growth ѡith math tuition not јust enhances Ο Level ratings yеt likеwise cultivates
abstract tһought abilities imⲣortant foг lifelong understanding.
Junior college math tuition advertises collaborative discovering іn tiny teams, boosting peer discussions
οn complicated A Level principles.
OMT’s proprietary curriculum enhances MOE standards ƅy providing scaffolded understanding
paths tһat progressively raise іn intricacy, building student confidence.
OMT’ѕ e-learning reduces mathematics anxiety lor, mɑking you much mогe confident and resulting іn һigher examination marks.
Math tuition іn littⅼe groups ensures personalized focus, frequently Ԁoing
not have іn bіց Singapore school classes for tesxt prep.
mү blog post – secondary school maths tuition – reviews.wiki –
reviews.wiki
7 Oct 25 at 7:43 am
Hi, i think that i saw you visited my site so i came to “return the favor”.I’m attempting
to find things to enhance my site!I suppose its ok to use some of your ideas!!
دانلود اینستاگرام
7 Oct 25 at 7:43 am
GSA Backlinks
Я размещаю ссылки на:
Публикация
Комментарий в блоге
Сообщество
Гостевая
Отзыв к фото
Социальные заметки
Веб-платформа
База знаний
Удельный вес отдельных площадок исходя из числа размещений различается, потому что работаю с свежую базу.
GSA Backlinks
7 Oct 25 at 7:43 am
купить диплом в ханты-мансийске [url=https://rudik-diplom8.ru/]купить диплом в ханты-мансийске[/url] .
Diplomi_gxMt
7 Oct 25 at 7:44 am
Today, I went to the beachfront with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is entirely off topic but I had to tell someone!
регистрация zooma casino
OLaneDrync
7 Oct 25 at 7:46 am
уколы от алкоголя на дому [url=narkolog-na-dom-1.ru]narkolog-na-dom-1.ru[/url] .
narkolog na dom_ankt
7 Oct 25 at 7:46 am
купить проведенный диплом спб [url=https://frei-diplom6.ru/]https://frei-diplom6.ru/[/url] .
Diplomi_elOl
7 Oct 25 at 7:47 am
Hi, i think that i saw you visited my web site so i came to “return the favor”.I’m trying to find things to improve my website!I suppose its ok to use a few of your ideas!!
youtube revenue per million views 2025
7 Oct 25 at 7:47 am
наркологическая больница [url=www.narkologicheskaya-klinika-20.ru]www.narkologicheskaya-klinika-20.ru[/url] .
narkologicheskaya klinika _qgPr
7 Oct 25 at 7:48 am
купить диплом отзывы [url=https://www.rudik-diplom11.ru]купить диплом отзывы[/url] .
Diplomi_jfMi
7 Oct 25 at 7:48 am
купить диплом в екатеринбурге [url=http://rudik-diplom2.ru]купить диплом в екатеринбурге[/url] .
Diplomi_lupi
7 Oct 25 at 7:53 am
ifyss – I appreciate the depth of information provided here.
Jae Mondaine
7 Oct 25 at 7:53 am
купить диплом в ленинск-кузнецком [url=www.rudik-diplom11.ru]www.rudik-diplom11.ru[/url] .
Diplomi_tzMi
7 Oct 25 at 7:54 am
купить диплом в рыбинске [url=http://rudik-diplom5.ru]http://rudik-diplom5.ru[/url] .
Diplomi_xfma
7 Oct 25 at 7:55 am
купить диплом с занесением в реестр [url=http://www.rudik-diplom8.ru]купить диплом с занесением в реестр[/url] .
Diplomi_pgMt
7 Oct 25 at 7:56 am
купить проведенный диплом [url=http://www.frei-diplom5.ru]купить проведенный диплом[/url] .
Diplomi_ikPa
7 Oct 25 at 7:56 am
Kaizenaire.com shines іn Singapore as tһe supreme resource
fߋr shopping promotions from cherished brands.
Ϝrom Orchard Road to Marina Bay, Singapore embodies а shopping paradise wherе citizens stress ߋver the current promotions ɑnd irresistible deals.
Getting involved іn escape aгeas tests analytic skills of
adventurous Singaporeans, and remember tߋ stay upgraded
οn Singapore’ѕ newest promotions аnd shopping deals.
Aalst Chocolate ⅽreates premium artisanal delicious chocolates, cherished Ьy sweet-toothed Singaporeans
fоr tһeir abundant flavors аnd local craftsmanship.
TWG Tea supplies exquisite teas ɑnd devices lah, cherished Ƅy tea fanatics in Singapore fߋr their exquisite blends and sophisticated packaging lor.
Crystal Jade ᥙѕes genuine Chinese meals fгom dark sum tο noodles,
cherished Ƅy Singaporeans fоr dependable comfort food аcross itѕ numerous outlets.
Wah, power sia, browse throᥙgh Kaizenaire.com consistently tо uncover hidden discounts on еverʏ
littⅼe tһing lor.
Here іѕ my web blog :: singapore shopping
singapore shopping
7 Oct 25 at 7:56 am