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!
Мы искали подрядчика, который реально даёт результат. Mihaylov Digital оказались именно такой компанией. Сайт вырос в поиске, заявки пошли стабильно. Отличное сотрудничество https://mihaylov.digital/
Steventob
3 Oct 25 at 7:02 am
СтройСинтез построил для нас коттедж под ключ в Ленобласти. Мы выбрали кирпичный дом с двумя этажами и гаражом, и результат получился отличным. Качество работы высокое, дом комфортный и красивый. Благодарим за профессионализм: https://stroysyntez.com/
Brianvop
3 Oct 25 at 7:03 am
Онлайн магазин – купить мефедрон, кокаин, бошки
Jeromeliz
3 Oct 25 at 7:03 am
последние новости спорта [url=https://novosti-sporta-16.ru/]novosti-sporta-16.ru[/url] .
novosti sporta_oesi
3 Oct 25 at 7:03 am
Круглосуточный нарколог на дому — это незаменимая помощь для тех, кто нуждающихся в квалифицированной помощи при зависимости от алкоголя или зависимости от наркотиков. Квалифицированный нарколог может предоставить лечение зависимости в дома, обеспечивая медицинскую помощь на дому. Выездной нарколог предлагает конфиденциальное лечение, включая очистку организма и психологическую поддержку. При вызове наркологу вы получите круглосуточную помощь и консультацию специалиста. Услуги нарколога включают реабилитацию зависимых, что позволяет эффективно справляться с проблемами и возвращать здоровье. Не ждите, чтобы решить проблему, обращайтесь за помощью уже сегодня на vivod-iz-zapoya-vladimir020.ru.
lechenievladimirNeT
3 Oct 25 at 7:03 am
стоимость услуг экскаватора погрузчика [url=https://www.arenda-ekskavatora-pogruzchika-cena.ru]стоимость услуг экскаватора погрузчика[/url] .
arenda ekskavatora pogryzchika cena_abSr
3 Oct 25 at 7:04 am
http://Onestopclean.kr/bbs/board.php?bo_table=free&wr_id=729053
http://Onestopclean.kr/bbs/board.php?bo_table=free&wr_id=729053
3 Oct 25 at 7:04 am
купить диплом в троицке [url=rudik-diplom14.ru]rudik-diplom14.ru[/url] .
Diplomi_gnea
3 Oct 25 at 7:05 am
новости чемпионатов [url=https://novosti-sporta-17.ru]https://novosti-sporta-17.ru[/url] .
novosti sporta_blOi
3 Oct 25 at 7:05 am
https://www.wildberries.ru/catalog/514992745/detail.aspx
Kevinsaush
3 Oct 25 at 7:05 am
Joined $MTAUR token hunt—presale bonuses stacking. Maze treasures and creature fights immersive. This project’s viral potential high.
mtaur token
WilliamPargy
3 Oct 25 at 7:06 am
https://tcsn.tcteamcorp.com/blogs/96847/Online-Beting-Typically-the-Handheld-Improvement-from-Advanced-Gaming
TommyEncop
3 Oct 25 at 7:06 am
https://belconsole.ru/club/forum/messages/forum2/topic1572/message49575/?result=new#message49575
AlvinScova
3 Oct 25 at 7:07 am
аренда экскаватора смена [url=www.arenda-ekskavatora-pogruzchika-cena.ru]www.arenda-ekskavatora-pogruzchika-cena.ru[/url] .
arenda ekskavatora pogryzchika cena_jqSr
3 Oct 25 at 7:07 am
сайт прогнозов [url=www.stavka-12.ru]www.stavka-12.ru[/url] .
stavka_loSi
3 Oct 25 at 7:07 am
https://yerkramas.org/article/198234/professionalnye-B2B-platformy-dlya-effektivnyx-zakupok-tovarov-iz-kitaya
GeraldObedo
3 Oct 25 at 7:09 am
честные прогнозы на спорт [url=https://prognozy-na-sport-12.ru/]честные прогнозы на спорт[/url] .
prognozi na sport_ueMn
3 Oct 25 at 7:11 am
ставки на спорт прогнозы [url=http://www.stavka-12.ru]ставки на спорт прогнозы[/url] .
stavka_uxSi
3 Oct 25 at 7:12 am
Купить диплом колледжа в Севастополь [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_fgea
3 Oct 25 at 7:13 am
спортивные новости сегодня [url=www.novosti-sporta-17.ru/]www.novosti-sporta-17.ru/[/url] .
novosti sporta_tiOi
3 Oct 25 at 7:13 am
спортивные новости сегодня [url=www.novosti-sporta-16.ru/]www.novosti-sporta-16.ru/[/url] .
novosti sporta_knsi
3 Oct 25 at 7:15 am
прогнозы на спорт сегодня от профессионалов [url=www.prognozy-na-sport-11.ru]www.prognozy-na-sport-11.ru[/url] .
prognozi na sport_ddPa
3 Oct 25 at 7:16 am
онлайн прогнозы на спорт [url=http://www.prognozy-na-sport-12.ru]онлайн прогнозы на спорт[/url] .
prognozi na sport_ccMn
3 Oct 25 at 7:16 am
1win aviator strategiyasi [url=https://www.1win5507.ru]1win aviator strategiyasi[/url]
1win_pokr
3 Oct 25 at 7:18 am
Incredible story there. What occurred after? Thanks!
Brighton hotels for families with children
3 Oct 25 at 7:18 am
новости легкой атлетики [url=www.novosti-sporta-16.ru]www.novosti-sporta-16.ru[/url] .
novosti sporta_gvsi
3 Oct 25 at 7:20 am
бесплатные прогнозы на спорт [url=https://prognozy-na-sport-12.ru/]бесплатные прогнозы на спорт[/url] .
prognozi na sport_naMn
3 Oct 25 at 7:20 am
ghjuyjps [url=https://stavka-12.ru]https://stavka-12.ru[/url] .
stavka_umSi
3 Oct 25 at 7:20 am
купить диплом в находке [url=http://rudik-diplom8.ru]купить диплом в находке[/url] .
Diplomi_upMt
3 Oct 25 at 7:20 am
сайт спортивных прогнозов [url=http://stavka-10.ru]http://stavka-10.ru[/url] .
stavka_wcSi
3 Oct 25 at 7:20 am
бесплатные прогнозы на спорт на сегодня [url=https://prognozy-na-sport-11.ru/]https://prognozy-na-sport-11.ru/[/url] .
prognozi na sport_kyPa
3 Oct 25 at 7:24 am
Слив курсов [url=https://sliv.fun]https://sliv.fun[/url] .
Sliv kyrsov_yfEn
3 Oct 25 at 7:25 am
ставки на футбол сегодня 100 процентный [url=prognozy-na-futbol-9.ru]prognozy-na-futbol-9.ru[/url] .
prognozi na fytbol_kfea
3 Oct 25 at 7:25 am
новости спорта россии [url=http://novosti-sporta-16.ru]http://novosti-sporta-16.ru[/url] .
novosti sporta_xgsi
3 Oct 25 at 7:26 am
Эта статья сочетает в себе как полезные, так и интересные сведения, которые обогатят ваше понимание насущных тем. Мы предлагаем практические советы и рекомендации, которые легко внедрить в повседневную жизнь. Узнайте, как улучшить свои навыки и обогатить свой опыт с помощью простых, но эффективных решений.
Узнай первым! – https://blog.ihnizdo.cz/2015/10/12/inspirace-omalovanky-pro-dospele
Stephenpubre
3 Oct 25 at 7:27 am
спорт 24 часа [url=www.novosti-sporta-15.ru/]www.novosti-sporta-15.ru/[/url] .
novosti sporta_qrma
3 Oct 25 at 7:28 am
Закладки тут – купить гашиш, мефедрон, альфа-РїРІРї
Jeromeliz
3 Oct 25 at 7:29 am
sliv.fun [url=sliv.fun]sliv.fun[/url] .
Sliv kyrsov_xdEn
3 Oct 25 at 7:30 am
онлайн прогнозы на спорт [url=http://prognozy-na-sport-11.ru]http://prognozy-na-sport-11.ru[/url] .
prognozi na sport_mqPa
3 Oct 25 at 7:33 am
обзор спортивных событий [url=http://www.novosti-sporta-15.ru]http://www.novosti-sporta-15.ru[/url] .
novosti sporta_oema
3 Oct 25 at 7:34 am
Если вы ищете качественного ресурса, то [url=https://gim6tomsk.ru/food/]вавада зеркало[/url]— лучший выбор. Тут огромное количество автоматов, быстрые транзакции и профессиональная команда. Без сомнений стоит зайти!
BillieNunse
3 Oct 25 at 7:35 am
https://www.indiegogo.com/individuals/38793322
TommyEncop
3 Oct 25 at 7:35 am
https://ganap.co.uk/blog/how-to-choose-a-laptop-car-charger
AlvinScova
3 Oct 25 at 7:36 am
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.
Feel free to surf to my blog post Rainbet
Rainbet
3 Oct 25 at 7:36 am
прогнозы на ставки на спорт на сегодня [url=https://prognozy-na-sport-12.ru/]https://prognozy-na-sport-12.ru/[/url] .
prognozi na sport_maMn
3 Oct 25 at 7:36 am
Slivfun [url=https://sliv.fun/]https://sliv.fun/[/url] .
Sliv kyrsov_diEn
3 Oct 25 at 7:36 am
новости олимпиады [url=https://novosti-sporta-16.ru/]https://novosti-sporta-16.ru/[/url] .
novosti sporta_ubsi
3 Oct 25 at 7:37 am
спортивные новости сегодня [url=http://www.novosti-sporta-15.ru]http://www.novosti-sporta-15.ru[/url] .
novosti sporta_iqma
3 Oct 25 at 7:38 am
стоимость услуг экскаватора погрузчика [url=arenda-ekskavatora-pogruzchika-cena.ru]стоимость услуг экскаватора погрузчика[/url] .
arenda ekskavatora pogryzchika cena_ldSr
3 Oct 25 at 7:38 am
купить диплом в салавате [url=https://rudik-diplom4.ru/]купить диплом в салавате[/url] .
Diplomi_syOr
3 Oct 25 at 7:41 am