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://modadinterni.it/2022/11/07/ciao-mondo
EugeneVem
21 Oct 25 at 8:42 am
купить диплом технолога [url=http://rudik-diplom8.ru]купить диплом технолога[/url] .
Diplomi_xqMt
21 Oct 25 at 8:42 am
kraken vpn
kraken vk3
JamesDaync
21 Oct 25 at 8:42 am
https://intimisante.shop/# achat discret de Cialis 20mg
MickeySum
21 Oct 25 at 8:43 am
прием СМС онлайн
Ernestadaky
21 Oct 25 at 8:43 am
pin up aviator app [url=https://pinup5008.ru]pin up aviator app[/url]
pin_up_uz_cySt
21 Oct 25 at 8:45 am
диплом техникума купить в [url=https://educ-ua7.ru]https://educ-ua7.ru[/url] .
Diplomi_uvea
21 Oct 25 at 8:45 am
купить диплом в сызрани [url=rudik-diplom1.ru]купить диплом в сызрани[/url] .
Diplomi_ycer
21 Oct 25 at 8:46 am
$MTAUR coin’s security audits by SolidProof and Coinsult make it trustworthy amid scam fears. Presale raffle for $100K is drawing crowds. Loving the whimsical creature battles in the demo.
mtaur token
WilliamPargy
21 Oct 25 at 8:47 am
купить диплом с занесением в реестр в красноярске [url=www.frei-diplom5.ru]www.frei-diplom5.ru[/url] .
Diplomi_hwPa
21 Oct 25 at 8:47 am
В этой статье представлен занимательный и актуальный контент, который заставит вас задуматься. Мы обсуждаем насущные вопросы и проблемы, а также освещаем истории, которые вдохновляют на действия и изменения. Узнайте, что стоит за событиями нашего времени!
Уточнить детали – https://jjavnxxhxfhmb.com/%D9%86%D9%82%D9%84-%D8%B9%D9%81%D8%B4-%D8%A8%D8%A7%D9%84%D8%AE%D8%A8%D8%B1-%D9%85%D8%B9-%D9%81%D9%87%D8%AF-%D8%A7%D9%84%D9%84%D9%8A%D9%84-%D8%A7%D9%84%D8%AE%D9%8A%D8%A7%D8%B1-%D8%A7%D9%84%D8%A3%D9%85/148/%D9%86%D9%82%D9%84-%D8%B9%D9%81%D8%B4
Daniellox
21 Oct 25 at 8:47 am
купить диплом в нефтекамске [url=https://rudik-diplom11.ru/]купить диплом в нефтекамске[/url] .
Diplomi_hjMi
21 Oct 25 at 8:47 am
http://www.medtronik.ru сайт для тех, кто хочет получить дополнительные преимущества
Aaronawads
21 Oct 25 at 8:48 am
сео фирмы [url=https://www.reiting-seo-kompaniy.ru]сео фирмы[/url] .
reiting seo kompanii_cqon
21 Oct 25 at 8:48 am
seo продвижение москва [url=www.reiting-seo-agentstv-moskvy.ru]seo продвижение москва[/url] .
reiting seo agentstv moskvi_ogMl
21 Oct 25 at 8:48 am
как купить легальный диплом [url=frei-diplom4.ru]frei-diplom4.ru[/url] .
Diplomi_zcOl
21 Oct 25 at 8:49 am
рейтинг сео компаний [url=reiting-seo-kompanii.ru]рейтинг сео компаний[/url] .
reiting seo kompanii_kqsn
21 Oct 25 at 8:49 am
купить диплом университета [url=http://www.rudik-diplom8.ru]купить диплом университета[/url] .
Diplomi_whMt
21 Oct 25 at 8:49 am
медсестра которая купила диплом врача [url=http://frei-diplom13.ru]медсестра которая купила диплом врача[/url] .
Diplomi_dfkt
21 Oct 25 at 8:50 am
купить диплом с занесением в реестр вуза [url=www.frei-diplom6.ru]купить диплом с занесением в реестр вуза[/url] .
Diplomi_buOl
21 Oct 25 at 8:50 am
kraken onion
kraken vpn
JamesDaync
21 Oct 25 at 8:51 am
куплю диплом о высшем образовании [url=www.rudik-diplom3.ru/]куплю диплом о высшем образовании[/url] .
Diplomi_gyei
21 Oct 25 at 8:51 am
trustbridgealliance.cfd – Site loads quickly and seems mobile-friendly — big plus for browsing on the go.
Devon Shand
21 Oct 25 at 8:51 am
виртуальный номер для WhatsApp
Ernestadaky
21 Oct 25 at 8:52 am
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Рассмотреть проблему всесторонне – https://pentvars.edu.gh/pucs-src-commends-rector
Ernierop
21 Oct 25 at 8:53 am
compresse per disfunzione erettile: dove comprare Cialis in Italia – cialis generico
RaymondNit
21 Oct 25 at 8:53 am
seo продвижение россия [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]seo продвижение россия[/url] .
agentstvo poiskovogo prodvijeniya_jiKt
21 Oct 25 at 8:54 am
одноразовые номера
Antoniomerty
21 Oct 25 at 8:55 am
где купить диплом с занесением реестр [url=https://frei-diplom5.ru/]где купить диплом с занесением реестр[/url] .
Diplomi_ugPa
21 Oct 25 at 8:55 am
Every weekend i used to pay a visit this website, for the reason that i want enjoyment,
since this this website conations in fact good funny information too.
gut support
21 Oct 25 at 8:55 am
купить диплом в волгодонске [url=rudik-diplom11.ru]купить диплом в волгодонске[/url] .
Diplomi_psMi
21 Oct 25 at 8:55 am
Этот обзор предлагает структурированное изложение информации по актуальным вопросам. Материал подан так, чтобы даже новичок мог быстро освоиться в теме и начать использовать полученные знания в практике.
А что дальше? – https://ccmdaci.org/irfmda/?option=com_content&view=article&id=3&Itemid=4&c54c502892c591ec2c2298f75e798fd3=a1592a190e1f2bb637eb91f72b7f45a7%20
Georgejet
21 Oct 25 at 8:56 am
виртуальный номер для банковских сервисов
Timothydrart
21 Oct 25 at 8:56 am
купить диплом в уссурийске [url=https://rudik-diplom1.ru/]https://rudik-diplom1.ru/[/url] .
Diplomi_rber
21 Oct 25 at 8:56 am
кракен qr код
кракен даркнет
JamesDaync
21 Oct 25 at 8:57 am
обслуживание и продвижение сайта [url=reiting-runeta-seo.ru]обслуживание и продвижение сайта[/url] .
reiting ryneta seo_alma
21 Oct 25 at 8:57 am
The Minotaurus presale vesting is flexible genius. Token’s DAO influence key. Gaming market ripe.
minotaurus ico
WilliamPargy
21 Oct 25 at 8:58 am
виртуальный номер для регистрации
Timothydrart
21 Oct 25 at 8:58 am
диплом о среднем профессиональном образовании с занесением в реестр купить [url=http://frei-diplom6.ru/]диплом о среднем профессиональном образовании с занесением в реестр купить[/url] .
Diplomi_cgOl
21 Oct 25 at 8:58 am
Thank you for the good writeup. It in fact was a amusement account it.
Look advanced to far added agreeable from you! By the way,
how could we communicate?
13win
21 Oct 25 at 8:59 am
seo продвижение сайтов москва [url=www.reiting-seo-agentstv-moskvy.ru/]www.reiting-seo-agentstv-moskvy.ru/[/url] .
reiting seo agentstv moskvi_zhMl
21 Oct 25 at 8:59 am
купить диплом в ачинске [url=rudik-diplom8.ru]купить диплом в ачинске[/url] .
Diplomi_zeMt
21 Oct 25 at 9:00 am
Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
Открыть полностью – https://www.2h-fit.net/how-to-seduce-your-girlfriend
PeterDrell
21 Oct 25 at 9:00 am
виртуальный номер для Facebook
Jaredvaf
21 Oct 25 at 9:01 am
топ интернет агентств [url=https://luchshie-digital-agencstva.ru]топ интернет агентств[/url] .
lychshie digital agentstva_gdoi
21 Oct 25 at 9:01 am
как купить диплом с проведением [url=www.frei-diplom5.ru/]как купить диплом с проведением[/url] .
Diplomi_naPa
21 Oct 25 at 9:01 am
купить диплом в крыму [url=http://rudik-diplom11.ru]купить диплом в крыму[/url] .
Diplomi_hhMi
21 Oct 25 at 9:01 am
купить диплом в техникуме [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_fvea
21 Oct 25 at 9:02 am
кракен онлайн
кракен vk3
JamesDaync
21 Oct 25 at 9:04 am
Le code promo est supprime : entrez-le dans le champ « Code promo » et reclamez un bonus de bienvenue de 100% jusqu’a 130€, a utiliser dans les paris sportifs. Vous pouvez vous inscrire sur le site 1xBet ou via l’application mobile. Apres votre premier depot, vous activerez le code bonus. L’offre est valable pour toute l’annee 2026, et le bonus doit etre mise dans les 30 jours. Vous pouvez trouver le code promo sur ce lien — https://ville-barentin.fr/wp-content/pgs/code-promo-bonus-1xbet.html.
Marvinspaft
21 Oct 25 at 9:04 am