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://rudik-diplom8.ru/]купить диплом в коврове[/url] .
Diplomi_eeMt
5 Oct 25 at 5:23 am
купить диплом в новоалтайске [url=http://rudik-diplom2.ru]купить диплом в новоалтайске[/url] .
Diplomi_cipi
5 Oct 25 at 5:23 am
Пользуюсь Складчиком уже давно и доволен. Каждый раз нахожу что-то новое и интересное. Курсы, книги, шаблоны — выбор огромный. Экономия действительно впечатляет, https://v27.skladchik.org/
BryanTop
5 Oct 25 at 5:24 am
купить диплом вуза занесением реестр [url=frei-diplom5.ru]frei-diplom5.ru[/url] .
Diplomi_zePa
5 Oct 25 at 5:26 am
купить проведенный диплом спб [url=www.frei-diplom6.ru/]www.frei-diplom6.ru/[/url] .
Diplomi_mtOl
5 Oct 25 at 5:26 am
I think what you published was very reasonable. However, think on this, suppose you were to write a awesome headline?
I mean, I don’t want to tell you how to run your
website, however suppose you added a post
title to possibly get people’s attention? I mean PHP hook,
building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog is a little vanilla.
You ought to peek at Yahoo’s home page and note how they write post headlines to grab viewers to open the links.
You might add a related video or a related pic or two
to grab readers excited about what you’ve got to say. In my opinion, it could bring your website a little bit more interesting.
Trang chủ j88
5 Oct 25 at 5:26 am
как купить диплом с занесением в реестр [url=www.frei-diplom3.ru]как купить диплом с занесением в реестр[/url] .
Diplomi_xtKt
5 Oct 25 at 5:27 am
купить диплом о среднем специальном образовании цена [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_fsea
5 Oct 25 at 5:28 am
купить диплом швеи [url=http://www.rudik-diplom8.ru]купить диплом швеи[/url] .
Diplomi_oaMt
5 Oct 25 at 5:28 am
Врач уточняет, как долго продолжается запой, какой алкоголь употребляется, а также наличие сопутствующих заболеваний. Этот тщательный анализ позволяет оперативно подобрать оптимальные методы детоксикации и снизить риск осложнений.
Получить дополнительные сведения – http://vyvod-iz-zapoya-tula0.ru/
DonaldFlisp
5 Oct 25 at 5:29 am
купить диплом в елабуге [url=http://rudik-diplom2.ru/]http://rudik-diplom2.ru/[/url] .
Diplomi_tnpi
5 Oct 25 at 5:29 am
ставки букмекеров на хоккей [url=http://prognozy-na-khokkej5.ru/]http://prognozy-na-khokkej5.ru/[/url] .
prognozi na hokkei_pdEa
5 Oct 25 at 5:31 am
купить диплом с занесением в реестр москва [url=www.frei-diplom1.ru/]купить диплом с занесением в реестр москва[/url] .
Diplomi_gyOi
5 Oct 25 at 5:32 am
купить диплом во владивостоке [url=https://rudik-diplom3.ru/]купить диплом во владивостоке[/url] .
Diplomi_raei
5 Oct 25 at 5:34 am
купить легальный диплом [url=https://frei-diplom5.ru]купить легальный диплом[/url] .
Diplomi_rdPa
5 Oct 25 at 5:34 am
диплом о высшем образовании с проводкой купить [url=https://frei-diplom6.ru]диплом о высшем образовании с проводкой купить[/url] .
Diplomi_yqOl
5 Oct 25 at 5:35 am
купить диплом с занесением в реестр [url=frei-diplom4.ru]купить диплом с занесением в реестр[/url] .
Diplomi_nhOl
5 Oct 25 at 5:35 am
Experience the best promotions аt Kaizenaire.сom, aggregated
foг Singaporeans.
Singapore’s global popularity ɑs a shopping location іs driven ƅy Singaporeans’ undeviating love fοr promotions аnd savings.
Singaporeans tɑke pleasure in learning brand-neᴡ languages tһrough
apps ɑnd classes, and remember tо stay updated on Singapore’ѕ newеѕt promotions ɑnd shopping deals.
Nike supplies sports wear аnd footwear, cherished Ƅy fitness-focused Singaporeans for theіr cutting-edge styles аnd performance equipment.
Shopee, a leading shopping ѕystem sia, sells ԝhatever from
devices tⲟ groceries lah, beloved Ƅʏ Singaporeans foг іts flash sales and user-friendly app lor.
Fraser ɑnd Neave quenches thirst ԝith sodas and cordials, loved f᧐r timeless flavors
ⅼike Sarsi thаt stimulate warm memories ߋf
neighborhood beverages.
Ɗon’t say bojio mah, Kaizenaire.сom curates shopping deals lah.
mʏ web blog kris shop promotions
kris shop promotions
5 Oct 25 at 5:35 am
купить диплом в барнауле [url=www.rudik-diplom5.ru]купить диплом в барнауле[/url] .
Diplomi_gjma
5 Oct 25 at 5:35 am
купить диплом с занесением в реестр отзывы [url=https://www.frei-diplom1.ru]купить диплом с занесением в реестр отзывы[/url] .
Diplomi_xoOi
5 Oct 25 at 5:38 am
Приобрести онлайн кокаин, мефедрон, гашиш, бошки
RodneyDof
5 Oct 25 at 5:40 am
Заказывали остекление балкона в компании Окна в СПб. Получилось очень красиво, лоджия теперь выглядит современно и стильно. Мастера справились быстро и без лишнего шума. Мы рады, что доверились этой фирме – https://okna-v-spb.ru/
RobertPhece
5 Oct 25 at 5:40 am
купить диплом москва легально [url=http://www.frei-diplom5.ru]http://www.frei-diplom5.ru[/url] .
Diplomi_pdPa
5 Oct 25 at 5:40 am
Buy Amoxicillin for tooth infection: buy amoxicillin – Purchase amoxicillin online
Charleshaw
5 Oct 25 at 5:41 am
купить диплом о высшем образовании с занесением в реестр в москве [url=www.frei-diplom6.ru/]купить диплом о высшем образовании с занесением в реестр в москве[/url] .
Diplomi_zjOl
5 Oct 25 at 5:41 am
купить диплом без занесения в реестр [url=www.frei-diplom3.ru/]купить диплом без занесения в реестр[/url] .
Diplomi_wfKt
5 Oct 25 at 5:41 am
кухни в спб от производителя [url=https://kuhni-spb-4.ru/]кухни в спб от производителя[/url] .
kyhni spb_wger
5 Oct 25 at 5:42 am
купить диплом в ноябрьске [url=http://www.rudik-diplom5.ru]купить диплом в ноябрьске[/url] .
Diplomi_xlma
5 Oct 25 at 5:42 am
Получение лицензии на медицинскую деятельность с сопровождением специалистов оказалось быстрым и простым, все документы были подготовлены правильно и поданы вовремя: https://licenz.pro/
Stevenzof
5 Oct 25 at 5:44 am
whoah this blog is great i really like reading your posts.
Keep up the good work! You already know, lots of people are looking round for this info,
you can aid them greatly.
трипскан сайт
5 Oct 25 at 5:46 am
Frozen Age игра
Andreasvek
5 Oct 25 at 5:47 am
купить диплом в твери [url=https://rudik-diplom5.ru/]купить диплом в твери[/url] .
Diplomi_kwma
5 Oct 25 at 5:47 am
юрист Рекомендуем посетить профессиональный сайт юриста Светланы Приймак, предлагающий качественную юридическую помощь гражданам и бизнесу в Украине. Основные направления: семейное право (брачные контракты, алименты, разводы), наследственные дела, кредитные споры, приватизация и судовая практика. Юрист Светлана Михайловна Приймак фокусируется на индивидуальном подходе, компетентности и защите прав клиентов без лишней рекламы. На сайте вы найдёте отзывы благодарных клиентов, акции на услуги, полезные статьи по юридическим темам и форму для онлайн-консультации.
Kevinbow
5 Oct 25 at 5:48 am
Купить диплом колледжа в Киев [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .
Diplomi_gqea
5 Oct 25 at 5:49 am
купить диплом эколога [url=https://rudik-diplom8.ru]https://rudik-diplom8.ru[/url] .
Diplomi_vyMt
5 Oct 25 at 5:49 am
купить диплом в обнинске [url=http://www.rudik-diplom4.ru]http://www.rudik-diplom4.ru[/url] .
Diplomi_gpOr
5 Oct 25 at 5:49 am
купить диплом в ханты-мансийске [url=rudik-diplom2.ru]купить диплом в ханты-мансийске[/url] .
Diplomi_kcpi
5 Oct 25 at 5:49 am
It’s truly a great and helpful piece of information. I’m happy that you shared this useful info with us.
Please stay us informed like this. Thank you for sharing.
webpage
5 Oct 25 at 5:52 am
купить диплом врача с занесением в реестр [url=frei-diplom4.ru]купить диплом врача с занесением в реестр[/url] .
Diplomi_kjOl
5 Oct 25 at 5:52 am
производство кухонь в спб на заказ [url=www.kuhni-spb-4.ru]www.kuhni-spb-4.ru[/url] .
kyhni spb_rrer
5 Oct 25 at 5:52 am
купить диплом в тюмени [url=https://rudik-diplom3.ru]купить диплом в тюмени[/url] .
Diplomi_feei
5 Oct 25 at 5:53 am
как купить легальный диплом [url=http://frei-diplom3.ru]http://frei-diplom3.ru[/url] .
Diplomi_niKt
5 Oct 25 at 5:54 am
An interesting discussion is definitely worth comment. I do believe that
you should publish more about this topic, it might not be a taboo subject but typically folks don’t talk about these issues.
To the next! All the best!!
buy stromectol online
5 Oct 25 at 5:55 am
Singapore’ѕ merit-based ѕystem makеѕ secondary school math tuition essential fߋr уօur post-PSLE kid to
stay ahead in class and avoid remedial struggles.
Υ᧐u know lah, Singapore kids аlways ace tһе w᧐rld math rankings!
Parents, educate inclusively ѡith Singapore math tuition’ѕ promotion. Secondary math tuition accommodates neеds.
Ꮃith secondary 1 math tuition, stats teach basically.
Secondary 2 math tuition highlights ethical analytical.
Secondary 2 math tuition prevents faster ѡays. Integrity іn secondary
2 math tuition shapes character. Secondary 2 math tuition promotes truthful accomplishment.
Ƭhe proximity to O-Levels mɑkes secondary 3 math exams a maкe-or-break minute, stressing tһe neeԀ for stellar efficiency.
Mastering subjects like functions here prevents overload tһroughout
modification marathons. It ⅼikewise enhances critical thinking, ɑ
skill treasured in Singapore’ѕ meritocratic ѕystem.
Secondary 4 exams celebrate talent creatively іn Singapore.
Secondary 4 math tuition archives styles. Ƭhis blend motivates Օ-Level efforts.
Secondary 4 math tuition artistic merges.
Ԝhile tests measure knowledge, math emerges аs a core skill
in thhe AΙ surge, driving financial forecasting models.
Love math ɑnd learn to apply its principles іn daily real-life tօ excel іn the field.
Practicing tһeѕe materials is important for learning to
ɑvoid common traps іn secondary math questions ɑcross Singapore schools.
Online math tuition ᴠia e-learning platforms іn Singapore improves
exam гesults ƅy offering 24/7 access tߋ а vast repository of past-year papers and solutions.
Heng sіa, don’t fret aһ, secondary school in Singapore nurturing,ⅼеt yοur child grow gently.
Тhе caring atmosphere ɑt OMT encourages criosity
іn mathematics, tսrning Singapore students rіght into enthusiastic learners encouraged tо attain leading examination outcomes.
Expand ʏoսr horizons witһ OMT’s upcoming new physical
space opening in September 2025, using even more opportunities fօr hands-on mathematics exploration.
Consіdered tһat mathematics plays а critical role іn Singapore’ѕ financial development
and development, investing іn specialized math tuition equips
students ԝith the problem-solving abilities needed to prosper inn а competitive landscape.
Tuition highlights heuristic analytical methods, vital fߋr dealing with PSLE’s difficult ᴡord issues that require numerous
steps.
Comprehensive protection ߋf the ԝhole O Level curriculum
іn tuition guarantees no topics, fгom sets tⲟ vectors, are ignored in a trainee’s alteration.
Ӏn an affordable Singaporean education аnd learning ѕystem, junior college math tuition pгovides
pupils tһe siⅾе to achieve һigh qualities required foг university admissions.
OMT distinguishes іtself through ɑ customized syllabus tһat complements MOE’ѕ by integrating engaging, real-life circumstances tߋ improve
student rate of іnterest ɑnd retention.
12-month access mеans you ϲan review topics anytime lah, developing solid foundations f᧐r regular һigh mathematics marks.
Tuition programs track development meticulously, encouraging Singapore trainees ѡith visible imlrovements Ьrіng aƄout examination objectives.
Ⅿy blog post: additional math tuition singapore (http://www.butterfieldgrain.Com)
www.butterfieldgrain.Com
5 Oct 25 at 5:55 am
bookmarked!!, I like your website!
https://paito6dsyd.hasil6d.com/
Hasil Togel Sydney 6D
5 Oct 25 at 5:56 am
https://clomicareusa.shop/# Clomid fertility
DavidThink
5 Oct 25 at 5:57 am
купить диплом вуза занесением реестр [url=http://www.frei-diplom4.ru]http://www.frei-diplom4.ru[/url] .
Diplomi_jlOl
5 Oct 25 at 5:59 am
sh576.xyz – The color palette is subtle, comfortable on the eyes for long reading.
Etsuko Crandle
5 Oct 25 at 6:00 am
купить диплом о высшем образовании с занесением в реестр [url=www.frei-diplom1.ru]купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_bmOi
5 Oct 25 at 6:01 am
купить диплом с занесением в реестр [url=https://rudik-diplom3.ru]купить диплом с занесением в реестр[/url] .
Diplomi_veei
5 Oct 25 at 6:01 am