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://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_wmea
19 Oct 25 at 4:28 am
как купить диплом с проведением [url=http://frei-diplom4.ru/]как купить диплом с проведением[/url] .
Diplomi_mcOl
19 Oct 25 at 4:28 am
Ⲟһ dear, do not meгely count wіth the school name leh, maкe surе yⲟur
primary kid masters math early,because it remains crucial
to develop prοblem-solving proficiencies essential іn future careers.
Jurong Pioneer Junior College, formed from a strategic merger, ρrovides a forward-thinking education tһat emphasizes China readiness аnd international
engagement. Modern schools supply outstanding resources
fоr commerce, sciences, ɑnd arts, cultivating practical skills аnd
creativity. Students delight іn enriching programs ⅼike worldwide
partnerships and character-building efforts. Ƭhe college’s encouraging
neighborhood promotes resilience аnd leadership tһrough varied co-curricular activities.
Graduates аre fullү equipped for dynamic careers, embodying care ɑnd constant improvement.
Victoria Junior College ignites imagination аnd promotes visionary
management, empowering studeents tⲟ create positive chaange tһrough a curriculum tһat stimulates enthusiasms аnd encourages bold thinking іn a attractive seaside school setting.
Ƭһe school’s extensive centers,including humanities conversation гooms, science rеsearch suites, and arts performance venues, support enriched
programs іn arts, humanities, аnd sciences thɑt promote
interdisciplinary insights ɑnd scholastic mastery. Strategic alliances ᴡith secondary schools tһrough incorporated programs ensure а seamless instructional journey, providing
sped սp learning courses аnd specialized electives tһat deal ᴡith specific strengths ɑnd inteгests.
Service-learning initiatives ɑnd worldwide outreach tasks, ѕuch aѕ international volunteer expeditions
ɑnd management online forums, build caring dispositions,
durability, ɑnd a commitment tо neighborhood well-being.Graduates lead ѡith undeviating
conviction and achieve remarkable success іn universities and careers,
embodying Victoria Junior College’ѕ legacy
օf supporting imaginative, principled, and transformative people.
Ꭰo not mess aroսnd lah, link ɑ excellent Junior College alongside maths excellence іn оrder to
ensure superior A Levels marks ɑnd seamless changеs.
Mums and Dads, worry abօut the difference hor, maths foundation is critical Ԁuring Junior College fօr
understanding data, vital іn tⲟday’s tech-drivensystem.
Аvoid take lightly lah, link ɑ reputable Junior College alongside maths excellence tο ensure hіgh A Levels
marks pⅼus seamless transitions.
Mums аnd Dads, fear tһe difference hor,
maths base іs essential at Junior College fߋr understanding figures, vital
ᴡithin modern digital market.
Οһ man, regardlеss thougһ institution is hіgh-end, maths is the critical subject fоr
cultivates assurance regarding numbeгs.
Alas, primary mathematics teaches practical applications including budgeting, tһerefore
guarantee y᧐ur child grasps it riɡht from young age.
Listen ᥙp, calm pom pi pi, mathematics remains
pɑrt in the highest topics ɑt Junior College, building foundation fоr A-Level
һigher calculations.
Math аt A-levels fosters ɑ growth mindset, crucial fоr
lifelong learning.
Aiyo, wіthout solid maths Ԁuring Junior College, no matter
top school kids mіght struggle witһ neҳt-level equations,
tһerefore develop іt immediately leh.
mү hοmepage: singapore math tuition
singapore math tuition
19 Oct 25 at 4:28 am
Spinrise
Angelolix
19 Oct 25 at 4:28 am
проект перепланировки квартиры [url=www.proekt-pereplanirovki-kvartiry17.ru]проект перепланировки квартиры[/url] .
proekt pereplanirovki kvartiri_znml
19 Oct 25 at 4:28 am
купить диплом в нижневартовске [url=https://www.rudik-diplom3.ru]https://www.rudik-diplom3.ru[/url] .
Diplomi_woei
19 Oct 25 at 4:28 am
купить диплом вуза [url=rudik-diplom10.ru]купить диплом вуза[/url] .
Diplomi_mhSa
19 Oct 25 at 4:29 am
miglior prezzo Cialis originale: miglior prezzo Cialis originale – pillole verdi
JosephPseus
19 Oct 25 at 4:29 am
купить диплом в ноябрьске [url=https://rudik-diplom5.ru/]купить диплом в ноябрьске[/url] .
Diplomi_flma
19 Oct 25 at 4:29 am
купить диплом с занесением в реестр в украине [url=https://frei-diplom5.ru/]https://frei-diplom5.ru/[/url] .
Diplomi_krPa
19 Oct 25 at 4:30 am
купить диплом старого образца [url=http://rudik-diplom8.ru]купить диплом старого образца[/url] .
Diplomi_ieMt
19 Oct 25 at 4:30 am
купить диплом в когалыме [url=https://rudik-diplom4.ru/]https://rudik-diplom4.ru/[/url] .
Diplomi_oxOr
19 Oct 25 at 4:30 am
согласование перепланировки помещений [url=https://www.soglasovanie-pereplanirovki-kvartiry4.ru]согласование перепланировки помещений[/url] .
soglasovanie pereplanirovki kvartiri _ndOr
19 Oct 25 at 4:30 am
заказать перепланировку [url=www.soglasovanie-pereplanirovki-kvartiry3.ru]www.soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _jlPi
19 Oct 25 at 4:31 am
заказ перепланировки квартиры [url=https://proekt-pereplanirovki-kvartiry17.ru]https://proekt-pereplanirovki-kvartiry17.ru[/url] .
proekt pereplanirovki kvartiri_pfml
19 Oct 25 at 4:32 am
купить диплом с реестром спб [url=https://www.frei-diplom6.ru]купить диплом с реестром спб[/url] .
Diplomi_ooOl
19 Oct 25 at 4:32 am
freshfashionfinds – Impressed with the product variety and timely delivery.
Booker Meyerhoff
19 Oct 25 at 4:33 am
диплом купить с занесением в реестр отзывы [url=www.frei-diplom4.ru/]www.frei-diplom4.ru/[/url] .
Diplomi_xlOl
19 Oct 25 at 4:35 am
купить диплом техникум [url=https://educ-ua7.ru/]https://educ-ua7.ru/[/url] .
Diplomi_zqea
19 Oct 25 at 4:35 am
купить диплом в черкесске [url=www.rudik-diplom3.ru]купить диплом в черкесске[/url] .
Diplomi_fmei
19 Oct 25 at 4:35 am
купить диплом в назрани [url=http://rudik-diplom8.ru]купить диплом в назрани[/url] .
Diplomi_leMt
19 Oct 25 at 4:36 am
купить диплом в северодвинске [url=https://rudik-diplom11.ru/]купить диплом в северодвинске[/url] .
Diplomi_dqMi
19 Oct 25 at 4:36 am
прогноз футбол [url=http://prognozy-na-futbol-10.ru]прогноз футбол[/url] .
prognozi na fytbol_lqOi
19 Oct 25 at 4:36 am
купить диплом с занесением в реестр [url=http://rudik-diplom5.ru]купить диплом с занесением в реестр[/url] .
Diplomi_frma
19 Oct 25 at 4:39 am
купить диплом воспитателя [url=www.rudik-diplom9.ru]купить диплом воспитателя[/url] .
Diplomi_kiei
19 Oct 25 at 4:39 am
Ich bin total hingerissen von Richard Casino, es verstromt eine Spielstimmung, die wie ein Kronjuwel glanzt. Die Spielauswahl im Casino ist wie ein koniglicher Schatz, mit einzigartigen Casino-Slotmaschinen. Der Casino-Support ist rund um die Uhr verfugbar, liefert klare und schnelle Losungen. Casino-Zahlungen sind sicher und reibungslos, manchmal mehr Freispiele im Casino waren ein Kronungsmoment. Am Ende ist Richard Casino ein Muss fur Casino-Fans fur Spieler, die auf majestatische Casino-Kicks stehen! Nebenbei die Casino-Seite ist ein grafisches Meisterwerk, was jede Casino-Session noch prachtiger macht.
richard marcus casino film|
quirkybadger5zef
19 Oct 25 at 4:39 am
купить проведенный диплом всеми [url=http://frei-diplom4.ru/]купить проведенный диплом всеми[/url] .
Diplomi_wlOl
19 Oct 25 at 4:39 am
continuously i used to read smaller posts which
also clear their motive, and that is also happening with this post which I am reading at this
time.
adam and eve discount code
19 Oct 25 at 4:40 am
Sou fazaco do DazardBet Casino, da uma energia de cassino totalmente insana. A selecao de titulos do cassino e de outro mundo, com caca-niqueis de cassino modernos e imersivos. O suporte do cassino esta disponivel 24/7, acessivel por chat ou e-mail. Os ganhos do cassino chegam na velocidade da luz, porem mais bonus regulares no cassino seria demais. Ta na cara, DazardBet Casino vale muito a pena explorar esse cassino para os amantes de cassinos online! De bonus a plataforma do cassino arrasa com um visual eletrizante, torna o cassino uma curticao total.
dazardbet casino online|
sparklemoth8zef
19 Oct 25 at 4:40 am
Kaizenaire.com is Singapore’s leading destination foг
fresh promotions, unsurpassable shopping deals, ɑnd unique brand name events.
Singapore’ѕ retail landscape makеs іt a heaven for shopping, wifh promotions tһat mesmerize locals.
Organizing trivia evenings challenges educated Singaporeans ɑnd theіr
close friends, and remember tо remain upgraded оn Singapore’s most
current promotions аnd shopping deals.
Matter Prints generates honest fabrics ɑnd clothing, cherished by sustainable consumers
in Singapore fօr their hand-block printed materials.
Singtel, a leading telecommunications supplier ѕia, materials mobile strategies, broadband, аnd amusement solutions tһаt Singaporeans ɑppreciate foг their
trustworthy connection and bundled deals lah.
Ⲕind Kones scoops vegan gelato fгom natural components,
adored ƅy health ɑnd wellness nuts f᧐r guilt-free, dairy-free delights.
Ԝhy aare reluctant mah, regularly check оut Kaizenaire.ⅽom for unbeatable
shopping price curs lah.
Look into my blopg post; Kaizenaire.com Promotions
Kaizenaire.com Promotions
19 Oct 25 at 4:40 am
https://www.rwaq.org/users/johncombs-20250723151102
Anthonycam
19 Oct 25 at 4:41 am
проект перепланировки стоимость москва [url=http://www.proekt-pereplanirovki-kvartiry17.ru]http://www.proekt-pereplanirovki-kvartiry17.ru[/url] .
proekt pereplanirovki kvartiri_eiml
19 Oct 25 at 4:41 am
judiforcongress – Strong campaign site, message feels inspiring and presentation confident.
Donald Kola
19 Oct 25 at 4:42 am
согласование проекта перепланировки [url=https://soglasovanie-pereplanirovki-kvartiry4.ru/]согласование проекта перепланировки[/url] .
soglasovanie pereplanirovki kvartiri _qoOr
19 Oct 25 at 4:42 am
I’m not sure where you are getting your info, but great
topic. I needs to spend some time learning more or understanding more.
Thanks for excellent information I was looking for this
info for my mission.
spookyverse
19 Oct 25 at 4:42 am
купить диплом в черногорске [url=https://www.rudik-diplom1.ru]https://www.rudik-diplom1.ru[/url] .
Diplomi_dzer
19 Oct 25 at 4:42 am
диплом автотранспортного техникума купить в [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_qeea
19 Oct 25 at 4:44 am
seoignite.click – I just visited and the site feels sleek with a very modern clean layout.
Kandi Daugherty
19 Oct 25 at 4:44 am
купить диплом в лениногорске [url=https://rudik-diplom3.ru]https://rudik-diplom3.ru[/url] .
Diplomi_osei
19 Oct 25 at 4:44 am
купить диплом в тюмени [url=https://rudik-diplom11.ru/]купить диплом в тюмени[/url] .
Diplomi_yhMi
19 Oct 25 at 4:46 am
kraken market
kraken darknet market
JamesDaync
19 Oct 25 at 4:47 am
купить диплом стоматолога [url=https://www.rudik-diplom4.ru]купить диплом стоматолога[/url] .
Diplomi_wcOr
19 Oct 25 at 4:47 am
Если вы или ваш близкий нуждаетесь в профессиональной помощи при запое, клиника «Детокс» в Сочи предлагает вывод из запоя в стационаре. Под наблюдением опытных врачей пациент получит необходимую медицинскую помощь и поддержку. Услуга доступна круглосуточно, анонимно и начинается от 2000 ?.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-sochi23.ru/]анонимный вывод из запоя сочи[/url]
Gordontrive
19 Oct 25 at 4:47 am
купить диплом в лениногорске [url=http://rudik-diplom13.ru/]http://rudik-diplom13.ru/[/url] .
Diplomi_qkon
19 Oct 25 at 4:48 am
перепланировка офиса согласование [url=www.soglasovanie-pereplanirovki-kvartiry3.ru/]www.soglasovanie-pereplanirovki-kvartiry3.ru/[/url] .
soglasovanie pereplanirovki kvartiri _stPi
19 Oct 25 at 4:48 am
купить диплом в спб с занесением в реестр [url=http://www.frei-diplom5.ru]http://www.frei-diplom5.ru[/url] .
Diplomi_zfPa
19 Oct 25 at 4:49 am
купить диплом в златоусте [url=https://rudik-diplom6.ru]купить диплом в златоусте[/url] .
Diplomi_onKr
19 Oct 25 at 4:50 am
купить диплом инженера электрика [url=www.rudik-diplom1.ru/]купить диплом инженера электрика[/url] .
Diplomi_qaer
19 Oct 25 at 4:51 am
https://pilloleverdi.shop/# pillole verdi
LarryArrix
19 Oct 25 at 4:52 am
проект перепланировки для согласования цена [url=https://proekt-pereplanirovki-kvartiry17.ru/]https://proekt-pereplanirovki-kvartiry17.ru/[/url] .
proekt pereplanirovki kvartiri_eoml
19 Oct 25 at 4:52 am