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=www.rudik-diplom14.ru]купить диплом во владимире[/url] .
Diplomi_eeea
2 Nov 25 at 12:07 pm
сео продвижение сайтов топ 10 [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]сео продвижение сайтов топ 10[/url] .
agentstvo poiskovogo prodvijeniya_jjKt
2 Nov 25 at 12:08 pm
рейтинг интернет агентств seo [url=https://www.reiting-seo-kompaniy.ru]https://www.reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_epon
2 Nov 25 at 12:08 pm
1xbet tr giri? [url=www.1xbet-giris-5.com]www.1xbet-giris-5.com[/url] .
1xbet giris_yySa
2 Nov 25 at 12:09 pm
диплом купить с занесением в реестр челябинск [url=www.frei-diplom6.ru/]www.frei-diplom6.ru/[/url] .
Diplomi_fqOl
2 Nov 25 at 12:09 pm
купить диплом в кропоткине [url=https://rudik-diplom6.ru/]https://rudik-diplom6.ru/[/url] .
Diplomi_fjKr
2 Nov 25 at 12:10 pm
купить диплом в новороссийске [url=http://www.rudik-diplom8.ru]купить диплом в новороссийске[/url] .
Diplomi_yuMt
2 Nov 25 at 12:10 pm
payid pokies
Australia’s Best Pokies: Our Hands-On Testing Results
Our team has spent many months testing the top online pokies in Australia. We’ve manually checked each site, checking how fast they pay out, the actual value of their bonuses, their licensing, and how well they work on handheld devices.
Every site we list holds GCB accreditation under 96GROUP, which means they meet standards for fair play and responsible gambling.
Our Selected Sites
Partner Top Offer Min Dep Payout Speed* Score
APP996 Up to AUD 2,000 match AUD 5 5–10 mins 5.0
OPAL96 6% weekly commission AUD 5 ~10 mins 4.9
VIVA96 110% welcome bonus AUD 5 ~10–15 mins 4.8
MM96 VIP rewards + missions AUD 5 ~15 mins 4.7
Handling time after KYC verification. Your bank’s processing times may vary.
Our Discoveries
– APP996: Presents a 50% welcome bonus and a 0.96% rebate.
– OPAL96: Has over 5,000 games and is a newer platform.
– VIVA96: Offers a 110% bonus, 17% daily reload, and an 8% win/loss rebate.
– MM96: Offers up to a 100% welcome offer and daily missions.
Our Evaluation Method
We made real withdrawals to verify processing times, ensured the validity of licenses and RNG fairness, examined the real bonus value after accounting for wagering requirements and withdrawal caps, evaluated the quality of their 24/7 support, and confirmed responsible gambling tools were available.
Mobile Compatibility
All these sites use Gialaitech’s mobile-adapted platform:
– Play directly in your browser—no app needed
– Add this site to your home screen for quick access
– Supports biometric login, works well with one hand, quick cashier (PayID, cards, e-wallets, crypto)
– Features custom themes, session controls, and optional notifications for bonuses or payouts
Crucial Notes
These partners are GCB-licensed. Our ratings are our own opinion—any affiliate payments don’t influence our scores. All bonuses come with terms (wagering requirements, withdrawal caps, game restrictions). Must be 18 or older.
For gambling support: Gambling Help Online: 1800 858 858 or gamblinghelponline.org.au
Play responsibly. Know your limits.
herkalkag
2 Nov 25 at 12:10 pm
купить диплом по реестру [url=https://www.frei-diplom4.ru]купить диплом по реестру[/url] .
Diplomi_zxOl
2 Nov 25 at 12:10 pm
купить диплом в хасавюрте [url=www.rudik-diplom10.ru/]купить диплом в хасавюрте[/url] .
Diplomi_naSa
2 Nov 25 at 12:11 pm
pharmacy online: verified online chemists in Australia – verified pharmacy coupon sites Australia
Johnnyfuede
2 Nov 25 at 12:12 pm
купить vip диплом техникума ссср [url=https://frei-diplom8.ru]купить vip диплом техникума ссср[/url] .
Diplomi_mssr
2 Nov 25 at 12:12 pm
сео фирмы [url=https://reiting-seo-kompaniy.ru/]сео фирмы[/url] .
reiting seo kompanii_kgon
2 Nov 25 at 12:14 pm
1xbwt giri? [url=http://www.1xbet-giris-2.com]http://www.1xbet-giris-2.com[/url] .
1xbet giris_csPt
2 Nov 25 at 12:15 pm
купить диплом в благовещенске [url=http://rudik-diplom3.ru]купить диплом в благовещенске[/url] .
Diplomi_toei
2 Nov 25 at 12:16 pm
купить новый диплом [url=https://www.rudik-diplom10.ru]купить новый диплом[/url] .
Diplomi_doSa
2 Nov 25 at 12:16 pm
топ компаний по продвижению сайтов [url=https://reiting-seo-kompaniy.ru/]топ компаний по продвижению сайтов[/url] .
reiting seo kompanii_ndon
2 Nov 25 at 12:17 pm
купить диплом в иваново [url=http://www.rudik-diplom4.ru]купить диплом в иваново[/url] .
Diplomi_oyOr
2 Nov 25 at 12:17 pm
1xbet giri? [url=https://1xbet-giris-4.com/]1xbet giri?[/url] .
1xbet giris_anSa
2 Nov 25 at 12:18 pm
купить диплом о образовании недорого [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_qzea
2 Nov 25 at 12:20 pm
продвижение сайта в топ 10 профессионалами [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_cuKt
2 Nov 25 at 12:20 pm
купить диплом в перми [url=https://rudik-diplom14.ru]купить диплом в перми[/url] .
Diplomi_dpea
2 Nov 25 at 12:21 pm
купить диплом в соликамске [url=www.rudik-diplom13.ru]купить диплом в соликамске[/url] .
Diplomi_pjon
2 Nov 25 at 12:21 pm
купить диплом в пятигорске [url=http://rudik-diplom10.ru/]купить диплом в пятигорске[/url] .
Diplomi_gaSa
2 Nov 25 at 12:21 pm
AussieMedsHubAu [url=http://aussiemedshubau.com/#]Aussie Meds Hub[/url] Aussie Meds Hub
Hermanengam
2 Nov 25 at 12:22 pm
купить диплом в керчи [url=www.rudik-diplom3.ru/]www.rudik-diplom3.ru/[/url] .
Diplomi_uvei
2 Nov 25 at 12:22 pm
купить диплом с проводкой моего [url=http://frei-diplom6.ru/]купить диплом с проводкой моего[/url] .
Diplomi_zeOl
2 Nov 25 at 12:22 pm
купить медицинский диплом медсестры [url=www.frei-diplom13.ru]купить медицинский диплом медсестры[/url] .
Diplomi_dukt
2 Nov 25 at 12:22 pm
купить диплом программиста [url=http://rudik-diplom4.ru]купить диплом программиста[/url] .
Diplomi_ldOr
2 Nov 25 at 12:23 pm
купить диплом о высшем образовании с занесением в реестр в калуге [url=www.frei-diplom5.ru/]купить диплом о высшем образовании с занесением в реестр в калуге[/url] .
Diplomi_gjPa
2 Nov 25 at 12:25 pm
OMT’s concentrate on fundamental abilities constructs unshakeable
confidence, enabling Singapore trainees tⲟ fall in love wіth math’s elegance аnd feel motivated fоr tests.
Broaden ʏour horizons with OMT’s upcoming brand-neᴡ physical space оpening іn Sеptember 2025, providing even more
chances for hands-on math expedition.
With students іn Singapore starting formal mathematics education fгom ԁay one and dealing with
һigh-stakes evaluations, math tuition ߋffers tһе additional edge needed to accomplish leading efficiency іn tһiѕ essential topic.
Tuition іn primary school math іs key foг PSLE preparation, аs
it pгesents advanced methods fοr handling non-routine рroblems tһat stump
numerous prospects.
In-depth responses fгom tuition instructors ߋn technique attempts
assists secondary students pick սp from mistakes, boosting accuracy
fοr the real O Levels.
Planning fⲟr the changability οf A Level concerns,
tuiution develops flexible analytical strategies fօr
real-time exam scenarios.
Uniquely customized tо match tһe MOE syllabus, OMT’ѕ custom-mаɗe math program incorporates technology-driven tools fоr interactive learning experiences.
Bite-sized lessons mɑke it verү easy tߋ fit in leh, leading t᧐ constant practice ɑnd Ƅetter overall qualities.
Singapore’ѕ incorporated math curriculum gain from tuition that attaches subjects across degrees fߋr cohesive test preparedness.
Ⅿy web blog: math tuition singapore (Ross)
Ross
2 Nov 25 at 12:25 pm
рейтинг seo фирм [url=www.reiting-seo-kompaniy.ru]www.reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_whon
2 Nov 25 at 12:26 pm
купить диплом в батайске [url=rudik-diplom3.ru]rudik-diplom3.ru[/url] .
Diplomi_dpei
2 Nov 25 at 12:26 pm
купить диплом в иркутске [url=http://rudik-diplom2.ru]купить диплом в иркутске[/url] .
Diplomi_xvpi
2 Nov 25 at 12:27 pm
купить диплом в тольятти [url=https://www.rudik-diplom4.ru]купить диплом в тольятти[/url] .
Diplomi_ozOr
2 Nov 25 at 12:28 pm
сео продвижение сайтов топ 10 [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]сео продвижение сайтов топ 10[/url] .
agentstvo poiskovogo prodvijeniya_joKt
2 Nov 25 at 12:28 pm
купить диплом в уфе с реестром [url=frei-diplom4.ru]frei-diplom4.ru[/url] .
Diplomi_laOl
2 Nov 25 at 12:28 pm
best Irish pharmacy websites [url=https://irishpharmafinder.shop/#]pharmacy delivery Ireland[/url] affordable medication Ireland
Hermanengam
2 Nov 25 at 12:28 pm
где купить диплом с реестром [url=http://frei-diplom6.ru]где купить диплом с реестром[/url] .
Diplomi_pkOl
2 Nov 25 at 12:28 pm
купить диплом швеи [url=http://rudik-diplom8.ru/]купить диплом швеи[/url] .
Diplomi_kwMt
2 Nov 25 at 12:28 pm
Saya merupakan pemain yang gemar dengan dunia taruhan online.
Saya sering bermain di KUBET karena situs ini memiliki banyak pilihan permainan menarik.
Melalui kubet login, saya bisa mengakses Situs Judi Bola Terlengkap dengan mudah dan cepat.
Saya juga suka bermain di Situs Parlay Resmi dan Situs
Parlay Gacor karena peluang menangnya cukup tinggi.
Selain itu, permainan toto macau dan Situs Mix Parlay juga menjadi andalan saya ketika mencari hiburan di situs parlay
yang terpercaya.
Situs Parlay Gacor
2 Nov 25 at 12:31 pm
купить диплом в мурманске с занесением в реестр [url=www.frei-diplom6.ru/]купить диплом в мурманске с занесением в реестр[/url] .
Diplomi_ozOl
2 Nov 25 at 12:32 pm
1 xbet [url=http://1xbet-giris-5.com]http://1xbet-giris-5.com[/url] .
1xbet giris_mfSa
2 Nov 25 at 12:34 pm
Купить диплом техникума в Мариуполь [url=https://educ-ua7.ru]https://educ-ua7.ru[/url] .
Diplomi_hdea
2 Nov 25 at 12:34 pm
https://textpesni2.ru/
https://textpesni2.ru/
2 Nov 25 at 12:34 pm
seo expert agency [url=https://www.reiting-seo-kompaniy.ru]https://www.reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_fxon
2 Nov 25 at 12:36 pm
https://t.me/official_1win_aviator/61
BluffMaster
2 Nov 25 at 12:36 pm
твір есе про природу 5 клас
Jamesstalm
2 Nov 25 at 12:36 pm
купить диплом в новоалтайске [url=www.rudik-diplom5.ru/]купить диплом в новоалтайске[/url] .
Diplomi_czma
2 Nov 25 at 12:36 pm
медсестра которая купила диплом врача [url=https://frei-diplom13.ru/]медсестра которая купила диплом врача[/url] .
Diplomi_jmkt
2 Nov 25 at 12:37 pm