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=frei-diplom9.ru]где купить диплом техникума тебя[/url] .
Diplomi_blea
15 Oct 25 at 12:18 pm
Hey I know this is off topic but I was wondering if you knew of
any widgets I could add to my blog that automatically tweet my newest twitter updates.
I’ve been looking for a plug-in like this for quite some time
and was hoping maybe you would have some experience with something like this.
Please let me know if you run into anything.
I truly enjoy reading your blog and I look forward to your new updates.
https://ee88game.net/
15 Oct 25 at 12:19 pm
купить диплом в шахтах [url=https://rudik-diplom4.ru]https://rudik-diplom4.ru[/url] .
Diplomi_boOr
15 Oct 25 at 12:19 pm
купить диплом в кирове [url=http://www.rudik-diplom7.ru]купить диплом в кирове[/url] .
Diplomi_lkPl
15 Oct 25 at 12:21 pm
потолочкин натяжные потолки нижний новгород официальный сайт [url=https://stretch-ceilings-nizhniy-novgorod.ru/]stretch-ceilings-nizhniy-novgorod.ru[/url] .
natyajnie potolki nijnii novgorod_hnPl
15 Oct 25 at 12:23 pm
где можно купить диплом медсестры [url=http://frei-diplom13.ru]где можно купить диплом медсестры[/url] .
Diplomi_srkt
15 Oct 25 at 12:24 pm
pharmacy in mexico [url=https://medicosur.com/#]mexican pharmacy[/url] mexico pharmacy
CareyMag
15 Oct 25 at 12:24 pm
Thanks on your marvelous posting! I seriously enjoyed reading it, you are
a great author. I will ensure that I bookmark your
blog and will eventually come back down the road. I want to encourage you to ultimately continue your
great job, have a nice afternoon!
rodaloft.com
15 Oct 25 at 12:24 pm
купить диплом колледжа в москве [url=www.frei-diplom8.ru]www.frei-diplom8.ru[/url] .
Diplomi_bhsr
15 Oct 25 at 12:25 pm
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Открой скрытое – https://wallahakhi.com/aliquet-lectus-proin-nibhnisl-condimentum-dvenenatis-condimentum
Howardordef
15 Oct 25 at 12:26 pm
купить диплом специалиста [url=https://www.rudik-diplom6.ru]купить диплом специалиста[/url] .
Diplomi_utKr
15 Oct 25 at 12:26 pm
купить старый диплом техникума в спб [url=frei-diplom9.ru]купить старый диплом техникума в спб[/url] .
Diplomi_mkea
15 Oct 25 at 12:27 pm
TG @‌LINKS_DEALER | EFFECTIVE SEO LINKS FOR Spinbetterbet.com
Jamesrab
15 Oct 25 at 12:28 pm
Купить диплом техникума в Донецк [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_rwea
15 Oct 25 at 12:28 pm
купить диплом в черкесске [url=http://rudik-diplom5.ru/]купить диплом в черкесске[/url] .
Diplomi_apma
15 Oct 25 at 12:28 pm
Сверху [url=https://www.igor-scherbakov.ru/muzyka-k-filmam-2020]странице не без; музыкой для кинокартинам 2020 года[/url] хоть почуять, как композитор наводить справки от призывами нестабильного периоде путем искусство. Евонный партитуры данного ступени особенно атмосферны также медитативны, яко отражая точки соприкосновения эмоция эпохи. При этом они сохраняют драматическую выразительность равно кинематографическую функциональность.
AnWap
15 Oct 25 at 12:29 pm
купить диплом с занесением в реестр отзывы [url=https://frei-diplom6.ru]купить диплом с занесением в реестр отзывы[/url] .
Diplomi_bcOl
15 Oct 25 at 12:30 pm
куплю диплом медсестры в москве [url=www.frei-diplom13.ru]куплю диплом медсестры в москве[/url] .
Diplomi_dikt
15 Oct 25 at 12:30 pm
купить диплом в москве [url=http://www.rudik-diplom9.ru]купить диплом в москве[/url] .
Diplomi_qoei
15 Oct 25 at 12:33 pm
купить диплом техникума образца ссср [url=www.frei-diplom9.ru/]купить диплом техникума образца ссср[/url] .
Diplomi_wdea
15 Oct 25 at 12:34 pm
1win az apk yüklə [url=https://1win5005.com/]1win az apk yüklə[/url]
1win_ebml
15 Oct 25 at 12:34 pm
If you would like to increase your familiarity simply
keep visiting this site and be updated with
the most up-to-date news posted here.
https://magrix.ru/
15 Oct 25 at 12:35 pm
Нужна недвижимость? жилье Черногория лучшие объекты для жизни и инвестиций. Виллы, квартиры и дома у моря. Помощь в подборе, оформлении и сопровождении сделки на всех этапах.
nedvizhimost-chernogorii-60
15 Oct 25 at 12:35 pm
купить диплом в архангельске [url=www.rudik-diplom2.ru/]купить диплом в архангельске[/url] .
Diplomi_uapi
15 Oct 25 at 12:36 pm
По окончании курса детоксикации нарколог дает пациенту и его близким подробные рекомендации, помогающие быстрее восстановить здоровье и предотвратить повторные случаи запоев.
Получить дополнительную информацию – http://vyvod-iz-zapoya-novosibirsk0.ru/vyvod-iz-zapoya-czena-novosibirsk/
Johnnynix
15 Oct 25 at 12:37 pm
http://tadalifepharmacy.com/# buy cialis online
Hermandug
15 Oct 25 at 12:37 pm
купить диплом с занесением в реестр [url=www.frei-diplom5.ru/]купить диплом с занесением в реестр[/url] .
Diplomi_hzPa
15 Oct 25 at 12:38 pm
Добро пожаловать в удивительный мир природы России!
Хочу выделить материал про Изучение ООПТ России: парки, заповедники, водоемы.
Ссылка ниже:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Что думаете о красоте природы России? Делитесь мнениями!
fixRow
15 Oct 25 at 12:38 pm
Нужна недвижимость? https://www.nedvizhimost-chernogorii-u-morya.ru/ лучшие объекты для жизни и инвестиций. Виллы, квартиры и дома у моря. Помощь в подборе, оформлении и сопровождении сделки на всех этапах.
nedvizhimost-chernogorii-502
15 Oct 25 at 12:38 pm
I think this is one of the most important information for me.
And i’m glad reading your article. But wanna remark on few general things, The web site style is wonderful, the articles is really excellent : D.
Good job, cheers
Zyskavia Opinie
15 Oct 25 at 12:40 pm
https://telegra.ph/Kupit-optiko-binokl-kazanskij-10-12-5
DennisNeene
15 Oct 25 at 12:41 pm
Аутстаффинг персонала https://skillstaff2.ru для бизнеса: легальное оформление сотрудников, снижение налоговой нагрузки и оптимизация расходов. Работаем с компаниями любого масштаба и отрасли.
skillstaff-216
15 Oct 25 at 12:41 pm
купить диплом в тюмени [url=http://rudik-diplom8.ru]купить диплом в тюмени[/url] .
Diplomi_jeMt
15 Oct 25 at 12:42 pm
купить диплом в норильске [url=https://rudik-diplom13.ru]купить диплом в норильске[/url] .
Diplomi_lson
15 Oct 25 at 12:42 pm
Добро пожаловать в Клубника Казино, где каждый игрок найдет для себя
идеальные условия для выигрыша и наслаждения игрой.
В Клубника Казино представлены самые популярные игровые автоматы,
настольные игры и множество интересных live-игр с реальными дилерами.
В Клубника Казино мы гарантируем полную безопасность и прозрачность всех процессов, чтобы
ваши данные и средства были в надежных руках.
Почему стоит играть именно в клубничка казино играть?
Мы предлагаем щедрые бонусы и акции,
чтобы каждый игрок мог увеличить свои шансы на победу и насладиться
игрой. В Клубника Казино мы ценим
ваше время и гарантируем быстрые выплаты, а наша служба поддержки всегда готова помочь в любой ситуации.
Когда вам стоит начать играть
в Клубника Казино? Не теряйте времени – начните свою игровую карьеру прямо сейчас и получите щедрые бонусы
на первый депозит. Вот что вас ждет:
Воспользуйтесь щедрыми бонусами и бесплатными спинами, чтобы начать игру с преимуществом.
Промо-акции и турниры с крупными призами.
Регулярные обновления и новые игры каждый месяц.
В Клубника Казино каждый момент игры может стать выигрышным для вас.
clubnika казино
15 Oct 25 at 12:44 pm
диплом колледжа купить с занесением в реестр [url=frei-diplom12.ru]frei-diplom12.ru[/url] .
Diplomi_crPt
15 Oct 25 at 12:45 pm
Аутстаффинг персонала https://skillstaff2.ru для бизнеса: легальное оформление сотрудников, снижение налоговой нагрузки и оптимизация расходов. Работаем с компаниями любого масштаба и отрасли.
skillstaff-652
15 Oct 25 at 12:45 pm
купить диплом в кызыле [url=www.rudik-diplom6.ru]купить диплом в кызыле[/url] .
Diplomi_egKr
15 Oct 25 at 12:45 pm
profi wett tipps heute
My web page: kombiwette eine falsch
kombiwette eine falsch
15 Oct 25 at 12:47 pm
купить диплом с проводкой одно [url=www.frei-diplom1.ru]купить диплом с проводкой одно[/url] .
Diplomi_uvOi
15 Oct 25 at 12:47 pm
https://crimea-news.com/other/2024/11/01/1504450.html
Nathanhip
15 Oct 25 at 12:50 pm
affordable Cialis with fast delivery [url=http://tadalifepharmacy.com/#]discreet ED pills delivery in the US[/url] safe online pharmacy for Cialis
CareyMag
15 Oct 25 at 12:50 pm
купить диплом техникума ссср в минске [url=http://frei-diplom12.ru]купить диплом техникума ссср в минске[/url] .
Diplomi_oyPt
15 Oct 25 at 12:52 pm
купить диплом об окончании колледжа в екатеринбурге [url=http://frei-diplom8.ru/]http://frei-diplom8.ru/[/url] .
Diplomi_oesr
15 Oct 25 at 12:53 pm
I was pretty pleased to find this web site. I want to to thank you for your time due to this fantastic read!!
I definitely loved every little bit of it and i also have you book marked to look at new
things in your blog.
đọc phim cấp 3 full hd
15 Oct 25 at 12:54 pm
1win poker otağı [url=1win5005.com]1win5005.com[/url]
1win_xoml
15 Oct 25 at 12:54 pm
Hi there, just became aware of your blog through Google, and found that it’s really informative.
I am gonna watch out for brussels. I will appreciate if you continue this in future.
Lots of people will be benefited from your writing. Cheers!
deutsche online casinos
15 Oct 25 at 12:55 pm
екатеринбург купить диплом в реестр [url=www.frei-diplom1.ru/]екатеринбург купить диплом в реестр[/url] .
Diplomi_jrOi
15 Oct 25 at 12:57 pm
Заказать диплом любого ВУЗа можем помочь. Купить диплом Томск – [url=http://diplomybox.com/kupit-diplom-tomsk/]diplomybox.com/kupit-diplom-tomsk[/url]
Cazrndd
15 Oct 25 at 12:58 pm
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Выяснить больше – https://cambrity.com/2022/01/31/add-multiple-languages-to-your-site
Robertelake
15 Oct 25 at 12:58 pm