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-diplom6.ru]купить диплом о высшем образовании реестр[/url] .
Diplomi_hiOl
22 Oct 25 at 8:37 am
купить диплом с проводкой моего [url=frei-diplom3.ru]купить диплом с проводкой моего[/url] .
Diplomi_jwKt
22 Oct 25 at 8:37 am
englische wettanbieter
Have a look at my web-site; wie am besten wetten (Tommie)
Tommie
22 Oct 25 at 8:40 am
Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех!
ТОП-5 причин узнать больше – https://jardincasadecampo.com/nurturing-the-bond-between-humans-and-nature
JustinInfiz
22 Oct 25 at 8:40 am
купить диплом лаборанта [url=http://www.rudik-diplom5.ru]купить диплом лаборанта[/url] .
Diplomi_afma
22 Oct 25 at 8:41 am
Attractive section of content. I just stumbled upon your site and in accession capital to claim that I acquire actually enjoyed account your blog posts.
Anyway I will be subscribing to your augment and even I achievement you access persistently rapidly.
88aa
22 Oct 25 at 8:41 am
Без ИТ уже невозможно представить современный бизнес сайт kraken onion kraken рабочая ссылка onion сайт kraken onion kraken darknet
RichardPep
22 Oct 25 at 8:42 am
москва купить диплом о высшем образовании с занесением в реестр [url=https://frei-diplom2.ru/]москва купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_bfEa
22 Oct 25 at 8:43 am
kraken СПб
kraken darknet
JamesDaync
22 Oct 25 at 8:44 am
Доброго!
Устали от блокировок? Пора купить виртуальный номер навсегда. Мы предлагаем надёжную возможность купить виртуальный номер навсегда с поддержкой. Анонимность и удобство — когда вы решаете купить виртуальный номер навсегда. Убедитесь, как легко купить виртуальный номер навсегда в нашем сервисе.
Полная информация по ссылке – https://malbusiness.com/virtualnyj-nomer-dlya-registratsii-na-avito-preimushhestva-i-osobennosti-ispolzovaniya/
купить виртуальный номер, купить виртуальный номер для смс навсегда, купить виртуальный номер для смс навсегда
купить номер телефона навсегда, купить виртуальный номер навсегда, купить постоянный виртуальный номер
Удачи и комфорта в общении!
Lynwoodassok
22 Oct 25 at 8:44 am
требования медицинского перевода [url=www.telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16/]www.telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16/[/url] .
Medicinskii perevod_poEr
22 Oct 25 at 8:44 am
купить диплом о высшем образовании с реестром [url=http://www.frei-diplom3.ru]купить диплом о высшем образовании с реестром[/url] .
Diplomi_jxKt
22 Oct 25 at 8:44 am
купить диплом в братске [url=https://www.rudik-diplom1.ru]купить диплом в братске[/url] .
Diplomi_uger
22 Oct 25 at 8:45 am
перевод научно технических текстов [url=https://teletype.in/@alexd78/HN462R01hzy/]https://teletype.in/@alexd78/HN462R01hzy/[/url] .
Vidi perevodov v buro Perevod i Pravo_bpst
22 Oct 25 at 8:45 am
диплом купить колледжа [url=http://frei-diplom8.ru]http://frei-diplom8.ru[/url] .
Diplomi_tisr
22 Oct 25 at 8:45 am
Всех благ данному магазину!!!
https://khartsyzkod.ru
Да,мне тоже первый класс как то ближе и недорого…
Donaldmoire
22 Oct 25 at 8:46 am
горный техникум диплом купить [url=http://frei-diplom9.ru/]горный техникум диплом купить[/url] .
Diplomi_npea
22 Oct 25 at 8:47 am
Ahaa, its nice discussion concerning this piece of writing here at this blog, I
have read all that, so now me also commenting here.
fk22
22 Oct 25 at 8:48 am
The Supreme Court agreed Monday to decide if the federal government may bar certain drug users from owning guns or if the law violates the Second Amendment, taking up a second significant guns case of its current term.
[url=https://kra–42-cc.ru]kra42[/url]
The appeal represents a rare circumstance in which the Trump administration is defending a gun prohibition, which it described in briefing at the Supreme Court as a “narrow” limitation on one of “Americans’ most cherished freedoms.”
[url=https://kra–42—cc.ru]kra42 cc[/url]
The case centers on Ali Danial Hemani, a dual citizen of the United States and Pakistan, who was indicted in 2023 on a single count of violating the guns-and-drugs law after the FBI found a 9mm pistol, 60 grams of marijuana, and 4.7 grams of cocaine at his family home. This prosecution, the government told the high court, rested Hemani’s habitual use of marijuana.
The court will likely hear arguments in the Hemani case next year and hand down a decision by the end of June.
kra42
https://kra-42at.net
A federal district court dismissed the charge, noting a landmark decision from the Supreme Court in 2022 that made it easier for Americans to carry handguns in public and also required similar gun prohibitions to have a connection to history.
But just how closely analogous prosecutors must come to a historic law has been a matter of debate. Last year, for instance, the Supreme Court upheld a federal law that bars guns for Americans who are the subject of certain domestic abuse restraining orders, rejecting an argument pressed by gun rights groups that the prohibition violated the Second Amendment.
The conservative 5th US Circuit Court of Appeals upheld that decision, holding in a brief decision that the historical record points only to laws that barred guns for Americans who are actively intoxicated or under the influence of drugs at the time of their arrest. The government, the court ruled, could not target habitual users.
The Trump administration appealed that decision.
Wendellnic
22 Oct 25 at 8:48 am
купить диплом в симферополе [url=https://rudik-diplom5.ru]https://rudik-diplom5.ru[/url] .
Diplomi_epma
22 Oct 25 at 8:48 am
раскрутка сайта москва [url=https://seo-prodvizhenie-reiting-kompanij.ru/]раскрутка сайта москва[/url] .
seo prodvijenie reiting kompanii_hpst
22 Oct 25 at 8:50 am
как можно купить диплом колледжа [url=http://frei-diplom8.ru/]http://frei-diplom8.ru/[/url] .
Diplomi_ndsr
22 Oct 25 at 8:52 am
купить диплом с занесением в реестр оренбург [url=http://frei-diplom1.ru/]купить диплом с занесением в реестр оренбург[/url] .
Diplomi_qnOi
22 Oct 25 at 8:52 am
купить диплом бухгалтера [url=http://rudik-diplom5.ru/]купить диплом бухгалтера[/url] .
Diplomi_itma
22 Oct 25 at 8:52 am
топ seo специалистов [url=https://top-10-seo-prodvizhenie.ru/]https://top-10-seo-prodvizhenie.ru/[/url] .
top 10 seo prodvijenie_bsKa
22 Oct 25 at 8:53 am
Эта познавательная публикация погружает вас в море интересного контента, который быстро захватит ваше внимание. Мы рассмотрим важные аспекты темы и предоставим вам уникальные Insights и полезные сведения для дальнейшего изучения.
Интересует подробная информация – https://alkram.info/%D9%84%D9%85%D9%8A%D8%A7%D8%A1-%D8%A8%D9%86%D8%AA-%D9%85%D8%A7%D8%AC%D8%AF-%D8%A8%D9%86-%D8%B3%D8%B9%D9%88%D8%AF-%D9%84%D9%85%D8%AD%D8%A9-%D8%B9%D9%86-%D8%AD%D9%8A%D8%A7%D8%AA%D9%87%D8%A7
Lewisnop
22 Oct 25 at 8:53 am
Этот обзор дает возможность взглянуть на историю и науку под новым углом. Мы представляем редкие факты, неожиданные связи и значимые события, которые помогут вам глубже понять развитие цивилизации и роль человека в ней.
Обратиться к источнику – https://www.media-bloom.ru/uslugi-po-vyvodu-iz-zapoya-pokhmelya-i-lecheniyu-alko-566qp
FrancisSIT
22 Oct 25 at 8:53 am
купить диплом техникума ссср в киеве [url=www.frei-diplom9.ru]купить диплом техникума ссср в киеве[/url] .
Diplomi_gqea
22 Oct 25 at 8:54 am
купить диплом в асбесте [url=https://rudik-diplom11.ru/]купить диплом в асбесте[/url] .
Diplomi_riMi
22 Oct 25 at 8:54 am
кракен онлайн
kraken vk6
JamesDaync
22 Oct 25 at 8:55 am
An outstanding share! I have just forwarded
this onto a colleague who had been conducting a little research on this.
And he in fact bought me breakfast due to the fact that I discovered it for him…
lol. So allow me to reword this…. Thank YOU for the meal!!
But yeah, thanx for spending time to discuss this subject here on your blog.
AU888
22 Oct 25 at 8:56 am
купить диплом вуза с проводкой [url=http://frei-diplom2.ru/]http://frei-diplom2.ru/[/url] .
Diplomi_tsEa
22 Oct 25 at 8:57 am
Где купить План в Завьяловое?Вот нашел https://ilimcity.ru
– нормальные цены, обещают быструю доставку. Может, кто брал у них? Интересует насколько качественный товар?
Stevenref
22 Oct 25 at 8:57 am
купить диплом в выборге [url=rudik-diplom12.ru]rudik-diplom12.ru[/url] .
Diplomi_fqPi
22 Oct 25 at 8:58 am
купить свидетельство о рождении ссср [url=rudik-diplom8.ru]купить свидетельство о рождении ссср[/url] .
Diplomi_dsMt
22 Oct 25 at 8:58 am
купить диплом судоводителя [url=http://rudik-diplom10.ru]купить диплом судоводителя[/url] .
Diplomi_rrSa
22 Oct 25 at 8:59 am
Diving into Minotaurus token details, the 60% presale allocation ensures fair launch. Vesting up to 14 months with 10% bonuses? That’s holder-friendly. Game’s endless runner vibe is pure fun.
minotaurus coin
WilliamPargy
22 Oct 25 at 8:59 am
Эта статья для ознакомления предлагает читателям общее представление об актуальной теме. Мы стремимся представить ключевые факты и идеи, которые помогут читателям получить представление о предмете и решить, стоит ли углубляться в изучение.
Перейти к полной версии – https://www.lingerietester.com/doing-a-cross-country-road-trip
Marcusidomo
22 Oct 25 at 9:01 am
купить диплом слесаря [url=http://www.rudik-diplom4.ru]купить диплом слесаря[/url] .
Diplomi_vpOr
22 Oct 25 at 9:02 am
купить диплом техникума 1997 года [url=https://www.frei-diplom8.ru]купить диплом техникума 1997 года[/url] .
Diplomi_czsr
22 Oct 25 at 9:02 am
купить диплом с занесением в реестр москва [url=https://frei-diplom4.ru]купить диплом с занесением в реестр москва[/url] .
Diplomi_xdOl
22 Oct 25 at 9:03 am
медицинский перевод справок [url=https://telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16/]https://telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16/[/url] .
Medicinskii perevod_qvEr
22 Oct 25 at 9:03 am
kraken обмен
кракен Россия
JamesDaync
22 Oct 25 at 9:04 am
купить диплом техникума легко пять плюс [url=frei-diplom9.ru]купить диплом техникума легко пять плюс[/url] .
Diplomi_ynea
22 Oct 25 at 9:04 am
купить диплом в кузнецке [url=https://rudik-diplom1.ru]https://rudik-diplom1.ru[/url] .
Diplomi_lker
22 Oct 25 at 9:04 am
Отличный сервис, всё работает идеально. DRINKIO доставил заказ раньше заявленного времени, что приятно удивило. Упаковка надёжная, видно, что заботятся о клиенте. Ассортимент большой, удобно, что можно выбрать онлайн. Теперь это мой постоянный вариант доставки https://drinkio105.ru/
Arthurtok
22 Oct 25 at 9:05 am
купить диплом специалиста [url=https://www.rudik-diplom2.ru]купить диплом специалиста[/url] .
Diplomi_anpi
22 Oct 25 at 9:06 am
диплом купить в реестре [url=https://frei-diplom2.ru/]диплом купить в реестре[/url] .
Diplomi_uwEa
22 Oct 25 at 9:06 am
купить диплом спб занесением реестр [url=frei-diplom1.ru]купить диплом спб занесением реестр[/url] .
Diplomi_yeOi
22 Oct 25 at 9:06 am
Potenzmittel rezeptfrei kaufen: Potenzmittel rezeptfrei kaufen – Sildenafil 100 mg bestellen
WilliamUnjup
22 Oct 25 at 9:07 am