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!
https://t.me/s/ud_StaKe
MichaelPione
2 Nov 25 at 4:16 am
top 10 seo [url=http://reiting-seo-agentstv.ru]http://reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_ydsa
2 Nov 25 at 4:16 am
http://ukmedsguide.com/# non-prescription medicines UK
Haroldovaph
2 Nov 25 at 4:16 am
купить диплом техникума в казани [url=frei-diplom10.ru]купить диплом техникума в казани[/url] .
Diplomi_vdEa
2 Nov 25 at 4:17 am
В Ростове-на-Дону мы используем только сертифицированные препараты и современные методики, что обеспечивает высокую эффективность лечения.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-rostov111.ru/]срочный вывод из запоя в ростове-на-дону[/url]
AltonPoula
2 Nov 25 at 4:17 am
https://t.me/s/uD_dRagonMOneY
MichaelPione
2 Nov 25 at 4:18 am
сео агентства [url=https://reiting-seo-agentstv.ru/]https://reiting-seo-agentstv.ru/[/url] .
reiting seo agentstv_tjsa
2 Nov 25 at 4:19 am
seo продвижение рейтинг компаний [url=http://www.reiting-seo-kompaniy.ru]seo продвижение рейтинг компаний[/url] .
reiting seo kompanii_acon
2 Nov 25 at 4:20 am
купить диплом в канске [url=http://rudik-diplom13.ru]купить диплом в канске[/url] .
Diplomi_qkon
2 Nov 25 at 4:20 am
http://www.google.se/url?q=https://www.lnrprecision.com/
MelvinBop
2 Nov 25 at 4:20 am
лидеры seo продвижения веб студия [url=www.reiting-seo-agentstv.ru]www.reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_flsa
2 Nov 25 at 4:24 am
купить бланк диплома [url=http://rudik-diplom4.ru/]купить бланк диплома[/url] .
Diplomi_liOr
2 Nov 25 at 4:25 am
Цена на обработка от клещей адекватная, результат супер.
дезинсекция
Wernermog
2 Nov 25 at 4:25 am
купить диплом о высшем образовании с занесением в реестр в красноярске [url=https://frei-diplom5.ru]купить диплом о высшем образовании с занесением в реестр в красноярске[/url] .
Diplomi_ukPa
2 Nov 25 at 4:26 am
Hi there! I could have sworn I’ve been to this website before but after looking at a
few of the posts I realized it’s new to me. Anyways,
I’m certainly pleased I discovered it and I’ll be book-marking it and checking back frequently!
swimming pool swimmingpool kaufen swimmingpool stahlwandbecken
2 Nov 25 at 4:27 am
Ich bin fasziniert von Cat Spins Casino, es ladt zu spannenden Spielen ein. Das Angebot an Titeln ist riesig, mit eleganten Tischspielen. 100 % bis zu 500 € mit Freispielen. Der Support ist effizient und professionell. Gewinne kommen ohne Verzogerung, aber mehr Promo-Vielfalt ware toll. Am Ende, Cat Spins Casino garantiert langanhaltenden Spa?. Zusatzlich ist das Design modern und einladend, was jede Session spannender macht. Ein weiteres Highlight die breiten Sportwetten-Angebote, die Gemeinschaft starken.
http://www.catspinsbonus.com|
sonicpowerik6zef
2 Nov 25 at 4:27 am
продвижение сайтов по россии [url=https://www.reiting-seo-agentstv.ru]https://www.reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_hysa
2 Nov 25 at 4:28 am
canadian pharmacy online viagra
canadian pharmacy online viagra
2 Nov 25 at 4:28 am
рейтинг seo компаний [url=www.reiting-seo-kompaniy.ru/]рейтинг seo компаний[/url] .
reiting seo kompanii_oson
2 Nov 25 at 4:29 am
seo продвижение сайта россия [url=http://reiting-seo-agentstv.ru/]seo продвижение сайта россия[/url] .
reiting seo agentstv_jtsa
2 Nov 25 at 4:29 am
фирмы по продвижению сайтов [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru]https://reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_rdKt
2 Nov 25 at 4:30 am
купить диплом с реестром о высшем образовании [url=https://www.frei-diplom4.ru]купить диплом с реестром о высшем образовании[/url] .
Diplomi_kzOl
2 Nov 25 at 4:30 am
https://t.me/s/uD_ggbET
MichaelPione
2 Nov 25 at 4:31 am
https://t.me/s/official_1win_aviator/51
RouletteRogue
2 Nov 25 at 4:32 am
купить диплом прораба [url=https://www.rudik-diplom13.ru]купить диплом прораба[/url] .
Diplomi_tpon
2 Nov 25 at 4:34 am
Awesome post.
udintogel
2 Nov 25 at 4:34 am
диплом медсестры с аккредитацией купить [url=https://frei-diplom14.ru]диплом медсестры с аккредитацией купить[/url] .
Diplomi_kvoi
2 Nov 25 at 4:35 am
https://t.me/official_1win_aviator/90
LuckyBandit
2 Nov 25 at 4:35 am
услуги seo компании [url=http://reiting-seo-agentstv.ru/]услуги seo компании[/url] .
reiting seo agentstv_nwsa
2 Nov 25 at 4:36 am
Hurrah! After all I got a website from where I can genuinely get valuable facts
concerning my study and knowledge.
b612 mod apk vip unlocked
2 Nov 25 at 4:37 am
сео фирмы [url=https://www.reiting-seo-kompaniy.ru]сео фирмы[/url] .
reiting seo kompanii_uron
2 Nov 25 at 4:39 am
купить диплом в биробиджане [url=https://www.rudik-diplom3.ru]купить диплом в биробиджане[/url] .
Diplomi_qsei
2 Nov 25 at 4:39 am
диплом о среднем образовании купить легально [url=https://www.frei-diplom2.ru]https://www.frei-diplom2.ru[/url] .
Diplomi_yeEa
2 Nov 25 at 4:40 am
мостбеи [url=https://mostbet12033.ru/]https://mostbet12033.ru/[/url]
mostbet_kg_nmpa
2 Nov 25 at 4:41 am
купить диплом в чапаевске [url=www.rudik-diplom5.ru/]купить диплом в чапаевске[/url] .
Diplomi_gzma
2 Nov 25 at 4:42 am
Thank you for another wonderful post. Where else could anyone get
that type of info in such an ideal means of writing?
I have a presentation next week, and I’m at the look for such information.
site
2 Nov 25 at 4:42 am
рейтинг seo фирм [url=https://reiting-seo-kompaniy.ru/]https://reiting-seo-kompaniy.ru/[/url] .
reiting seo kompanii_pion
2 Nov 25 at 4:43 am
мостбет мобильная версия скачать [url=mostbet12034.ru]mostbet12034.ru[/url]
mostbet_kg_ylPr
2 Nov 25 at 4:43 am
russian seo services [url=https://www.reiting-seo-agentstv.ru]https://www.reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_xwsa
2 Nov 25 at 4:43 am
Мы обеспечиваем полную поддержку на всех этапах лечения в Ростове-на-Дону, включая реабилитацию и профилактику рецидивов.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-rostov235.ru/]вывод из запоя недорого[/url]
Richardbit
2 Nov 25 at 4:45 am
Alas, lacking robust math аt Junior College, no matter
tօp institution children ⅽould stumble wіth next-level equations,
therefore cultivate thаt now leh.
Eunoia Junior College represents contemporary development іn education, ѡith іts
һigh-rise campus integrating community аreas for
collective learning ɑnd development. Τhe college’s emphasis оn lovely
thinking promotes intellectual curiosity ɑnd goodwill, supported by dynamic
programs іn arts, sciences, and leadership.
Modern centers, including carrying оut arts venues, mɑke it possibⅼe for trainees t᧐ check oᥙt passions and develop skills holistically.
Partnerships ѡith renowned organizations
offer enhancing chances for resesarch аnd worldwide exposure.
Trainees Ьecome thoughtful leaders, prepared t᧐ contribute favorably to a diverse ᴡorld.
Jurong Pioneer Junior College, developed tһrough the thoughtful merger ᧐f Jurong Junior College and Pioneer Junior
College, delivers ɑ progressive and future-oriented education tһat positions
a special focus օn China preparedness, international service acumen,
аnd cross-cultural engagement tо prepare students for flourishing in Asia’ѕ vibrant
economic landscape. Tһе college’ѕ dual schools
arе outfitted witfh modern, versatile facilities consisting ᧐f specialized
commerce simulation spaces, science innovation labs, аnd arts ateliers, аll designed
to foster useful skills, creativity, аnd interdisciplinary
knowing. Enhancing academicc programs аre complemented
ƅy global cooperations, ѕuch as joint projects ᴡith Chinese universities ɑnd cultural immersion trips, ԝhich improve students’ linguistic proficiency ɑnd worldwide outlook.
А helpful аnd inclusive neighborhood environment encourages strength ɑnd leadership advancement tһrough a large range ⲟf co-curricular activities,
from entrepreneurship ϲlubs to sports teams tһat promote team
effort ɑnd perseverance. Graduates οf Jurong Pioneer Junior
College arе remarkably ᴡell-prepared foг competitive careers, embodying thе
values of care, continuous enhancement, ɑnd innovation tһat
define the organization’s forward-lօoking principles.
Folks, fear tһe gap hor, math groundwork remains critical at Junior College іn grasping data, essential in modern online economy.
Goodness, no matter thoᥙgh school is atas, math serves аs the decisive topic f᧐r developing confidence ᴡith figures.
Wah, maths іs the base stone in primary learning,
aiding kids fօr dimensional reasoning fօr architecture routes.
Ⲟһ man, even if establishment proves atas, maths serves аѕ the make-or-break subject to building assurance ѡith numbers.
Alas, primary math teaches everyday implementations including financial planning, ѕo mɑke sսre your kid getѕ thаt гight
starting early.
Eh eh, calm pom ⲣi pі, mathematics is paгt fr᧐m
thе top disciploines at Junior College, establishing base іn A-Level hiɡher
calculations.
Math equips ʏoս forr statistical analysis іn social sciences.
Avoid taкe lightly lah, link а gooɗ Junior College ρlus maths superiority tⲟ ensure elevated Α Levels results plus smooth shifts.
Look into mʏ web site … jc 2 math tuition
jc 2 math tuition
2 Nov 25 at 4:45 am
discount pharmacies in Ireland [url=https://irishpharmafinder.shop/#]affordable medication Ireland[/url] discount pharmacies in Ireland
Hermanengam
2 Nov 25 at 4:45 am
I’m not sure where you are getting your info, but good
topic. I needs to spend some time learning much more
or understanding more. Thanks for magnificent info I was looking for this info
for my mission.
certified public accountant
2 Nov 25 at 4:45 am
Excellent post. I used to be checking continuously this weblog and I’m inspired!
Very helpful info specially the remaining section 🙂 I maintain such information a
lot. I used to be seeking this certain info for a very lengthy
time. Thank you and good luck.
web design
2 Nov 25 at 4:46 am
Ich bin beeindruckt von SpinBetter Casino, es liefert ein Abenteuer voller Energie. Das Angebot an Spielen ist phanomenal, mit aufregenden Sportwetten. Der Support ist 24/7 erreichbar, immer parat zu assistieren. Die Transaktionen sind verlasslich, dennoch zusatzliche Freispiele waren ein Highlight. Alles in allem, SpinBetter Casino garantiert hochsten Spa? fur Spieler auf der Suche nach Action ! Zusatzlich die Plattform ist visuell ein Hit, fugt Magie hinzu. Besonders toll die schnellen Einzahlungen, die Vertrauen schaffen.
spinbettercasino.de|
ChillgerN4zef
2 Nov 25 at 4:47 am
продвижение сайтов сео топ [url=www.reiting-seo-agentstv.ru]продвижение сайтов сео топ[/url] .
reiting seo agentstv_zesa
2 Nov 25 at 4:47 am
https://aussiemedshubau.shop/# online pharmacy australia
Haroldovaph
2 Nov 25 at 4:48 am
affordable medication Ireland
Edmundexpon
2 Nov 25 at 4:49 am
как купить легальный диплом [url=https://frei-diplom2.ru]https://frei-diplom2.ru[/url] .
Diplomi_ioEa
2 Nov 25 at 4:51 am
russian seo [url=www.reiting-seo-agentstv.ru]www.reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_mlsa
2 Nov 25 at 4:52 am