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://vyvod-iz-zapoya-petrozavodsk0.ru/]анонимный вывод из запоя в петрозаводске[/url]
PatrickSlode
24 Oct 25 at 8:50 pm
1 xbet giri? [url=https://www.1xbet-7.com]https://www.1xbet-7.com[/url] .
1xbet_ngol
24 Oct 25 at 8:51 pm
[url=https://1deposit.net/slots/]1 dollar deposit[/url]
Charlessup
24 Oct 25 at 8:51 pm
купить диплом в армавире [url=https://rudik-diplom2.ru/]купить диплом в армавире[/url] .
Diplomi_ztpi
24 Oct 25 at 8:53 pm
https://t.me/s/bs_1xbet/44
https://t.me/s/bs_1xbet/47
24 Oct 25 at 8:53 pm
https://t.me/bs_1xbet/34
https://t.me/s/bs_1xbet/15
24 Oct 25 at 8:55 pm
https://yoursocialpeople.com/story5919778/1xbet-promo-code-free-spins-egypt
ZacharyGip
24 Oct 25 at 8:56 pm
certainly like your website however you have to
test the spelling on several of your posts. Several
of them are rife with spelling issues and I in finding it very troublesome to inform the
truth on the other hand I’ll certainly come back again.
turkish visa australia
24 Oct 25 at 8:57 pm
buildbrand.bond – Love the color scheme; it’s subtle yet impactful.
Nathanael Glee
24 Oct 25 at 8:57 pm
Oh dear, mіnus robust math during Junior
College, no matter prestigious school kids сould falter with next-level equations, ѕo
cultivate іt immediateⅼy leh.
Catholic Junior College οffers ɑ values-centered education rooted
іn compassion ɑnd fɑct, creating an inviting neighborhood where trainees flourish
academically аnd spiritually. Wіtһ a concentrate on holistic growth, the college offerѕ robust programs
in liberal arts аnd sciences, assisted by caring coaches
ѡho motivate l᧐ng-lasting learning. Its dynamic со-curricular scene,including sports
аnd arts, promotes teamwork and self-discovery in а supportive environment.
Opportunities f᧐r neighborhood service ɑnd worldwide exchanges build empathy аnd global
viewpoints amongst trainees. Alumni typically Ьecome empathetic leaders, geared սⲣ to makе meaningful contributions tⲟ society.
Millennia Institute stands аpart with its unique three-yeɑr pre-university
pathway leading tⲟ the GCE A-Level evaluations, offering
versatile аnd tһorough study choices іn commerce, arts,
аnd sciences customized to accommodate
а vared variety оf learners and tһeir unique aspirations.
Аѕ a centralized institute, іt offers tailored assistance and
support ɡroup, consisting օf dedicated scholastic consultants аnd counseling services, tⲟ ensure evеry trainee’s
holistic advancement аnd academic success іn a inspiring environment.
Ꭲhе institute’s cutting edge facilities, ѕuch as digital learning hubs,
multimedia resource centers, ɑnd collective workspaces, create an engaging platform fоr
ingenious teaching ɑpproaches ɑnd hands-on projects tһat bridge
theory ԝith practical application. Τhrough strong market partnerships, students
access real-ᴡorld experiences ⅼike internships, workshops ѡith professionals, аnd
scholarship opportunities tһɑt boost their employability аnd career readiness.
Alumni frоm Millennia Institute regularly accomplish success іn highеr education аnd
professional arenas, reflecting tһe institution’s unwavering dedication tto promoting
lifelong knowing, adaptability, ɑnd individual empowerment.
Ᏼesides beyond institution amenities, emphasize оn math for stop common mistakes
ⅼike careless mistakes іn tests.
Parents, kiasu mode оn lah, strong primary mathematichs leads іn superior science
understanding as well аs tech dreams.
Goodness, no matter tһough school iѕ high-end, maths is tһe decisive subject fߋr building poise гegarding figures.
Aiyah, primary math teaches practical սses sucһ аs money management, so guarantee youг
child ɡets tһis гight from young.
Aiyo, withoսt strong maths in Junior College, еven toр school youngsters couⅼd falter ɑt secondary algebra, tһus build tһiѕ immeԀiately leh.
Math at A-levels іs ⅼike a puzzle; solving іt builds confidence fߋr life’ѕ challenges.
Eh eh, calm pom рi pi, mathematics iѕ part in thе leading topics ɑt Junior
College, laying groundwork іn Α-Level calculus.
Ꭺpart from school facilities, emphasize ᥙpon maths for ѕtop
common pitfalls including sloppy mistakes ⅾuring tests.
Mums аnd Dads, competitive style on lah, robust primary mathematics guides fⲟr better STEM understanding
ɑs weⅼl aѕ engineering goals.
Mʏ web blog – secondary school singapore
secondary school singapore
24 Oct 25 at 8:57 pm
köp receptfria potensmedel online: billig Viagra Sverige – Sildenafil-tabletter pris
Jesuskax
24 Oct 25 at 8:57 pm
купить диплом железнодорожника [url=www.rudik-diplom11.ru/]купить диплом железнодорожника[/url] .
Diplomi_pqMi
24 Oct 25 at 8:57 pm
Я извиняюсь, но, по-моему, Вы ошибаетесь. Давайте обсудим это. Пишите мне в PM, пообщаемся.
The application has almost all identical parameters, what and web version, including training consumables and support [url=https://web-binomo.org/binomo-sign-in-secure-online-trading-access/]https://web-binomo.org/binomo-sign-in-secure-online-trading-access/[/url].
Peggyskype
24 Oct 25 at 8:59 pm
https://t.me/bs_1xbet/45
https://t.me/bs_1xbet/45
24 Oct 25 at 9:00 pm
+905516067299 fetoden dolayi ulkeyi terk etti
AHMET ENGİN
24 Oct 25 at 9:00 pm
https://t.me/bs_1xbet/13
https://t.me/bs_1xbet/49
24 Oct 25 at 9:00 pm
1xbet com giri? [url=https://1xbet-giris-3.com/]https://1xbet-giris-3.com/[/url] .
1xbet giris_jwMi
24 Oct 25 at 9:00 pm
leanneslifechangingfairies.com – Great combination of visuals and text; looks professional yet friendly.
Ezra Yeh
24 Oct 25 at 9:01 pm
купить диплом в шадринске [url=https://rudik-diplom6.ru]купить диплом в шадринске[/url] .
Diplomi_glKr
24 Oct 25 at 9:01 pm
What’s Going down i am new to this, I stumbled upon this I’ve discovered It absolutely
useful and it has aided me out loads. I am hoping to contribute & help different customers like its aided me.
Great job.
how to make bomb
24 Oct 25 at 9:01 pm
медсестра которая купила диплом врача [url=www.frei-diplom13.ru]www.frei-diplom13.ru[/url] .
Diplomi_drkt
24 Oct 25 at 9:02 pm
1xbet giri? [url=http://1xbet-7.com]1xbet giri?[/url] .
1xbet_caol
24 Oct 25 at 9:03 pm
1xbet giris [url=http://1xbet-9.com]1xbet giris[/url] .
1xbet_pnSn
24 Oct 25 at 9:03 pm
1x bet [url=www.1xbet-4.com/]www.1xbet-4.com/[/url] .
1xbet_ajol
24 Oct 25 at 9:03 pm
1xbet ?ye ol [url=https://1xbet-9.com/]https://1xbet-9.com/[/url] .
1xbet_xkSn
24 Oct 25 at 9:05 pm
которые воспитанны на обычном Фене ! https://melitopolqa.ru Почему больше не берете?
Louismes
24 Oct 25 at 9:05 pm
1xbet g?ncel adres [url=https://www.1xbet-4.com]https://www.1xbet-4.com[/url] .
1xbet_ktol
24 Oct 25 at 9:05 pm
http://mediuomo.com/# farmaci per potenza maschile
Hermanereli
24 Oct 25 at 9:06 pm
is? bahisl?r may ?yl?nc? formas? olun, [url=http://aj1716.online/zW4vGtaAbvMs30Jp0jeKrhR69OWCItcWAME52Ntcky66zDHx-3AnWPMMqgllaaO-KhUPA5gefS_7rlQbpF15COnOzpWANAJtlW6PosS7CImE2IhI-n81ycFL6ZWwis_-iQran0hgQ5HIwGNxXZJFUr_2hhZkypb4n9IfkdsfA9xBKEZC_iC_WQHyPkV-fo-2P3z7J7kxOhhdjhmBAbDyIWGoF1Bb1cPgKzZxe_dsbKJyHwfDgWbyg1GnCydek9wpPE-A0RLM81nq9Chmi2Po_xQ6CvtaxROACo5PJJAL2mMJ89LOA14r-dP2t3e_4DzMtVhBEnJuXhLwPv7GplFlw69Jr?DC=WZ&u=mostbet-azerbaijan.website.yandexcloud.net]http://aj1716.online/zW4vGtaAbvMs30Jp0jeKrhR69OWCItcWAME52Ntcky66zDHx-3AnWPMMqgllaaO-KhUPA5gefS_7rlQbpF15COnOzpWANAJtlW6PosS7CImE2IhI-n81ycFL6ZWwis_-iQran0hgQ5HIwGNxXZJFUr_2hhZkypb4n9IfkdsfA9xBKEZC_iC_WQHyPkV-fo-2P3z7J7kxOhhdjhmBAbDyIWGoF1Bb1cPgKzZxe_dsbKJyHwfDgWbyg1GnCydek9wpPE-A0RLM81nq9Chmi2Po_xQ6CvtaxROACo5PJJAL2mMJ89LOA14r-dP2t3e_4DzMtVhBEnJuXhLwPv7GplFlw69Jr?DC=WZ&u=mostbet-azerbaijan.website.yandexcloud.net[/url] we understand that it should never be excessive or harmful.
Antoinehal
24 Oct 25 at 9:07 pm
купить диплом в волгодонске [url=http://www.rudik-diplom11.ru]купить диплом в волгодонске[/url] .
Diplomi_tfMi
24 Oct 25 at 9:07 pm
купить диплом в балашове [url=rudik-diplom2.ru]купить диплом в балашове[/url] .
Diplomi_gcpi
24 Oct 25 at 9:08 pm
купить диплом в кузнецке [url=http://www.rudik-diplom6.ru]http://www.rudik-diplom6.ru[/url] .
Diplomi_apKr
24 Oct 25 at 9:09 pm
диплом медицинского колледжа купить в [url=https://frei-diplom12.ru]https://frei-diplom12.ru[/url] .
Diplomi_ogPt
24 Oct 25 at 9:09 pm
Kaizenaire.com unites Singapore’ѕ finest promotions, placing іtself ɑs the Ьest internet
site fοr deals ɑnd occasions.
Singaporeans’ enjoyment fօr deals iѕ palpable in Singapore’s busy shopping heaven.
Singaporeans tаke ɑ break witһ medspa days at lavish resorts, ɑnd bear in mind to stay upgraded օn Singapore’s neweѕt promotions
ɑnd shopping deals.
Ling Wu mɑkes exotic natural leather bags, loved Ƅy luxury sekers іn Singapore f᧐r tһeir artisanal top quality аnd exotic
products.
DBS, а leading banking organization іn Singapore lah, gives ɑ variety of monetary solutions fгom electronic banking to wealth management one, whicһ Singaporeans adore for their smooth combination гight into daily life siɑ.
Jumbo Seafood wows restaurants wіth chili crab and fish ɑnd
shellfish dishes, cherished ƅy Singaporeans for fresh catches and renowned black pepper crab experiences.
Singaporeans, tіme to level uup ʏouг shopping game lah, check
Kaizenaire.ϲom for the lɑtest deals mah.
My page; league օf legends promotions [lifestyle.dailydispatcher.com]
lifestyle.dailydispatcher.com
24 Oct 25 at 9:10 pm
bahis siteler 1xbet [url=http://www.1xbet-giris-3.com]http://www.1xbet-giris-3.com[/url] .
1xbet giris_ueMi
24 Oct 25 at 9:12 pm
was there a casino on the titanic (Louann) online usa all sites, best
$10 deposit bonus new zealand and no deposit slots usa, or 100 australia
casino free keep online spin winnings
Louann
24 Oct 25 at 9:13 pm
диплом техникума с отличием купить [url=https://frei-diplom11.ru/]диплом техникума с отличием купить[/url] .
Diplomi_ozsa
24 Oct 25 at 9:14 pm
купить диплом в мытищах [url=http://rudik-diplom2.ru]купить диплом в мытищах[/url] .
Diplomi_nopi
24 Oct 25 at 9:14 pm
https://confiafarmacia.shop/# Confia Farmacia
JamesSlilk
24 Oct 25 at 9:15 pm
купить диплом техникума в пензе [url=http://frei-diplom12.ru]купить диплом техникума в пензе[/url] .
Diplomi_rrPt
24 Oct 25 at 9:15 pm
It’s fantastic that you are getting thoughts from this article as well as from our argument made at this place.
estate
24 Oct 25 at 9:16 pm
1xbet tr [url=www.1xbet-7.com/]1xbet tr[/url] .
1xbet_scol
24 Oct 25 at 9:16 pm
It’s really a nice and helpful piece of information. I’m happy that you shared
this helpful information with us. Please keep us informed like
this. Thank you for sharing.
how to make antrax
24 Oct 25 at 9:18 pm
birxbet [url=https://1xbet-9.com/]https://1xbet-9.com/[/url] .
1xbet_mxSn
24 Oct 25 at 9:18 pm
1xbet yeni adresi [url=https://1xbet-4.com]https://1xbet-4.com[/url] .
1xbet_hxol
24 Oct 25 at 9:18 pm
When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time
a comment is added I get four emails with the same comment.
Is there any way you can remove me from that service?
Appreciate it!
kitchen exhaust singapore
24 Oct 25 at 9:20 pm
где купить диплом техникума старого образца [url=https://www.frei-diplom12.ru]где купить диплом техникума старого образца[/url] .
Diplomi_dbPt
24 Oct 25 at 9:20 pm
https://dzen.ru/a/aPRXjPraMEja6Ols
PatrickHob
24 Oct 25 at 9:20 pm
birxbet giri? [url=www.1xbet-giris-3.com]www.1xbet-giris-3.com[/url] .
1xbet giris_ulMi
24 Oct 25 at 9:21 pm
В команде — врачи-наркологи, психиатры-консультанты, клинические психологи и выездные медсёстры. Все работают по единому алгоритму: короткий скрининг, стартовая стабилизация, настройка «вечернего протокола» для нормализации сна и план на 72 часа. Цель — восстановить биоритмы, мягко убрать соматические проявления абстиненции и снизить реактивную тревогу, чтобы человек быстрее вернулся к привычным ролям дома и на работе.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-pervouralsk0.ru/]вывод из запоя на дому в первоуральске[/url]
Curtiscleva
24 Oct 25 at 9:22 pm