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://frei-diplom4.ru/]как купить диплом с проводкой[/url] .
Diplomi_apOl
3 Oct 25 at 9:59 pm
Детские велосипеды с гарантией kra 40at kraken рабочая ссылка onion сайт kraken onion kraken darknet
RichardPep
3 Oct 25 at 10:00 pm
купить диплом в кунгуре [url=http://rudik-diplom15.ru]http://rudik-diplom15.ru[/url] .
Diplomi_kiPi
3 Oct 25 at 10:01 pm
диплом техникума казахстана купить [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_area
3 Oct 25 at 10:01 pm
Следует отметить, что с появлением электронного источника официального
опубликования – “Официального интернет-портала правовой информации”
(), количество проблемных случаев с определением первой официальной публикации значительно уменьшилось.
Посмотреть здесь
3 Oct 25 at 10:02 pm
купить диплом в ульяновске [url=https://www.rudik-diplom8.ru]купить диплом в ульяновске[/url] .
Diplomi_iuMt
3 Oct 25 at 10:02 pm
купить диплом в симферополе [url=www.rudik-diplom4.ru]www.rudik-diplom4.ru[/url] .
Diplomi_wnOr
3 Oct 25 at 10:02 pm
Казино X слот Fussball
Matthewbox
3 Oct 25 at 10:05 pm
легальный диплом купить [url=frei-diplom2.ru]легальный диплом купить[/url] .
Diplomi_hkEa
3 Oct 25 at 10:06 pm
как купить диплом о высшем образовании с занесением в реестр отзывы [url=https://frei-diplom3.ru]как купить диплом о высшем образовании с занесением в реестр отзывы[/url] .
Diplomi_ryKt
3 Oct 25 at 10:07 pm
купить свидетельство о рождении [url=https://rudik-diplom5.ru]купить свидетельство о рождении[/url] .
Diplomi_bkma
3 Oct 25 at 10:07 pm
где купить дипломы медсестры [url=http://www.frei-diplom15.ru]где купить дипломы медсестры[/url] .
Diplomi_nwoi
3 Oct 25 at 10:07 pm
Рекомендую https://kubota-hosp.jp/2024/04/07/hello-world/
PedroMop
3 Oct 25 at 10:08 pm
купить диплом в тольятти [url=https://www.rudik-diplom11.ru]купить диплом в тольятти[/url] .
Diplomi_bhMi
3 Oct 25 at 10:09 pm
Все этапы получения лицензии «под ключ» проходили под профессиональным контролем Журавлев Консалтинг Групп, специалисты проверяли документы, сопровождали подачу и обеспечивали полное соответствие требованиям – https://licenz.pro/
BrianRomma
3 Oct 25 at 10:10 pm
новости хоккея [url=http://www.novosti-sporta-15.ru]http://www.novosti-sporta-15.ru[/url] .
novosti sporta_ozma
3 Oct 25 at 10:10 pm
купить диплом в каспийске [url=https://rudik-diplom2.ru]https://rudik-diplom2.ru[/url] .
Diplomi_iipi
3 Oct 25 at 10:10 pm
купить диплом с занесением в реестр челябинск [url=http://frei-diplom1.ru]купить диплом с занесением в реестр челябинск[/url] .
Diplomi_ttOi
3 Oct 25 at 10:10 pm
Когда запой угрожает здоровью и жизни, оперативное вмешательство становится критически важным. В Донецке ДНР опытные специалисты по наркологии оказывают профессиональную помощь на дому, обеспечивая качественную детоксикацию организма, стабилизацию жизненно важных функций и психологическую поддержку. Такой формат лечения позволяет пациенту получить комплексную терапию в условиях комфорта, сохраняя полную конфиденциальность и избегая лишних формальностей.
Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-donetsk-dnr0.ru/]narkolog-vyvod-iz-zapoya donetsk[/url]
Claytonfix
3 Oct 25 at 10:11 pm
Incredible points. Outstanding arguments. Keep up the great effort.
SEO BLACKHAT
3 Oct 25 at 10:11 pm
https://epcsoft.ru
PatrickGop
3 Oct 25 at 10:11 pm
как купить диплом с занесением в реестр в екатеринбурге [url=www.frei-diplom2.ru]www.frei-diplom2.ru[/url] .
Diplomi_dwEa
3 Oct 25 at 10:11 pm
где купить диплом колледжа в астрахани [url=frei-diplom8.ru]frei-diplom8.ru[/url] .
Diplomi_rlsr
3 Oct 25 at 10:12 pm
купить диплом университета [url=www.rudik-diplom4.ru/]купить диплом университета[/url] .
Diplomi_jgOr
3 Oct 25 at 10:12 pm
TESLATOTO hadir sebagai platform terpercaya 2025 yang menawarkan kemudahan deposit QRIS mulai 5000.
TESLATOTO menyediakan situs slot aman dengan kesempatan jackpot setiap hari.
Nikmati sensasi bermain aman, cepat, dan menguntungkan bersama platform slot deposit
5000 yang selalu siap memberikan maxwin menarik untuk semua pemain.
SLOT QRIS
3 Oct 25 at 10:12 pm
Іn Singapore’s framework, secondary school math tuition plays a crucial role іn enhancing conceptual clarity.
Power lah, оur kids’ math skills ρut Singapore at thе pinnacle leh!
Moms and dads, discover how Singapore math tuition transforms math fгom
intimidating to delightful fоr Secondary 1 kids.
Secondary math tuition stresses understanding οver memorization. With secondary 1 math tuition,
coordinate geometry clicks іnto pⅼace, setting үour child օn а courѕе to
academic stars.
Ϝ᧐r tһose intending for toр secondary schools, secondary 2 math tuition іs
іmportant. Secondary 2 math tuition covers
innovative fractions ɑnd decimals ᴡith accuracy.
Τһe encouraging environment of secondary 2 math tuition motivates questioning аnd expedition. In general, secondary 2 math tuition contributes
tο holistic scholastic development.
Secondary 3 math exams function аs essential tests, preceding
Ⲟ-Levels, requiring diligence. Excelling facilitates quiet reflection ɑreas.
Tһey build archival understanding for future reference.
Secondary 4 exams аrе a maқe-or-break minute in Singapore’s syѕtem, wherе math grades ցreatly impact aggregate гesults.
Secondary 4 math tuition ᧐ffers extensive revision sessions οn geometry evidence.
Students who taқe pаrt in thіs tuition typically report lowered anxiety tһroughout nationals.
Focusing oon secondary 4 math tuition іs essential to navigating tһe
competitive landscape effectively.
Mathematics transcends exam preparation; іt’s
a fundamental talent in tһe AI era, powering financial risk assessments.
Ƭo reach the pinnacle in math, embrace а heartfelt love fߋr it and employ mathematical principles іn everyday practical settings.
Тhе significance of this practice іѕ in simulating the pressure ⲟf secondary math exams using papers from dіfferent Singapore schools.
Ᏼy engaging with online math tuition e-learning systems, learners in Singapore gain personalized feedback, leading tߋ better performance іn secondary math
assessments.
Eh eh, ԁ᧐n’t sɑʏ die lor, secondary school ցot holidays too, Ԁon’t worry and Ԁon’t pressure
your child t᧐o hard.
secondary school math tuition
3 Oct 25 at 10:13 pm
At this moment I am going away to do my breakfast, afterward having my breakfast coming yet again to read additional news.
Magyar Befektetési
3 Oct 25 at 10:13 pm
диплом реестр купить [url=https://www.frei-diplom3.ru]диплом реестр купить[/url] .
Diplomi_fzKt
3 Oct 25 at 10:13 pm
На данном этапе врач уточняет, сколько времени продолжается запой, какой тип алкоголя употребляется и имеются ли сопутствующие заболевания. Тщательный анализ этих данных позволяет подобрать оптимальные методы детоксикации и снизить риск осложнений.
Получить дополнительные сведения – http://narcolog-na-dom-mariupol0.ru/
WillisFal
3 Oct 25 at 10:14 pm
Hello, after reading this amazing paragraph i
am too happy to share my experience here with colleagues.
family physician in Vaughan Ontario
3 Oct 25 at 10:15 pm
купить диплом врача [url=http://www.rudik-diplom3.ru]купить диплом врача[/url] .
Diplomi_ybei
3 Oct 25 at 10:15 pm
купить диплом машиниста [url=https://rudik-diplom7.ru]купить диплом машиниста[/url] .
Diplomi_vyPl
3 Oct 25 at 10:16 pm
купить диплом о высшем образовании с занесением в реестр в калуге [url=www.frei-diplom4.ru]купить диплом о высшем образовании с занесением в реестр в калуге[/url] .
Diplomi_bwOl
3 Oct 25 at 10:16 pm
купить диплом в твери [url=https://rudik-diplom5.ru]купить диплом в твери[/url] .
Diplomi_npma
3 Oct 25 at 10:17 pm
спортивные события [url=https://www.novosti-sporta-15.ru]https://www.novosti-sporta-15.ru[/url] .
novosti sporta_coma
3 Oct 25 at 10:17 pm
купить диплом в старом осколе [url=https://rudik-diplom8.ru]купить диплом в старом осколе[/url] .
Diplomi_hjMt
3 Oct 25 at 10:19 pm
купить диплом в междуреченске [url=https://www.rudik-diplom1.ru]https://www.rudik-diplom1.ru[/url] .
Diplomi_gfer
3 Oct 25 at 10:21 pm
Fruityliner 5 играть
TommyCap
3 Oct 25 at 10:22 pm
купить диплом в сочи [url=https://rudik-diplom11.ru]купить диплом в сочи[/url] .
Diplomi_lrMi
3 Oct 25 at 10:22 pm
диплом медсестры с занесением в реестр купить [url=www.frei-diplom4.ru/]диплом медсестры с занесением в реестр купить[/url] .
Diplomi_yxOl
3 Oct 25 at 10:24 pm
купить диплом техникум официальный [url=https://www.frei-diplom9.ru]купить диплом техникум официальный[/url] .
Diplomi_nyea
3 Oct 25 at 10:24 pm
диплом купить с занесением в реестр рязань [url=http://frei-diplom6.ru]http://frei-diplom6.ru[/url] .
Diplomi_uzOl
3 Oct 25 at 10:25 pm
купить диплом с занесением в реестр в москве [url=www.frei-diplom3.ru]купить диплом с занесением в реестр в москве[/url] .
Diplomi_udKt
3 Oct 25 at 10:25 pm
новости футбола [url=https://novosti-sporta-15.ru]https://novosti-sporta-15.ru[/url] .
novosti sporta_qhma
3 Oct 25 at 10:25 pm
купить диплом в сочи [url=http://rudik-diplom7.ru]купить диплом в сочи[/url] .
Diplomi_ckPl
3 Oct 25 at 10:25 pm
где купить диплом техникума хорошую [url=http://www.frei-diplom8.ru]где купить диплом техникума хорошую[/url] .
Diplomi_eysr
3 Oct 25 at 10:26 pm
купить диплом в биробиджане [url=https://rudik-diplom8.ru]купить диплом в биробиджане[/url] .
Diplomi_gnMt
3 Oct 25 at 10:26 pm
купить диплом об образовании с реестром [url=www.frei-diplom1.ru]купить диплом об образовании с реестром[/url] .
Diplomi_ktOi
3 Oct 25 at 10:27 pm
Je suis totalement hypnotise par Impressario, ca balance une vibe spectaculaire. La gamme est une vraie constellation de fun, incluant des jeux de table pleins de panache. Le service client est digne d’un gala, joignable par chat ou email. Le processus est limpide et sans fausse note, de temps en temps les offres pourraient etre plus genereuses. Dans le fond, Impressario c’est une scene a decouvrir absolument pour les amateurs de slots qui brillent ! Cote plus la navigation est simple comme une melodie, ajoute un max de charisme.
impressario casino no deposit bonus|
quirkytoad9zef
3 Oct 25 at 10:27 pm
Sildenafil 100mg [url=https://truevitalmeds.shop/#]sildenafil price 50 mg[/url] true vital meds
TimothyArrar
3 Oct 25 at 10:27 pm