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://frei-diplom2.ru]легально купить диплом о высшем образовании[/url] .
Diplomi_ufEa
3 Oct 25 at 10:28 pm
Попробуйте https://www.zulamitapaz.com/2022/11/01/hello-world/
PedroMop
3 Oct 25 at 10:28 pm
Your mode of telling all in this article is truly good,
all be capable of simply understand it, Thanks a lot.
real money online casinos
3 Oct 25 at 10:29 pm
I have been exploring for a little for any high-quality articles or weblog
posts in this sort of space . Exploring in Yahoo I finally stumbled upon this website.
Studying this information So i am glad to exhibit that I have a very good uncanny feeling I came upon just
what I needed. I most surely will make sure to don?t put out of your mind this site and
give it a look regularly.
stream music albums
3 Oct 25 at 10:29 pm
купить диплом в сарове [url=www.rudik-diplom4.ru]купить диплом в сарове[/url] .
Diplomi_afOr
3 Oct 25 at 10:30 pm
куплю диплом медсестры в москве [url=www.frei-diplom15.ru]куплю диплом медсестры в москве[/url] .
Diplomi_vtoi
3 Oct 25 at 10:30 pm
купить диплом в крыму [url=http://rudik-diplom7.ru/]купить диплом в крыму[/url] .
Diplomi_wkPl
3 Oct 25 at 10:31 pm
диплом техникума купить дешево пять плюс [url=www.frei-diplom9.ru/]диплом техникума купить дешево пять плюс[/url] .
Diplomi_wyea
3 Oct 25 at 10:31 pm
Je trouve phenomenal Circus, c’est une plateforme qui deborde de vie. La gamme est tout simplement eblouissante, proposant des sessions live palpitantes. L’assistance est efficace et conviviale, repondant en un rien de temps. Les gains arrivent sans attendre, cependant des promotions plus frequentes seraient top. En resume, Circus garantit un divertissement de haut vol pour les passionnes de sensations fortes ! Notons aussi le site est style et bien pense, ajoute une touche de magie.
las vegas circus circus hotel & casino|
thunderwave8zef
3 Oct 25 at 10:33 pm
Soccermania
Michaelrow
3 Oct 25 at 10:33 pm
Hi! I’m at work browsing your blog from my new iphone 3gs!
Just wanted to say I love reading through your blog and
look forward to all your posts! Keep up the outstanding work!
NeuroVest Legit Or Not
3 Oct 25 at 10:33 pm
купить диплом спб с занесением в реестр [url=www.frei-diplom5.ru/]www.frei-diplom5.ru/[/url] .
Diplomi_kdPa
3 Oct 25 at 10:33 pm
купить проведенный диплом красноярск [url=www.frei-diplom4.ru]купить проведенный диплом красноярск[/url] .
Diplomi_mcOl
3 Oct 25 at 10:33 pm
купить диплом в ставрополе [url=http://www.rudik-diplom11.ru]купить диплом в ставрополе[/url] .
Diplomi_cqMi
3 Oct 25 at 10:35 pm
Официальный источник должен быть основан
на надежных данных, проведенных исследованиях или проверенной информации, достоверных ресурсах.
https://www.mjg.co.th/beste-bitcoin-casinos-einzahlungen-und-46/
3 Oct 25 at 10:35 pm
https://fermerskiiprodukt.ru
PatrickGop
3 Oct 25 at 10:36 pm
купить диплом в великих луках [url=www.rudik-diplom8.ru]купить диплом в великих луках[/url] .
Diplomi_ooMt
3 Oct 25 at 10:36 pm
где купить диплом мед колледжа [url=https://frei-diplom9.ru/]https://frei-diplom9.ru/[/url] .
Diplomi_msea
3 Oct 25 at 10:37 pm
где купить диплом с реестром [url=www.frei-diplom1.ru/]где купить диплом с реестром[/url] .
Diplomi_jsOi
3 Oct 25 at 10:37 pm
купить диплом о высшем образовании [url=https://www.rudik-diplom5.ru]купить диплом о высшем образовании[/url] .
Diplomi_yhma
3 Oct 25 at 10:38 pm
1xBet / 1хБет Ищете 1xBet официальный сайт? Он может быть заблокирован, но у 1хБет есть решения. 1xbet зеркало на сегодня — ваш главный инструмент. Это 1xbet зеркало рабочее всегда актуально. Также вы можете скачать 1xbet приложение для iOS и Android — это надежная альтернатива. Неважно, используете ли вы 1xbet сайт или 1хБет зеркало, вас ждет полный функционал: ставки на спорт и захватывающее 1xbet casino. 1хБет сегодня — это тысячи возможностей. Начните прямо сейчас!
MatthewBoymn
3 Oct 25 at 10:40 pm
купить медицинский диплом медсестры [url=https://www.frei-diplom13.ru]купить медицинский диплом медсестры[/url] .
Diplomi_utkt
3 Oct 25 at 10:41 pm
купить проведенный диплом высокие [url=http://frei-diplom3.ru/]купить проведенный диплом высокие[/url] .
Diplomi_hkKt
3 Oct 25 at 10:41 pm
купить диплом в магнитогорске [url=http://rudik-diplom4.ru]http://rudik-diplom4.ru[/url] .
Diplomi_qdOr
3 Oct 25 at 10:44 pm
купить диплом с занесением в реестр в украине [url=www.frei-diplom1.ru/]www.frei-diplom1.ru/[/url] .
Diplomi_fcOi
3 Oct 25 at 10:45 pm
Heard about Minotaurus ICO through a referral, and wow, the rewards are real. Battling obstacles in the game while staking $MTAUR for bonuses? Sign me up. This project’s momentum is unstoppable.
minotaurus presale
WilliamPargy
3 Oct 25 at 10:45 pm
диплом реестр купить [url=http://frei-diplom2.ru/]диплом реестр купить[/url] .
Diplomi_pyEa
3 Oct 25 at 10:45 pm
uv08gu
🗂 💼 Balance Notification - 0.33 BTC pending. Secure transfer > https://graph.org/Get-your-BTC-09-11?hs=7255fc1a3bb72291f146f9661674a5a8& 🗂
3 Oct 25 at 10:46 pm
купить диплом в подольске [url=rudik-diplom2.ru]купить диплом в подольске[/url] .
Diplomi_mepi
3 Oct 25 at 10:46 pm
Специалист уточняет продолжительность запоя, тип употребляемого алкоголя и наличие сопутствующих заболеваний. Такой подробный анализ позволяет подобрать оптимальные методы детоксикации и снизить риск осложнений.
Подробнее можно узнать тут – https://kapelnica-ot-zapoya-lugansk-lnr0.ru
HenryOrepe
3 Oct 25 at 10:47 pm
где можно купить диплом техникума пять плюс [url=www.frei-diplom8.ru/]где можно купить диплом техникума пять плюс[/url] .
Diplomi_rtsr
3 Oct 25 at 10:48 pm
https://lkc.hp.com/member/codeprom01o57930
Stanleycow
3 Oct 25 at 10:49 pm
Процесс оказания срочной помощи нарколога на дому в Мариуполе построен по отлаженной схеме, которая включает несколько ключевых этапов, направленных на быстрое и безопасное восстановление здоровья пациента.
Узнать больше – http://narcolog-na-dom-mariupol00.ru
CharlesNip
3 Oct 25 at 10:49 pm
Lucky Mate is an online casino for Australian players, offering pokies, table games, and live dealer options. It provides a welcome bonus up to AUD 1,000, accepts Visa, PayID, and crypto with AUD 20 minimum deposit, and has withdrawal limits of AUD 5,000 weekly. Licensed, it promotes safe play: Lucky Mate
Edwardfrevy
3 Oct 25 at 10:50 pm
https://medicexpressmx.com/# Legit online Mexican pharmacy
Williamjib
3 Oct 25 at 10:50 pm
Thanks a bunch for sharing this with all people you really understand what you are
talking approximately! Bookmarked. Please additionally seek advice from my web site =).
We can have a link alternate arrangement among us
BC.GAME slots games
3 Oct 25 at 10:51 pm
купить диплом в нижнем тагиле [url=http://rudik-diplom4.ru]купить диплом в нижнем тагиле[/url] .
Diplomi_nxOr
3 Oct 25 at 10:52 pm
хоккей прогноз сегодня [url=www.prognozy-na-khokkej4.ru/]www.prognozy-na-khokkej4.ru/[/url] .
prognozi na hokkei_gsOl
3 Oct 25 at 10:52 pm
купить диплом высшее [url=http://rudik-diplom5.ru/]купить диплом высшее[/url] .
Diplomi_fsma
3 Oct 25 at 10:52 pm
Do you mind if I quote a couple of your posts as long as I provide credit and sources back to
your website? My blog is in the very same area of interest
as yours and my visitors would definitely benefit from a lot of
the information you present here. Please let me know if this alright with you.
Thanks!
Shopping stickers for brands
3 Oct 25 at 10:53 pm
Мы используем новейшие образцы медицинской техники, что повышает безопасность процедур и скорость детоксикации.
Получить дополнительные сведения – [url=https://narkologicheskaya-pomoshh-ufa9.ru/]неотложная наркологическая помощь в уфе[/url]
LionelBok
3 Oct 25 at 10:53 pm
купить диплом ижевск с занесением в реестр [url=frei-diplom3.ru]купить диплом ижевск с занесением в реестр[/url] .
Diplomi_uwKt
3 Oct 25 at 10:54 pm
Mums and Dads, composed lah, excellent establishment рlus solid maths groundwork mеans yoᥙr child ѡill
handle decimals аѕ well as shapes wіth assurance, guiding for improved ⲟverall academic performance.
Yishun Innova Junior College combines strengths fоr digital literacy аnd
management excellence. Upgraded facilities promote development аnd long-lasting learning.
Varied programs іn media аnd languages promote imagination аnd citizenship.
Neighborhood engagements construct empathy аnd skills. Students become confident, tech-savvy leaders аll set for the digital age.
Nanyang Junior College masters championing bilingual efficiency ɑnd
cultural excellence, masterfully weaving tοgether abundant Chinese
heritage ᴡith contemporary international education t᧐ shape positive,
culturally nimble peolple ԝho are poised tо lead іn multicultural contexts.
Тhe college’s innovative centers, consisting ߋf specialized STEM labs,
performing arts theaters, ɑnd language immersion centers,
support robust programs іn science, technology,
engineering, mathematics, arts, аnd humanities that motivate innovation, crucial thinking,
аnd artistic expression. Ιn ɑ vibrant and inclusive community, students participate іn management opportunities ѕuch as student governance roles
ɑnd global exchange programs witһ partner organizations abroad,
ԝhich expand their perspectives аnd build vital global proficiencies.
Ƭhe focus on core worths ⅼike stability and strength іѕ incorporated
intօ life throսgh mentorship schemes, neighborhood service efforts, and health care tһat cultivate psychological intelligence ɑnd
personal growth. Graduates օf Nanyang Junior
College consistently master admissions
tօ top-tier universities, supporting а рroud legacy of impressive achievements, cultural
appreciation, ɑnd a deep-seated enthusiasm fߋr constant self-improvement.
Ꭺvoid mess ɑrоսnd lah, combine a excellent Junior College alongside math excellence tߋ assure elevated
A Levels scores аnd seamless сhanges.
Parents, dread tһe disparity hor,mathematics groundwork is critical in Junior College
to grasping data, essential ѡithin todаү’s digital economy.
Parents, kiasu approach оn lah, solid primary math guides fоr
superior science understanding as well aѕ construction dreams.
Wow, math acts ⅼike thee foundation stone іn primary education, assisting youngsters ᴡith dimensional reasoning fߋr architecture paths.
Օh no, primary maths teaches real-ѡorld uses likе
budgeting, tһerefore guarantee уour kid grasps tһіѕ correctly
beginning early.
Ԍood A-level results mean moгe choices in life, fгom courses tօ potential salaries.
Hey hey, Singapore folks, math proves ρrobably tһe extremely essential primary subject, encouraging
innovation tһrough pгoblem-solving to creative jobs.
Ꮋave a looқ at my website; Anglo-Chinese Junior College
Anglo-Chinese Junior College
3 Oct 25 at 10:54 pm
купить легальный диплом [url=http://frei-diplom1.ru/]купить легальный диплом[/url] .
Diplomi_xrOi
3 Oct 25 at 10:56 pm
В Кухни в Дом купили кухонный гарнитур с встраиваемой техникой. Всё сделали идеально: проект, материалы, монтаж. Теперь готовить стало удобно и приятно https://kuhni-v-dom.ru/
Eugeniostync
3 Oct 25 at 10:58 pm
купить диплом в великих луках [url=http://www.rudik-diplom2.ru]купить диплом в великих луках[/url] .
Diplomi_qrpi
3 Oct 25 at 10:58 pm
Hi, I do think this is an excellent blog. I stumbledupon it
😉 I may revisit once again since i have book
marked it. Money and freedom is the best way
to change, may you be rich and continue to help other people.
real money casino online
3 Oct 25 at 10:58 pm
купить диплом о средне специальном образовании с занесением в реестр [url=http://frei-diplom6.ru]купить диплом о средне специальном образовании с занесением в реестр[/url] .
Diplomi_uwOl
3 Oct 25 at 10:59 pm
купить диплом в уфе с реестром [url=https://frei-diplom5.ru]https://frei-diplom5.ru[/url] .
Diplomi_zyPa
3 Oct 25 at 10:59 pm
В Кухни в Дом купили бюджетную кухню, и она оказалась очень удобной и красивой. Даже за небольшие деньги можно получить отличное качество https://kuhni-v-dom.ru/
Eugeniostync
3 Oct 25 at 10:59 pm