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=http://rudik-diplom4.ru/]купить диплом врача[/url] .
Diplomi_rcOr
22 Oct 25 at 12:49 pm
купить диплом с проводкой меня [url=frei-diplom3.ru]купить диплом с проводкой меня[/url] .
Diplomi_srKt
22 Oct 25 at 12:49 pm
купить диплом железнодорожника [url=www.rudik-diplom11.ru/]купить диплом железнодорожника[/url] .
Diplomi_emMi
22 Oct 25 at 12:50 pm
купить диплом высшем образовании занесением реестр [url=www.frei-diplom4.ru/]купить диплом высшем образовании занесением реестр[/url] .
Diplomi_tuOl
22 Oct 25 at 12:50 pm
kraken онлайн
kraken vk3
JamesDaync
22 Oct 25 at 12:51 pm
где купить диплом [url=http://www.rudik-diplom2.ru]где купить диплом[/url] .
Diplomi_ejpi
22 Oct 25 at 12:51 pm
It’s a pity you don’t have a donate button! I’d most certainly
donate to this outstanding blog! I suppose for now i’ll
settle for book-marking and adding your RSS feed to my Google account.
I look forward to brand new updates and will share this website with my Facebook group.
Chat soon!
https://egritud.com/
Musik Hits
22 Oct 25 at 12:51 pm
купить диплом вуза с занесением в реестр [url=https://frei-diplom1.ru/]купить диплом вуза с занесением в реестр[/url] .
Diplomi_gdOi
22 Oct 25 at 12:51 pm
kraken darknet
kraken сайт
JamesDaync
22 Oct 25 at 12:52 pm
купить диплом в таганроге [url=http://www.rudik-diplom8.ru]http://www.rudik-diplom8.ru[/url] .
Diplomi_mtMt
22 Oct 25 at 12:53 pm
компании занимающиеся продвижением сайтов [url=https://top-10-seo-prodvizhenie.ru/]компании занимающиеся продвижением сайтов[/url] .
top 10 seo prodvijenie_crKa
22 Oct 25 at 12:54 pm
I was recommended this blog by my cousin. I am not
sure whether this post is written by him as no one else know such detailed about
my trouble. You’re amazing! Thanks!
1win casino официальный сайт
22 Oct 25 at 12:54 pm
Читатель отправляется в интеллектуальное путешествие по самым ярким событиям истории и важнейшим научным открытиям. Мы раскроем тайны эпох, покажем, как идеи меняли миры, и объясним, почему эти знания остаются актуальными сегодня.
Неизвестные факты о… – https://mm-online.ru/narkologicheskaya-klinika-istochnik-zhizni-v-omske-ke
Richardkap
22 Oct 25 at 12:55 pm
купить диплом в белогорске [url=http://rudik-diplom10.ru/]http://rudik-diplom10.ru/[/url] .
Diplomi_wtSa
22 Oct 25 at 12:55 pm
как купить диплом с занесением в реестр [url=www.frei-diplom1.ru]как купить диплом с занесением в реестр[/url] .
Diplomi_phOi
22 Oct 25 at 12:55 pm
купить диплом в нефтеюганске [url=www.rudik-diplom11.ru]купить диплом в нефтеюганске[/url] .
Diplomi_wzMi
22 Oct 25 at 12:57 pm
купить диплом в новосибирске [url=http://rudik-diplom7.ru/]купить диплом в новосибирске[/url] .
Diplomi_stPl
22 Oct 25 at 12:57 pm
купить диплом нефтяного колледжа в москве [url=http://frei-diplom9.ru]http://frei-diplom9.ru[/url] .
Diplomi_xjea
22 Oct 25 at 12:59 pm
купить медицинский диплом с занесением в реестр [url=https://www.frei-diplom4.ru]купить медицинский диплом с занесением в реестр[/url] .
Diplomi_dcOl
22 Oct 25 at 1:00 pm
Зарубежные стриминговые сериалы бесплатно —
кто знает хорошие платформы?
стриминговые сериалы
22 Oct 25 at 1:00 pm
Акционный код 1xBet — активируйте его в поле для промокода при регистрации, пополните баланс свой счет на сумму от 100 RUB и получите бонусом в размере 100 процентов (до 32500 рублей).В разделе аккаунта перейдите в раздел «Бонусные предложения» и выберите вариант «Активировать промокод».Укажите полученный код в соответствующее поле. Сохраните изменения и изучите подробности бонуса.Промокод 1xBet на 2026 год можно взять по ссылке: 1xbet промокод на 100 рублей.
Jasonbrado
22 Oct 25 at 1:01 pm
лучшие seo агентства [url=https://top-10-seo-prodvizhenie.ru/]https://top-10-seo-prodvizhenie.ru/[/url] .
top 10 seo prodvijenie_xgKa
22 Oct 25 at 1:04 pm
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Запросить дополнительные данные – https://rpasminio.cl/?p=1118
Justincal
22 Oct 25 at 1:06 pm
Капельница от запоя в Нижнем Новгороде — процедура, направленная на детоксикацию организма и восстановление нормального самочувствия. Она включает в себя введение препаратов, способствующих выведению токсинов и восстановлению функций органов.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-nizhnij-novgorod12.ru/]скорая вывод из запоя в нижний новгороде[/url]
CharlesDof
22 Oct 25 at 1:07 pm
купить диплом швеи [url=https://www.rudik-diplom12.ru]купить диплом швеи[/url] .
Diplomi_tdPi
22 Oct 25 at 1:08 pm
купить диплом в омске [url=http://rudik-diplom2.ru]купить диплом в омске[/url] .
Diplomi_uepi
22 Oct 25 at 1:09 pm
купить медицинский диплом медсестры [url=https://frei-diplom13.ru]купить медицинский диплом медсестры[/url] .
Diplomi_cikt
22 Oct 25 at 1:09 pm
рекламное агентство seo [url=www.seo-prodvizhenie-reiting-kompanij.ru/]www.seo-prodvizhenie-reiting-kompanij.ru/[/url] .
seo prodvijenie reiting kompanii_ulst
22 Oct 25 at 1:10 pm
купить диплом программиста [url=https://rudik-diplom7.ru]купить диплом программиста[/url] .
Diplomi_kbPl
22 Oct 25 at 1:10 pm
купить диплом института с реестром [url=https://frei-diplom5.ru]купить диплом института с реестром[/url] .
Diplomi_eqPa
22 Oct 25 at 1:13 pm
перевод научно технических текстов [url=https://teletype.in/@alexd78/HN462R01hzy/]https://teletype.in/@alexd78/HN462R01hzy/[/url] .
Vidi perevodov v buro Perevod i Pravo_shst
22 Oct 25 at 1:13 pm
рекламное агентство продвижение сайта [url=seo-prodvizhenie-reiting-kompanij.ru]seo-prodvizhenie-reiting-kompanij.ru[/url] .
seo prodvijenie reiting kompanii_eyst
22 Oct 25 at 1:13 pm
Доброго!
праведность в христианстве
Полная информация по ссылке – https://www.gada.su/
Лингвистика — наука, изучающая язык, [url=https://www.gada.su/]Кремниево силиконовая долина[/url], Кремниево силиконовая долина
Удачи и успехов в жизни и саморазвитии!
JamesTipsy
22 Oct 25 at 1:13 pm
ИТ меняют систему образования kraken сайт кракен онион тор кракен онион зеркало кракен даркнет маркет
RichardPep
22 Oct 25 at 1:15 pm
https://www.dropbox.com/scl/fi/a7yyslhrdftmimcr5ihb2/Untitled-1.paper?rlkey=ymxxo8faym1hrht2xafmx552r&st=hfk97p41&dl=0
Gordonren
22 Oct 25 at 1:16 pm
купить медицинский диплом с занесением в реестр [url=http://frei-diplom6.ru]купить медицинский диплом с занесением в реестр[/url] .
Diplomi_zlOl
22 Oct 25 at 1:16 pm
Стационарное лечение запоя в Воронеже — индивидуальный подход к каждому пациенту. Мы предлагаем комфортные условия и профессиональную помощь для быстрого и безопасного вывода из запоя.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh24.ru/]вывод из запоя в стационаре анонимно в воронеже[/url]
Gregorykip
22 Oct 25 at 1:17 pm
Стационарное лечение запоя в Воронеже — индивидуальный подход к каждому пациенту. Мы предлагаем комфортные условия и профессиональную помощь для быстрого и безопасного вывода из запоя.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh22.ru/]нарколог вывод из запоя в стационаре[/url]
Craigret
22 Oct 25 at 1:18 pm
Good post. I learn something new and challenging on websites I stumbleupon on a daily
basis. It’s always interesting to read through content from other
authors and use something from their web sites.
casino utan spelpaus
22 Oct 25 at 1:19 pm
В «Частном Медике 24» в Самаре лечение организовано так, чтобы пациент чувствовал себя безопасно и защищённо.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-v-stacionare-samara24.ru/]быстрый вывод из запоя в стационаре самара[/url]
Carloscealp
22 Oct 25 at 1:20 pm
Minotaurus ICO’s market research shines in concept. $MTAUR holders get DAO say. Presale hype justified.
minotaurus presale
WilliamPargy
22 Oct 25 at 1:21 pm
купить сертификат специалиста [url=http://rudik-diplom7.ru/]купить сертификат специалиста[/url] .
Diplomi_aoPl
22 Oct 25 at 1:21 pm
If you would like to grow your familiarity only keep visiting this site and be
updated with the hottest news update posted here.
Zentravex TEST
22 Oct 25 at 1:23 pm
сео продвижение заказать москва [url=https://seo-prodvizhenie-reiting-kompanij.ru/]сео продвижение заказать москва[/url] .
seo prodvijenie reiting kompanii_qlst
22 Oct 25 at 1:23 pm
диплом с занесением в реестр купить [url=http://frei-diplom6.ru/]диплом с занесением в реестр купить[/url] .
Diplomi_aqOl
22 Oct 25 at 1:24 pm
Superb blog! Do you have any suggestions for aspiring writers?
I’m planning to start my own website soon but I’m a
little lost on everything. Would you propose starting with
a free platform like WordPress or go for a paid option? There are so many choices out
there that I’m totally confused .. Any ideas? Bless you!
dewascatter
22 Oct 25 at 1:25 pm
купить диплом с проводкой [url=http://frei-diplom5.ru/]купить диплом с проводкой[/url] .
Diplomi_rjPa
22 Oct 25 at 1:25 pm
https://enkling.com/read-blog/55292
RogelioItelt
22 Oct 25 at 1:26 pm
купить диплом в каменске-шахтинском [url=rudik-diplom2.ru]rudik-diplom2.ru[/url] .
Diplomi_zqpi
22 Oct 25 at 1:26 pm
wetten handicap bedeutung
My web page :: sportwetten lizenz österreich (Louanne)
Louanne
22 Oct 25 at 1:28 pm