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://regrowrxonline.shop/# generic propecia no prescription
AnthonyGique
7 Oct 25 at 5:33 am
купить диплом с реестром цена [url=frei-diplom5.ru]купить диплом с реестром цена[/url] .
Diplomi_vtPa
7 Oct 25 at 5:33 am
новости спорта россии [url=www.sportivnye-novosti-2.ru/]новости спорта россии[/url] .
sportivnie novosti_inma
7 Oct 25 at 5:34 am
Вызов нарколога на дом в Краснодаре — услуга клиники «Детокс». Специалисты оказывают квалифицированную помощь прямо у вас дома.
Подробнее можно узнать тут – [url=https://narkolog-na-dom-krasnodar27.ru/]нарколог на дом цены краснодар[/url]
Charlesshofe
7 Oct 25 at 5:34 am
Когда нужна срочная помощь, служба Stop-Alko в Екатеринбурге может выехать на дом, провести диагностику, капельницу и восстановление сил.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-ekaterinburg26.ru/]нарколог на дом вывод из запоя[/url]
Alfredoneisy
7 Oct 25 at 5:34 am
Buy Amoxicillin for tooth infection: Buy Amoxicillin for tooth infection – Amoxicillin 500mg buy online
Charleshaw
7 Oct 25 at 5:35 am
можно ли купить диплом в реестре [url=https://www.frei-diplom2.ru]можно ли купить диплом в реестре[/url] .
Diplomi_fpEa
7 Oct 25 at 5:35 am
купить диплом в бугульме [url=http://www.rudik-diplom8.ru]купить диплом в бугульме[/url] .
Diplomi_viMt
7 Oct 25 at 5:36 am
диплом техникума старого образца до 1996 г купить [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_mzea
7 Oct 25 at 5:36 am
купить диплом в шахтах [url=https://www.rudik-diplom4.ru]https://www.rudik-diplom4.ru[/url] .
Diplomi_keOr
7 Oct 25 at 5:37 am
купить диплом в сосновом бору [url=https://www.rudik-diplom15.ru]https://www.rudik-diplom15.ru[/url] .
Diplomi_dxPi
7 Oct 25 at 5:38 am
купить диплом в георгиевске [url=http://www.rudik-diplom7.ru]купить диплом в георгиевске[/url] .
Diplomi_qpPl
7 Oct 25 at 5:40 am
В Самаре клиника «Частный Медик 24» предлагает вывод из запоя в стационаре с полным медицинским контролем и комфортными палатами.
Разобраться лучше – [url=https://vyvod-iz-zapoya-v-stacionare-samara23.ru/]быстрый вывод из запоя в стационаре[/url]
Garrettpew
7 Oct 25 at 5:40 am
диплом с реестром купить [url=www.frei-diplom2.ru]диплом с реестром купить[/url] .
Diplomi_pjEa
7 Oct 25 at 5:40 am
купить диплом для техникума цена [url=frei-diplom9.ru]купить диплом для техникума цена[/url] .
Diplomi_krea
7 Oct 25 at 5:40 am
купить диплом в чапаевске [url=https://rudik-diplom3.ru/]купить диплом в чапаевске[/url] .
Diplomi_oaei
7 Oct 25 at 5:40 am
$MTAUR coin stands out with its audited security focus. Extending vesting for bonuses is a no-brainer. Maze battles against creatures? Count me in.
mtaur token
WilliamPargy
7 Oct 25 at 5:42 am
купить диплом в новошахтинске [url=rudik-diplom11.ru]rudik-diplom11.ru[/url] .
Diplomi_uoMi
7 Oct 25 at 5:43 am
купить дипломы о высшем образовании цена [url=https://rudik-diplom8.ru/]купить дипломы о высшем образовании цена[/url] .
Diplomi_lyMt
7 Oct 25 at 5:44 am
Hi there! I just wanted to ask if you ever have any problems with hackers?
My last blog (wordpress) was hacked and I ended up losing many months of hard
work due to no data backup. Do you have any methods to prevent hackers?
Azione Kivo Recensione
7 Oct 25 at 5:45 am
I’m really enjoying the design and layout of your blog. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you
hire out a designer to create your theme? Outstanding work!
ZynerixPro
7 Oct 25 at 5:49 am
В Краснодаре клиника «Детокс» предоставляет услугу вызова нарколога на дом. Специалисты приедут к вам в течение 1–2 часов, проведут осмотр и назначат необходимое лечение. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Получить дополнительные сведения – [url=https://narkolog-na-dom-krasnodar26.ru/]платный нарколог на дом[/url]
RobertCom
7 Oct 25 at 5:49 am
как купить диплом с проводкой [url=http://frei-diplom3.ru]как купить диплом с проводкой[/url] .
Diplomi_wdKt
7 Oct 25 at 5:49 am
ダッチワイフ エロand dinner,and to-morrow thesame and the day after the same and always the same .
ラブドール
7 Oct 25 at 5:50 am
купить речной диплом [url=http://rudik-diplom3.ru/]купить речной диплом[/url] .
Diplomi_xsei
7 Oct 25 at 5:50 am
In thefarthest stable a light was glimmering.lovedollSomething seemed to tell himthat the body was there,
ラブドール
7 Oct 25 at 5:51 am
купить диплом в клинцах [url=www.rudik-diplom7.ru]купить диплом в клинцах[/url] .
Diplomi_qjPl
7 Oct 25 at 5:51 am
Программы вывода из запоя в Самаре включают детоксикацию, медикаментозную поддержку и работу с психотерапевтом.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]нарколог вывод из запоя в стационаре в самаре[/url]
Hectorpam
7 Oct 25 at 5:51 am
https://derufa-crimea.ru
HowardGoony
7 Oct 25 at 5:51 am
Пациентам в Самаре предлагается анонимное лечение в стационаре с круглосуточным уходом и безопасными условиями.
Подробнее тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]наркология вывод из запоя в стационаре[/url]
Hectorpam
7 Oct 25 at 5:51 am
купить диплом в северске [url=www.rudik-diplom15.ru]www.rudik-diplom15.ru[/url] .
Diplomi_yzPi
7 Oct 25 at 5:52 am
When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is
added I get three e-mails with the same comment. Is there any
way you can remove me from that service? Cheers!
казино с бонусами без первого депозита
7 Oct 25 at 5:53 am
купить диплом колледжа недорого [url=www.frei-diplom9.ru]www.frei-diplom9.ru[/url] .
Diplomi_nmea
7 Oct 25 at 5:53 am
диплом техникума купить [url=http://frei-diplom10.ru/]диплом техникума купить[/url] .
Diplomi_twEa
7 Oct 25 at 5:54 am
buy amoxil [url=https://amoxdirectusa.com/#]buy amoxil[/url] Amoxicillin 500mg buy online
Davidbax
7 Oct 25 at 5:54 am
как купить диплом с занесением в реестр [url=https://frei-diplom6.ru/]как купить диплом с занесением в реестр[/url] .
Diplomi_mjOl
7 Oct 25 at 5:54 am
купить диплом в черкесске [url=rudik-diplom2.ru]купить диплом в черкесске[/url] .
Diplomi_appi
7 Oct 25 at 5:55 am
купить диплом в виннице [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .
Diplomi_shea
7 Oct 25 at 5:55 am
купить диплом с занесением в реестр новокузнецке [url=frei-diplom3.ru]купить диплом с занесением в реестр новокузнецке[/url] .
Diplomi_mvKt
7 Oct 25 at 5:57 am
купить диплом в железногорске [url=www.rudik-diplom4.ru]www.rudik-diplom4.ru[/url] .
Diplomi_qmOr
7 Oct 25 at 5:57 am
новости легкой атлетики [url=https://novosti-sporta-8.ru/]novosti-sporta-8.ru[/url] .
novosti sporta_scMa
7 Oct 25 at 5:58 am
купить диплом в красноярске [url=http://rudik-diplom11.ru]купить диплом в красноярске[/url] .
Diplomi_boMi
7 Oct 25 at 5:59 am
Стационарное лечение запоя в Воронеже — индивидуальный подход к каждому пациенту. Мы предлагаем комфортные условия и профессиональную помощь для быстрого и безопасного вывода из запоя.
Получить больше информации – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh24.ru/]наркология вывод из запоя в стационаре[/url]
Ronaldsteaf
7 Oct 25 at 6:00 am
купить диплом в великих луках [url=www.rudik-diplom15.ru]купить диплом в великих луках[/url] .
Diplomi_qrPi
7 Oct 25 at 6:00 am
В Воронеже клиника «Частный Медик 24» предлагает программу вывода из запоя в стационаре по цене от 6500 ?. Здесь вас ждут комфортные палаты, круглосуточный медицинский контроль и безопасные методы детоксикации, включая капельницы и восстановительное лечение. Анонимность гарантирована, без лишних формальностей и без постановки на учёт.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh24.ru/]вывод из запоя в стационаре воронеж[/url]
Ronaldsteaf
7 Oct 25 at 6:00 am
я купил проведенный диплом [url=http://www.frei-diplom2.ru]я купил проведенный диплом[/url] .
Diplomi_ffEa
7 Oct 25 at 6:01 am
Hurrah, that’s what I was searching for, what a stuff!
existing here at this web site, thanks admin of this web site.
pet clinic
7 Oct 25 at 6:01 am
I do believe all the ideas you have offered
for your post. They’re very convincing and will certainly work.
Still, the posts are very short for newbies.
May you please prolong them a bit from next time?
Thank you for the post.
buôn bán nội tạng
7 Oct 25 at 6:01 am
https://Stayzada.com/bbs/board.php?bo_table=free&wr_id=352965
https://Stayzada.com/bbs/board.php?bo_table=free&wr_id=352965
7 Oct 25 at 6:02 am
купить диплом в саранске [url=http://www.rudik-diplom2.ru]купить диплом в саранске[/url] .
Diplomi_bupi
7 Oct 25 at 6:02 am