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://frei-diplom1.ru/]купить диплом с занесением в реестр вуза[/url] .
Diplomi_isOi
15 Oct 25 at 8:16 am
натяжной потолок потолочкин отзывы [url=http://www.natyazhnye-potolki-samara-2.ru]http://www.natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_wbPi
15 Oct 25 at 8:17 am
Hello! Someone in my Facebook group shared this website with us
so I came to take a look. I’m definitely loving the information.
I’m bookmarking and will be tweeting this to my followers!
Wonderful blog and great style and design.
Siding Replacement
15 Oct 25 at 8:18 am
купить диплом в кисловодске [url=rudik-diplom6.ru]купить диплом в кисловодске[/url] .
Diplomi_fuKr
15 Oct 25 at 8:18 am
цены на натяжные потолки в самаре [url=https://natyazhnye-potolki-samara-2.ru/]цены на натяжные потолки в самаре[/url] .
natyajnie potolki samara_mfPi
15 Oct 25 at 8:19 am
Добро пожаловать в Клубника Казино, где каждый игрок найдет для себя идеальные условия для
выигрыша и наслаждения игрой. Мы предлагаем широкий выбор игр, включая классические слоты, рулетку, блэкджек
и уникальные игры с живыми дилерами.
В Клубника Казино мы гарантируем полную безопасность и прозрачность всех процессов, чтобы ваши данные и средства были в надежных руках.
Почему Clubnika казино для мобильных – лучший выбор для азартных игроков?
Мы предлагаем щедрые бонусы и
акции, чтобы каждый игрок мог увеличить свои шансы на победу и насладиться игрой.
В Клубника Казино мы ценим ваше время
и гарантируем быстрые выплаты, а наша служба поддержки всегда готова помочь в любой ситуации.
Когда стоит начать играть в Клубника Казино?
Не теряйте времени – начните свою
игровую карьеру прямо сейчас и получите щедрые бонусы на первый депозит.
Вот что вас ждет:
Щедрые бонусы и бесплатные спины для новых игроков.
Примите участие в наших турнирах и промо-акциях, чтобы получить шанс выиграть крупные денежные
призы.
Регулярные обновления
и новые игры каждый месяц.
В Клубника Казино каждый момент игры
может стать выигрышным для вас.
казино клубника онлайн
15 Oct 25 at 8:20 am
Этот информационный материал привлекает внимание множеством интересных деталей и необычных ракурсов. Мы предлагаем уникальные взгляды на привычные вещи и рассматриваем вопросы, которые волнуют общество. Будьте в курсе актуальных тем и расширяйте свои знания!
Ознакомьтесь с аналитикой – https://www.luckylads.io/wordpress-as-a-service-our-tech
NathanNef
15 Oct 25 at 8:22 am
купить диплом техникума с занесением в базу [url=https://www.frei-diplom9.ru]купить диплом техникума с занесением в базу[/url] .
Diplomi_fhea
15 Oct 25 at 8:22 am
купить дипломы о высшем [url=rudik-diplom13.ru]купить дипломы о высшем[/url] .
Diplomi_yuon
15 Oct 25 at 8:22 am
купить диплом в воронеже [url=https://rudik-diplom7.ru]купить диплом в воронеже[/url] .
Diplomi_jwPl
15 Oct 25 at 8:22 am
купить диплом украины с занесением в реестр [url=http://www.frei-diplom2.ru]http://www.frei-diplom2.ru[/url] .
Diplomi_rkEa
15 Oct 25 at 8:23 am
купить диплом с проводкой одно [url=frei-diplom3.ru]купить диплом с проводкой одно[/url] .
Diplomi_sqKt
15 Oct 25 at 8:23 am
купить диплом медсестры [url=https://www.frei-diplom13.ru]купить диплом медсестры[/url] .
Diplomi_tbkt
15 Oct 25 at 8:25 am
purple pharmacy online ordering: mexico pharmacy – mexican pharmacy
Andresstold
15 Oct 25 at 8:26 am
купить диплом в братске [url=http://rudik-diplom9.ru/]купить диплом в братске[/url] .
Diplomi_obei
15 Oct 25 at 8:29 am
Astronomers first discovered Cha 1107-7626 in 2008, and since then, they have observed it with different telescopes to learn more about how the infant planet evolves, as well as to study its surroundings.
[url=https://tlk-triga.ru/tral/]низкопольный трал[/url]
The research team observed the planet with Webb in 2024, making a clear detection of the surrounding disk. Next, the researchers studied it using the X-shooter spectrograph on the Very Large Telescope, which can capture different wavelengths of light emitted by an object ranging from ultraviolet to near-infrared.
The observations detected a puzzling event as the planet transitioned from a steady accretion rate in April and May to a burst of growth between June and August.
https://tlk-triga.ru/tral/
трал грузовик
“I fully expected that this is a short-term event, because those are much more common,” Scholz said. “When the burst kept going through July and August, I was absolutely stunned.”
Follow-up observations made using the Webb telescope also showed that the chemistry of the disk had changed. Water vapor, present during the growth spurt, wasn’t in the disk before. Webb is the only telescope capable of capturing such detailed changes in the environment for such a faint object, Scholz said. Prior to this research, astronomers had only ever seen the chemistry of a disk change around a star, but not around a planet.
Comparing observations from before and during the event showed that magnetic activity seems to be the main driver behind how much gas and dust is falling on the planet — a phenomenon typically associated with stars as they grow.
But the new observations suggest that objects with much less mass than stars — the rogue world is less than 1% the mass of our sun — can have strong magnetic fields capable of driving the growth of the object, according to the study authors.
An infrared image taken with the Visible and Infrared Telescope for Astronomy shows Cha 1107-7626, a dot located in the center.
An infrared image taken with the Visible and Infrared Telescope for Astronomy shows Cha 1107-7626, a dot located in the center. ESO/Meingast et al.
A planet that acts like a star
The origin of rogue planets remains murky. It’s possible they are planets that are kicked out of orbit around stars due to the gravitational influence of other objects. Or perhaps they are the lowest-mass objects that happen to form like stars. For Cha 1107-7626, astronomers said they think it’s the latter.
“This object most likely formed in a way similar to stars — from the collapse and fragmentation of a molecular cloud,” Scholz said.
A molecular cloud is a massive, cold cloud of gas and dust that can stretch for hundreds of light-years, according to NASA.
“We’re struck by quite how much the infancy of free-floating planetary-mass objects resembles that of stars like the Sun,” Jayawardhana said in a statement. “Our new findings underscore that similarity, and imply that some objects comparable to giant planets form the way stars do, from contracting clouds of gas and dust accompanied by disks of their own, and they go through growth episodes just like newborn stars.”
JasonGoave
15 Oct 25 at 8:30 am
Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех!
Что ещё? Расскажи всё! – https://yukisoramiko.com/2024/05/07/hello-world
Kevinacart
15 Oct 25 at 8:30 am
Selamat datang di E28BET Indonesia – Kemenangan Anda, Dibayar
Sepenuhnya. Nikmati bonus menarik, mainkan permainan seru, dan rasakan pengalaman taruhan online yang adil dan nyaman. Daftar
sekarang!
E28BET Indonesia – Kemenangan Anda
15 Oct 25 at 8:31 am
купить диплом с реестром в москве [url=frei-diplom3.ru]купить диплом с реестром в москве[/url] .
Diplomi_rwKt
15 Oct 25 at 8:32 am
купить диплом с занесением в реестр пенза [url=www.frei-diplom2.ru/]купить диплом с занесением в реестр пенза[/url] .
Diplomi_zaEa
15 Oct 25 at 8:32 am
https://bs2site.or.at
Hermannalia
15 Oct 25 at 8:32 am
Thank you for sharing your info. I truly
appreciate your efforts and I will be waiting for your next write ups thank you once again.
dewascatter link alternatif
15 Oct 25 at 8:32 am
Wow that was odd. I just wrote an very long comment but
after I clicked submit my comment didn’t show up.
Grrrr… well I’m not writing all that over again. Anyhow, just wanted to
say wonderful blog!
Soccer betting tips
15 Oct 25 at 8:32 am
https://telegra.ph/Mobilnaya-stanciya-monitoringa-dji-kupit-10-13
RonaldZer
15 Oct 25 at 8:33 am
купить диплом о высшем образовании с занесением в реестр в кемерово [url=http://frei-diplom1.ru]купить диплом о высшем образовании с занесением в реестр в кемерово[/url] .
Diplomi_leOi
15 Oct 25 at 8:34 am
компания потолочник [url=https://www.natyazhnye-potolki-samara-2.ru]https://www.natyazhnye-potolki-samara-2.ru[/url] .
natyajnie potolki samara_wsPi
15 Oct 25 at 8:34 am
Ожидаемый результат
Подробнее тут – https://vyvod-iz-zapoya-noginsk7.ru/vyvod-iz-zapoya-kruglosutochno-v-noginske
WaynekiX
15 Oct 25 at 8:34 am
купить диплом в новомосковске [url=https://www.rudik-diplom2.ru]купить диплом в новомосковске[/url] .
Diplomi_ddpi
15 Oct 25 at 8:35 am
Howdy! Would you mind if I share your blog with my myspace group?
There’s a lot of people that I think would really enjoy your content.
Please let me know. Cheers
88fc đăng nhập
15 Oct 25 at 8:35 am
Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
Хочешь знать всё? – https://get-way.com/about-us
Williamexirm
15 Oct 25 at 8:35 am
OMT’ѕ interactive tests gamify knowing, mɑking math addictive
fοr Singapore students ɑnd inspiring them
tⲟ press fοr superior test qualities.
Dive іnto self-paced math mastery ԝith OMT’ѕ 12-mοnth e-learning courses, сomplete with practice worksheets ɑnd recorded sessions fоr thorⲟugh revision.
Ꮤith math integrated perfectly іnto Singapore’s class settings tο benefit Ƅoth
instructors аnd students, committed math tuition magnifies tһese gains
by providing customized support fоr sustained accomplishment.
Tuition іn primary math iis crucial fоr PSLE preparation, as
іt introduces sophisticated techniques fοr handling non-routine рroblems thɑt stump ⅼots ᧐f prospects.
Tuition helps secondary pupils establish examination аpproaches, sսch аs timе allotment
for the 2 O Level mathematics papers, leading
t᧐ much better total efficiency.
Personalized junior college tuition helps link tһe gap from O Level tօ Α Level math,
mаking cеrtain trainees adjust to the enhanced rigor ɑnd
deepness required.
Ꭲhe originality of OMT hinges οn its tailored curriculum
that lines upp seamlessly ѡith MOE requirements ᴡhile introducing ingenious analytic techniques not ɡenerally highlighted іn classrooms.
OMT’ѕ on-line community proᴠides assistance leh,
ԝһere you ⅽan askk questions and boost your learning f᧐r
far better grades.
Team math tuition in Singapore promotes peer understanding,
encouraging students tⲟ push harder for premium exam results.
Feel free to surf t᧐ mу blog post; maths tuition online
maths tuition online
15 Oct 25 at 8:36 am
купить диплом с проводкой одной [url=frei-diplom3.ru]купить диплом с проводкой одной[/url] .
Diplomi_diKt
15 Oct 25 at 8:37 am
купить диплом с проводкой кого [url=http://frei-diplom2.ru]купить диплом с проводкой кого[/url] .
Diplomi_zrEa
15 Oct 25 at 8:37 am
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Получить исчерпывающие сведения – https://travelreviewsguide.com/blog/explore-the-charm-of-the-united-states-top-10-must-visit-places
JorgeKayaw
15 Oct 25 at 8:37 am
купить диплом механика [url=rudik-diplom9.ru]купить диплом механика[/url] .
Diplomi_lwei
15 Oct 25 at 8:39 am
купить диплом в красноярске [url=rudik-diplom13.ru]купить диплом в красноярске[/url] .
Diplomi_ekon
15 Oct 25 at 8:39 am
Там же вы найдете подробные правила, условия участия и
призовую структуру каждого мероприятия.
кэт казино зеркало
15 Oct 25 at 8:41 am
где купить диплом о среднем образование [url=https://rudik-diplom7.ru]где купить диплом о среднем образование[/url] .
Diplomi_fpPl
15 Oct 25 at 8:41 am
купить диплом механик техникум дипломы челябинск ком [url=https://frei-diplom9.ru/]купить диплом механик техникум дипломы челябинск ком[/url] .
Diplomi_nzea
15 Oct 25 at 8:41 am
В этой статье вы найдете познавательную и занимательную информацию, которая поможет вам лучше понять мир вокруг. Мы собрали интересные данные, которые вдохновляют на размышления и побуждают к действиям. Открывайте новую информацию и получайте удовольствие от чтения!
Что ещё? Расскажи всё! – https://purexculture.com/es/2023/11/17/sube-el-nivel
Danielwrill
15 Oct 25 at 8:43 am
Spot on with this write-up, I really believe that this site needs far more
attention. I’ll probably be back again to see more, thanks for the info!
nhà cái au88
15 Oct 25 at 8:43 am
купить диплом в чите [url=http://rudik-diplom2.ru]купить диплом в чите[/url] .
Diplomi_eapi
15 Oct 25 at 8:44 am
Keiran Lee
Brentsek
15 Oct 25 at 8:45 am
куплю диплом младшей медсестры [url=www.frei-diplom13.ru]www.frei-diplom13.ru[/url] .
Diplomi_yekt
15 Oct 25 at 8:45 am
натяжные потолки цена самара [url=www.natyazhnye-potolki-samara-2.ru]натяжные потолки цена самара[/url] .
natyajnie potolki samara_vmPi
15 Oct 25 at 8:47 am
купить диплом колледжа стоит пять плюс [url=http://frei-diplom9.ru]http://frei-diplom9.ru[/url] .
Diplomi_uhea
15 Oct 25 at 8:48 am
купить диплом в горно-алтайске [url=https://rudik-diplom7.ru/]https://rudik-diplom7.ru/[/url] .
Diplomi_cwPl
15 Oct 25 at 8:48 am
Hey there! This is my first comment here so I just wanted to give a quick shout out and tell
you I really enjoy reading through your articles.
Can you suggest any other blogs/websites/forums that cover the
same subjects? Thanks a ton!
BTC Income
15 Oct 25 at 8:49 am
Для игроков это означает, что они
могут беспрепятственно наслаждаться играми и акциями на платформе Vulcan.
вулкан старс вход
15 Oct 25 at 8:50 am
купить диплом о высшем образовании [url=https://rudik-diplom10.ru]купить диплом о высшем образовании[/url] .
Diplomi_ecSa
15 Oct 25 at 8:50 am