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://srochnyj-vyvod-iz-zapoya.ru/]вывод из запоя на дому круглосуточно в казани[/url]
TerryTew
7 Sep 25 at 12:37 am
Мы готовы предложить документы ВУЗов, расположенных в любом регионе России. Купить диплом университета:
[url=http://raussga.flybb.ru/viewtopic.php?f=12&t=2892/]купить аттестат за 11 класс в иркутске[/url]
Diplomi_loPn
7 Sep 25 at 12:37 am
https://www.betterplace.org/en/organisations/67620
Marionploge
7 Sep 25 at 12:38 am
экстренный вывод из запоя
vivod-iz-zapoya-chelyabinsk009.ru
вывод из запоя цена
alkogolizmchelyabinskNeT
7 Sep 25 at 12:38 am
кракен onion kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
7 Sep 25 at 12:39 am
В Люберцах капельница от запоя доступна круглосуточно — в клинике Stop Alko её ставят как на дому, так и в стационаре.
Изучить вопрос глубже – [url=https://kapelnica-ot-zapoya-lyubercy12.ru/]капельница от запоя выезд[/url]
AnthonyVah
7 Sep 25 at 12:40 am
легально купить диплом [url=http://educ-ua12.ru]легально купить диплом[/url] .
Diplomi_mrMt
7 Sep 25 at 12:40 am
I enjoy what you guys are up too. This sort of clever work and reporting!
Keep up the terrific works guys I’ve included you
guys to our blogroll.
Download YouTube Videos Online
7 Sep 25 at 12:43 am
Please let me know if you’re looking for a article writer for your site.
You have some really good articles and I feel I would be a good asset.
If you ever want to take some of the load off, I’d really like
to write some articles for your blog in exchange for a link back to mine.
Please blast me an email if interested. Kudos!
Snapchat Downloader
7 Sep 25 at 12:43 am
mostbet link [url=https://www.mostbet4158.ru]mostbet link[/url]
mostbet_jwEn
7 Sep 25 at 12:44 am
https://mayanhjp.com/tests/pgs/melbet_promo_code__38.html
https://mayanhjp.com/tests/pgs/melbet_promo_code__38.html
7 Sep 25 at 12:44 am
букмекерская контора mostbet [url=mostbet4157.ru]mostbet4157.ru[/url]
mostbet_efOi
7 Sep 25 at 12:46 am
диплом купить реестр [url=https://educ-ua13.ru/]диплом купить реестр[/url] .
Diplomi_axpn
7 Sep 25 at 12:46 am
dark market list darkmarket 2025 nexus shop [url=https://privatedarknetmarket.com/ ]dark web sites [/url]
Robertalima
7 Sep 25 at 12:48 am
dark web market urls dark web drug marketplace darknet drug store [url=https://darknetmarketgate.com/ ]nexus market url [/url]
DwayneAricE
7 Sep 25 at 12:49 am
https://chelny.agregatka.ru/media/pgs/chto_vliyaet_na_vremya_reabilitacii_bolynyh_skoliozom.html
RichardRhype
7 Sep 25 at 12:51 am
https://whatwood.ru/pag/kak_ponyaty_chto_pora_uvolynyatysya_yavnye_priznaki_vygoraniya.html
RichardRhype
7 Sep 25 at 12:53 am
купить легально диплом [url=educ-ua13.ru]купить легально диплом[/url] .
Diplomi_nxpn
7 Sep 25 at 12:54 am
https://www.pinterest.com/officialpromocode/_profile/
RichardSot
7 Sep 25 at 12:57 am
Хотите оформить медкнижка за 1 день без похода к врачу? На [url=https://med-bez-boli.ru]https://med-bez-boli.ru[/url] можно оформить или обновить официальную медкнижку легально, без прохождения врачей — оперативно и официально. Работаем с реальной клиникой и выдаём медкнижки нового формата, оформляем настоящую медкнижку, которую фиксируют в единой системе. Это комфортно, законно и по доступной стоимости. Все детали смотрите — санитарная книжка без врачей, быстрое оформление, санитарная книжка онлайн.
Spravkisia
7 Sep 25 at 12:57 am
https://www.atrium-patrimoine.com/wp-content/artcls/?code_promo_linebet_bonus_de_bienvenue.html
RichardSot
7 Sep 25 at 12:59 am
https://www.walat.nl/
walat-921
7 Sep 25 at 1:00 am
mostbet скачать на андроид официального сайта [url=https://www.mostbet4157.ru]https://www.mostbet4157.ru[/url]
mostbet_nmOi
7 Sep 25 at 1:01 am
https://hub.docker.com/u/katlynlovely1982
Marionploge
7 Sep 25 at 1:01 am
mostvet [url=https://mostbet4170.ru/]https://mostbet4170.ru/[/url]
mostbet_vaPi
7 Sep 25 at 1:02 am
Доказательная медицина: мы используем только проверенные и эффективные методы, основанные на последних научных исследованиях в области наркологии и психиатрии.
Получить дополнительную информацию – [url=https://srochno-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-v-kruglosutochno-v-ufe.ru/]вывод из запоя капельница на дому в уфе[/url]
JesusGes
7 Sep 25 at 1:04 am
кракен даркнет маркет kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
7 Sep 25 at 1:09 am
купить диплом в кировограде [url=www.educ-ua4.ru/]www.educ-ua4.ru/[/url] .
Diplomi_mrPl
7 Sep 25 at 1:09 am
mostbet uz online [url=https://mostbet4170.ru]mostbet uz online[/url]
mostbet_odPi
7 Sep 25 at 1:10 am
kraken зеркало kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
7 Sep 25 at 1:10 am
mostbet yuklab olish [url=http://mostbet4170.ru]mostbet yuklab olish[/url]
mostbet_adPi
7 Sep 25 at 1:12 am
https://www.walat.nl/
walat-886
7 Sep 25 at 1:12 am
купить диплом с регистрацией [url=educ-ua12.ru]купить диплом с регистрацией[/url] .
Diplomi_uhMt
7 Sep 25 at 1:16 am
Hey very interesting blog!
Nitric Boost Ultra
7 Sep 25 at 1:17 am
Hey there I am so glad I found your weblog, I really found
you by mistake, while I was researching on Yahoo for something
else, Regardless I am here now and would just like to say thank you for a marvelous post and a all round entertaining blog (I also love the theme/design),
I don’t have time to look over it all at the minute but I have book-marked it and also included your RSS
feeds, so when I have time I will be back to read much more, Please do keep up
the awesome b.
Useful
7 Sep 25 at 1:24 am
вывод из запоя иркутск
vivod-iz-zapoya-irkutsk008.ru
вывод из запоя цена
vivodirkutskNeT
7 Sep 25 at 1:24 am
https://form.jotform.com/252453601864053
Marionploge
7 Sep 25 at 1:25 am
kraken darknet market kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
7 Sep 25 at 1:25 am
купить диплом колледжа [url=http://educ-ua20.ru/]купить диплом колледжа[/url] .
Diplomi_urEn
7 Sep 25 at 1:26 am
https://www.walat.nl/
walat-447
7 Sep 25 at 1:26 am
купить диплом легальный [url=http://educ-ua13.ru/]купить диплом легальный[/url] .
Diplomi_lupn
7 Sep 25 at 1:28 am
купить диплом о среднем образовании с занесением в реестр [url=www.educ-ua12.ru/]купить диплом о среднем образовании с занесением в реестр[/url] .
Diplomi_ccMt
7 Sep 25 at 1:29 am
nexus site official link dark market link darknet sites [url=https://darknetmarketsgate.com/ ]darkmarket link [/url]
Donaldfup
7 Sep 25 at 1:29 am
https://ihrchq.org/blog/pgs/code-promo-melbet_bonus-sportifs-et-casino.html
hueuiha
7 Sep 25 at 1:29 am
мостбет скачать на андроид [url=https://mostbet4154.ru/]мостбет скачать на андроид[/url]
mostbet_pmki
7 Sep 25 at 1:31 am
https://www.walat.nl/
walat-129
7 Sep 25 at 1:31 am
Have you ever considered creating an e-book or
guest authoring on other sites? I have a blog based on the same subjects you discuss and would really like to have you share some stories/information. I
know my visitors would enjoy your work. If you’re even remotely interested, feel free to send me an e-mail.
https://hongkongpools.today/
Data HK6D
7 Sep 25 at 1:33 am
hi!,I really like your writing so so much! proportion we keep up a correspondence extra approximately
your post on AOL? I require a specialist on this area to resolve my
problem. Maybe that’s you! Having a look ahead to see you.
site
7 Sep 25 at 1:36 am
мосбет скачат [url=mostbet4159.ru]mostbet4159.ru[/url]
mostbet_yaen
7 Sep 25 at 1:37 am
No matter if some one searches for his essential thing, so
he/she desires to be available that in detail, so that thing is maintained over here.
alternatif hargatoto
7 Sep 25 at 1:38 am