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!
melbet ru [url=http://melbetbonusy.ru]http://melbetbonusy.ru[/url] .
melbet_krOi
18 Oct 25 at 5:57 am
Согласен, замечательная мысль
support service [url=https://crwngreen.casino/]crowngreen[/url] is open anytime, 7 days a week, although the answers are brief. The welcome prize is great, and the bonus is available daily.
Irmaclums
18 Oct 25 at 6:00 am
В Краснодаре клиника «Детокс» предлагает услугу выезда нарколога на дом. Быстро, безопасно, анонимно.
Изучить вопрос глубже – [url=https://narkolog-na-dom-krasnodar26.ru/]частный нарколог на дом[/url]
DanielCaupe
18 Oct 25 at 6:03 am
mostbet online скачать [url=www.mostbet4182.ru]mostbet online скачать[/url]
mostbet_uz_ogkt
18 Oct 25 at 6:03 am
Hi, i think that i saw you visited my weblog thus i came to
“return the favor”.I’m trying to find things to enhance my web site!I suppose its ok
to use a few of your ideas!!
Spot Codrix 300
18 Oct 25 at 6:04 am
мелбет официальный сайт вход [url=melbetbonusy.ru]melbetbonusy.ru[/url] .
melbet_riOi
18 Oct 25 at 6:05 am
согласовать перепланировку квартиры цена [url=http://zakazat-proekt-pereplanirovki-kvartiry11.ru]http://zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_bpet
18 Oct 25 at 6:06 am
https://telegra.ph/Kupit-teplovizor-v-irkutske-sajtong-10-13-3
JesseHow
18 Oct 25 at 6:07 am
перепланировка квартиры согласование [url=https://soglasovanie-pereplanirovki-kvartiry11.ru/]soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _mlMi
18 Oct 25 at 6:08 am
проект перепланировки квартиры в москве [url=https://proekt-pereplanirovki-kvartiry16.ru/]proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_qfMl
18 Oct 25 at 6:08 am
Nіce slot bro!
link slot gacor
18 Oct 25 at 6:09 am
перепланировка услуги [url=soglasovanie-pereplanirovki-kvartiry14.ru]soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _xaEl
18 Oct 25 at 6:11 am
Клиника «Похмельная служба» в Нижнем Новгороде предлагает комплексное лечение запоя с использованием капельницы. Наши специалисты проводят диагностику и назначают индивидуальный план лечения.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-nizhnij-novgorod11.ru/]врач вывод из запоя[/url]
TerrellOwelf
18 Oct 25 at 6:11 am
Oi oi, Singapore folks, math proves likely the extremely crucial primary topic,
fostering innovation fߋr issue-resolving t᧐ groundbreaking careers.
Avoid tаke lightly lah, link ɑ excellent Junior
College ѡith math excellence tο guarantee superior Ꭺ Levels marks аs
ԝell as effortless shifts.
Parents, fear tһe difference hor, math foundation proves critical аt Junior
College fοr comprehending іnformation, crucial іn current online economy.
National Junior College, ɑs Singapore’s pioneering juniokr
college, οffers unequaled chances fοr intellectual аnd
leadership growth іn a historic setting. Ӏts boarding program ɑnd гesearch centers foster sеlf-reliance and development аmongst varied trainees.
Programs in arts, sciences, ɑnd liberal arts, including electives, motivate deep expedition ɑnd quality.
Global collaborations ɑnd exchanges broaden horizons аnd develop networks.
Alumni lead іn diffeгent fields, reflecting tһe college’s
enduring effect on nation-building.
Ⴝt. Andrew’s Junior College accepts Anglican values tⲟ promote holistic growth,
cultivating principled people ѡith robust character traits tһrough a blend of spiritual assistance, scholastic
pursuit, ɑnd community involvement іn a warm and inclusive
environment. Ꭲhe college’s contemporary features, consisting οf interactive classrooms, sports complexes,
ɑnd imaginative arts studios, assist іn excellence аcross scholastic disciplines, sports programs tһɑt emphasize physical fitness ɑnd reasonable play, аnd
artisttic ventures tһаt encourage self-expression ɑnd development.
Community service efforts, ѕuch as volunteer partnerships ѡith local companies ɑnd
outreach projects, impart compassion, social responsibility, аnd a sense
of purpose, improving students’ academic journeys.
Ꭺ diverse variety of co-curricular activities, from debate societies to musical ensembles, cultivates teamwork, management skills, ɑnd personal discovery,
allowing every student to shine in thеir chosen areas.
Alumni оf Ꮪt. Andrew’s Junior College regularly emerge ɑs ethical, resistant leaders who maқе siɡnificant contributions tߋ society, reflecting tһe institution’ѕ extensive influence օn developing weⅼl-rounded, valᥙe-driven people.
Оh dear, lacking strong math іn Junior College, evеn tоp institution children could stumble in hіgh school
equations, tһerefore build tһat prοmptly leh.
Hey hey, Singapore folks, math гemains pеrhaps
the extremely important primary subject, promoting creativity іn challenge-tackling
tο innovative jobs.
Ɗo not tɑke lightly lah, link ɑ excellent Junior College ⲣlus maths superiority tⲟ ensure elevated
А Levels results and effortless сhanges.
Oi oi,Singapore moms ɑnd dads, maths proves likely tһe extremely essential primary subject, promoting innovation fօr
challenge-tackling іn creative careers.
Listen սp, Singapore folks, math гemains pгobably the most crucial primary subject, fostering creativity fοr
problem-solving in innovative careers.
Ɗon’t mess ar᧐und lah, combine a excellent Junior College alongside math excellence tο
ensure superior Ꭺ Levels results ρlus smooth changes.
Kiasu revision timetables ensure balanced A-level prep.
Listen սp, steady pom pi pі, mathematics proves аmong in the һighest
topics аt Junior College, establishing groundwork f᧐r A-Level calculus.
mʏ webpage: Jurong Pioneer Junior College
Jurong Pioneer Junior College
18 Oct 25 at 6:13 am
http://tadalafiloexpress.com/# tadalafilo
MickeySum
18 Oct 25 at 6:13 am
https://t.me/s/Official_1xbet_1xbet/1619
Josephadvem
18 Oct 25 at 6:14 am
https://t.me/Official_1xbet_1xbet/1755
Josephadvem
18 Oct 25 at 6:15 am
Профессионалы буквально всё сделают за вас, а
вы сможете заняться своими делами, отдохнуть или же при необходимости уладить важные дела по работе.
уборка квартир в центре спб
18 Oct 25 at 6:17 am
купить диплом в воткинске [url=http://www.rudik-diplom12.ru]купить диплом в воткинске[/url] .
Diplomi_yvPi
18 Oct 25 at 6:17 am
I was curious if you ever considered changing the page layout of your website?
Its very well written; I love what youve got to
say. But maybe you could a little more in the way of content so people could connect
with it better. Youve got an awful lot of text
for only having 1 or two pictures. Maybe you
could space it out better?
BETFLIK45
18 Oct 25 at 6:17 am
стоимость проекта перепланировки квартиры [url=http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_odPt
18 Oct 25 at 6:17 am
Сливы курсов по подготовке к ЕГЭ русский https://courses-ege.ru
courses-ege-314
18 Oct 25 at 6:18 am
https://t.me/s/Official_1xbet_1xbet/1718
Josephadvem
18 Oct 25 at 6:20 am
https://t.me/Official_1xbet_1xbet/1612
Josephadvem
18 Oct 25 at 6:21 am
мелбет вход [url=https://melbetbonusy.ru]https://melbetbonusy.ru[/url] .
melbet_izOi
18 Oct 25 at 6:21 am
melbet букмекерская контора [url=http://melbetbonusy.ru]melbet букмекерская контора[/url] .
melbet_gsOi
18 Oct 25 at 6:25 am
сколько стоит узаконить перепланировку в бти [url=https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru]https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_joet
18 Oct 25 at 6:25 am
Cialis Preisvergleich Deutschland [url=https://potenzvital.com/#]cialis kaufen[/url] PotenzVital
GeorgeHot
18 Oct 25 at 6:27 am
Hi there! This post could not be written any better!
Looking at this article reminds me of my previous roommate!
He always kept preaching about this. I am going to send this article to him.
Pretty sure he’s going to have a great read. Thank you for sharing!
派遣 物流
18 Oct 25 at 6:29 am
согласование перепланировки квартиры в москве цена [url=https://www.proekt-pereplanirovki-kvartiry16.ru]https://www.proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_whMl
18 Oct 25 at 6:29 am
Great post. I was checking constantly this blog and I’m impressed!
Very useful info particularly the last part 🙂 I care for such info a lot.
I was seeking this particular information for a very long
time. Thank you and good luck.
https://intan3dshd6.snack-blog.com/profile
18 Oct 25 at 6:30 am
Estou alucinado com BR4Bet Casino, vibra como um farol em alto-mar. O leque do cassino e um brilho de delicias. oferecendo lives que acendem como fogueiras. O time do cassino e digno de um faroleiro. disponivel por chat ou e-mail. As transacoes sao simples como uma luz. mas mais recompensas fariam o coracao brilhar. Em resumo, BR4Bet Casino vale explorar esse cassino ja para os viciados em emocoes de cassino! Como extra o design e um espetaculo visual iluminado. dando vontade de voltar como uma chama eterna.
30|
quirkyblazepenguin3zef
18 Oct 25 at 6:31 am
https://tadalafiloexpress.shop/# tadalafilo
MickeySum
18 Oct 25 at 6:31 am
Ich bin total begeistert von PlayJango Casino, es bietet ein Casino-Abenteuer, das wie ein Regenbogen funkelt. Die Auswahl im Casino ist ein echtes Spektakel, mit Casino-Spielen, die fur Kryptowahrungen optimiert sind. Der Casino-Kundenservice ist wie ein Leuchtfeuer, mit Hilfe, die wie ein Funke spruht. Casino-Zahlungen sind sicher und reibungslos, trotzdem mehr Freispiele im Casino waren ein Volltreffer. Insgesamt ist PlayJango Casino ein Casino, das man nicht verpassen darf fur Fans von Online-Casinos! Nebenbei die Casino-Navigation ist kinderleicht wie ein Windhauch, den Spielspa? im Casino in die Hohe treibt.
playjango deposit bonus code|
fizzypanda4zef
18 Oct 25 at 6:32 am
В клинике «Частный Медик 24» пациенту гарантирована анонимность и внимательное отношение при лечении запоя.
Детальнее – [url=https://vyvod-iz-zapoya-v-stacionare23.ru/]вывод из запоя в стационаре анонимно[/url]
Francisitedo
18 Oct 25 at 6:34 am
melbet вход с мобильного зеркало [url=https://melbetbonusy.ru]melbet вход с мобильного зеркало[/url] .
melbet_gaOi
18 Oct 25 at 6:35 am
сколько стоит оформить перепланировку квартиры в бти [url=http://zakazat-proekt-pereplanirovki-kvartiry11.ru/]http://zakazat-proekt-pereplanirovki-kvartiry11.ru/[/url] .
zakazat proekt pereplanirovki kvartiri_qtet
18 Oct 25 at 6:35 am
одноразовые номера
Ricardopam
18 Oct 25 at 6:38 am
согласование. [url=https://soglasovanie-pereplanirovki-kvartiry11.ru]https://soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _deMi
18 Oct 25 at 6:40 am
согласование перепланировок [url=https://soglasovanie-pereplanirovki-kvartiry14.ru/]https://soglasovanie-pereplanirovki-kvartiry14.ru/[/url] .
soglasovanie pereplanirovki kvartiri _kpEl
18 Oct 25 at 6:42 am
заказать перепланировку [url=proekt-pereplanirovki-kvartiry16.ru]proekt-pereplanirovki-kvartiry16.ru[/url] .
proekt pereplanirovki kvartiri_jpMl
18 Oct 25 at 6:42 am
Прием СМС
Ricardopam
18 Oct 25 at 6:42 am
https://t.me/Official_1xbet_1xbet/1811
Josephadvem
18 Oct 25 at 6:43 am
https://t.me/Official_1xbet_1xbet/1732
Josephadvem
18 Oct 25 at 6:44 am
linebet apps
linebet login bd mobile
18 Oct 25 at 6:44 am
Since the admin of this web page is working, no question very soon it will be famous, due to its
quality contents.
hm88
18 Oct 25 at 6:45 am
Hello this is kind of of off topic but I was wondering if blogs
use WYSIWYG editors or if you have to manually code
with HTML. I’m starting a blog soon but have no coding experience so I wanted to get guidance from someone with experience.
Any help would be enormously appreciated!
jepang88
18 Oct 25 at 6:46 am
Estou pirando com SpeiCasino, tem uma vibe de jogo tao reluzente quanto uma supernova. As opcoes de jogo no cassino sao ricas e brilhantes como estrelas, incluindo jogos de mesa de cassino com um toque cosmico. O servico do cassino e confiavel e brilha como uma galaxia, garantindo suporte de cassino direto e sem buracos negros. Os pagamentos do cassino sao lisos e blindados, mas queria mais promocoes de cassino que explodem como estrelas. Na real, SpeiCasino e o point perfeito pros fas de cassino para os amantes de cassinos online! De lambuja o design do cassino e um espetaculo visual intergalactico, eleva a imersao no cassino a um nivel cosmico.
app spei|
zapfunkyferret3zef
18 Oct 25 at 6:47 am
перепланировка квартиры бти цена [url=https://www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]https://www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_qoPt
18 Oct 25 at 6:48 am
программы https://softprogram-free.ru/
Maximodaf
18 Oct 25 at 6:48 am