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://narkologicheskaya-klinika-mytishchi0.ru/chastnaya-narkologicheskaya-klinika-v-mytishchah
PhillipSok
3 Oct 25 at 3:31 pm
Dragons Fire
Michaelrow
3 Oct 25 at 3:32 pm
купить диплом в благовещенске [url=http://www.rudik-diplom4.ru]купить диплом в благовещенске[/url] .
Diplomi_bvOr
3 Oct 25 at 3:32 pm
как купить диплом с проводкой [url=frei-diplom5.ru]как купить диплом с проводкой[/url] .
Diplomi_hiPa
3 Oct 25 at 3:34 pm
диплом купить с занесением в реестр отзывы [url=https://www.frei-diplom4.ru]https://www.frei-diplom4.ru[/url] .
Diplomi_veOl
3 Oct 25 at 3:35 pm
ceriavpn – A dependable service that balances speed and safety perfectly.
Claudio Fredericksen
3 Oct 25 at 3:36 pm
Hey I am so excited I found your web site, I really found you by mistake, while I was searching on Google for something else, Anyways I am here now and would just like to say thanks for a remarkable post and a all round exciting blog (I also love the theme/design), I don’t have time to read it all at the moment but I have bookmarked it and also added your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the fantastic b.
https://fontanero.com.ua/
Timsothydet
3 Oct 25 at 3:36 pm
купить диплом в зеленодольске [url=https://rudik-diplom2.ru/]купить диплом в зеленодольске[/url] .
Diplomi_sxpi
3 Oct 25 at 3:38 pm
купить диплом с внесением в реестр [url=http://www.frei-diplom3.ru]купить диплом с внесением в реестр[/url] .
Diplomi_tuKt
3 Oct 25 at 3:39 pm
купить государственный диплом с занесением в реестр [url=https://frei-diplom2.ru]купить государственный диплом с занесением в реестр[/url] .
Diplomi_yeEa
3 Oct 25 at 3:40 pm
купить диплом воспитателя [url=www.rudik-diplom4.ru]купить диплом воспитателя[/url] .
Diplomi_jnOr
3 Oct 25 at 3:40 pm
купить легальный диплом техникума [url=frei-diplom6.ru]купить легальный диплом техникума[/url] .
Diplomi_jlOl
3 Oct 25 at 3:40 pm
купить диплом медсестры [url=https://frei-diplom15.ru]купить диплом медсестры[/url] .
Diplomi_jioi
3 Oct 25 at 3:41 pm
купить диплом колледжа с занесением в реестр [url=https://frei-diplom9.ru/]купить диплом колледжа с занесением в реестр[/url] .
Diplomi_btea
3 Oct 25 at 3:42 pm
http://www.detiseti.ru/modules/newbb_plus/viewtopic.php?topic_id=78506&post_id=269335&order=0&viewmode=flat&pid=0&forum=13#269335
OscarWEk
3 Oct 25 at 3:43 pm
купить диплом в лениногорске [url=https://rudik-diplom15.ru/]https://rudik-diplom15.ru/[/url] .
Diplomi_hdPi
3 Oct 25 at 3:44 pm
В Люберцах мы убираем неопределённость уже с первого звонка. Дежурный врач аккуратно уточняет жалобы, длительность запоя, принимаемые лекарства и сопутствующие диагнозы, после чего предлагает безопасную точку входа: выезд на дом, дневной формат или стационар с наблюдением 24/7. Каждую процедуру объясняем простым языком и фиксируем цели на ближайшие часы — снижение тревоги и тремора, «мягкий» сон, стабилизацию давления и пульса. Приватность встроена по умолчанию: минимум данных на старте, нейтральная коммуникация, ограниченный доступ к карте, без постановки на учёт. Такой регламент снимает лишнее напряжение и экономит время, исключая «перекидывания» между отделениями и очереди.
Подробнее можно узнать тут – [url=https://narkologicheskaya-klinika-lyubercy0.ru/]частная наркологическая клиника[/url]
Jorgesmusy
3 Oct 25 at 3:44 pm
This is my first time visit at here and i am genuinely impressed to read all at single place.
Trenqor Logic AI Recenzja
3 Oct 25 at 3:44 pm
https://khasanovich.ru
KevinEdica
3 Oct 25 at 3:44 pm
купить диплом техникума образец [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_tdea
3 Oct 25 at 3:45 pm
купить диплом в пензе [url=https://www.rudik-diplom4.ru]https://www.rudik-diplom4.ru[/url] .
Diplomi_rnOr
3 Oct 25 at 3:45 pm
http://www.detiseti.ru/modules/newbb_plus/viewtopic.php?topic_id=78506&post_id=269335&order=0&viewmode=flat&pid=0&forum=13#269335
OscarWEk
3 Oct 25 at 3:46 pm
купить диплом в камышине [url=http://www.rudik-diplom7.ru]купить диплом в камышине[/url] .
Diplomi_qfPl
3 Oct 25 at 3:48 pm
It’s nearly impossible to find experienced people for this topic,
however, you seem like you know what you’re talking about!
Thanks
تعمیرات مایکروفر بوتان در تهران
3 Oct 25 at 3:48 pm
купить диплом продавца [url=rudik-diplom2.ru]купить диплом продавца[/url] .
Diplomi_bqpi
3 Oct 25 at 3:48 pm
Уральская школа живописи пополнилась ярким именем — Сергеем Арсеньевым. Его работы, основанные на классике, звучат современно и искренне, находя отклик у зрителей всей России.
https://arsenev-art.ru/
JasonDug
3 Oct 25 at 3:49 pm
купить диплом в балаково [url=https://rudik-diplom8.ru]купить диплом в балаково[/url] .
Diplomi_ugMt
3 Oct 25 at 3:50 pm
купить диплом медицинского училища [url=http://rudik-diplom5.ru]купить диплом медицинского училища[/url] .
Diplomi_uuma
3 Oct 25 at 3:50 pm
купить диплом с занесением в реестр в нижнем тагиле [url=https://www.frei-diplom1.ru]купить диплом с занесением в реестр в нижнем тагиле[/url] .
Diplomi_wpOi
3 Oct 25 at 3:51 pm
I savour, cause I found just what I was looking
for. You’ve ended my 4 day long hunt! God Bless you
man. Have a great day. Bye
Finxor GPT
3 Oct 25 at 3:51 pm
tadalafil [url=https://tadalmedspharmacy.com/#]tadalafil 20 mg price canada[/url] Buy Tadalafil 20mg
TimothyArrar
3 Oct 25 at 3:52 pm
Мы доверили Кухни в Дом проект нашей новой кухни, и это было правильное решение. Всё сделано аккуратно и качественно, кухня радует нас каждый день https://kuhni-v-dom.ru/
Eugeniostync
3 Oct 25 at 3:52 pm
If you’re on the hunt for a reliable and enjoyable crypto casino,
I highly recommend Bitstarz.
soyboy Frank
3 Oct 25 at 3:52 pm
Superb site you have here but I was wanting to know if
you knew of any discussion boards that cover the same topics talked about here?
I’d really love to be a part of group where I can get feedback from other knowledgeable individuals that share the same interest.
If you have any suggestions, please let me know.
Many thanks!
https://auto-online.uk.com/
3 Oct 25 at 3:53 pm
Этот слот от Booongo предлагает игрокам
окунуться в сказочную атмосферу, где главный символ – магическое
яблоко.
7к казино скачать
3 Oct 25 at 3:53 pm
купить диплом машиниста [url=http://rudik-diplom2.ru]купить диплом машиниста[/url] .
Diplomi_hdpi
3 Oct 25 at 3:54 pm
купить проведенный диплом [url=https://frei-diplom4.ru]купить проведенный диплом[/url] .
Diplomi_zbOl
3 Oct 25 at 3:54 pm
купить диплом о среднем специальном [url=http://www.rudik-diplom15.ru]купить диплом о среднем специальном[/url] .
Diplomi_pnPi
3 Oct 25 at 3:55 pm
купить диплом о техническом образовании с занесением в реестр [url=https://frei-diplom3.ru/]https://frei-diplom3.ru/[/url] .
Diplomi_ntKt
3 Oct 25 at 3:55 pm
купить диплом в саратове [url=https://rudik-diplom8.ru/]купить диплом в саратове[/url] .
Diplomi_mkMt
3 Oct 25 at 3:58 pm
купить диплом в виннице [url=http://educ-ua7.ru/]http://educ-ua7.ru/[/url] .
Diplomi_vlea
3 Oct 25 at 3:59 pm
https://freekashmir.mn.co/members/36190462
Walterbal
3 Oct 25 at 4:00 pm
я купил проведенный диплом [url=http://frei-diplom1.ru/]я купил проведенный диплом[/url] .
Diplomi_ppOi
3 Oct 25 at 4:00 pm
как купить диплом о высшем образовании с занесением в реестр [url=https://frei-diplom4.ru/]как купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_wpOl
3 Oct 25 at 4:01 pm
купить диплом в кирово-чепецке [url=http://rudik-diplom7.ru]http://rudik-diplom7.ru[/url] .
Diplomi_hvPl
3 Oct 25 at 4:02 pm
купить диплом с реестром цена [url=https://www.frei-diplom5.ru]купить диплом с реестром цена[/url] .
Diplomi_qePa
3 Oct 25 at 4:03 pm
3D-печать сегодня является передовой технологией. Мы готовы предложить выгодные услуги по печати изделий любой сложности. Наши заказчики получают функциональные модели, выполненные с использованием новейших технологий. Это дает возможность реализовать любую идею. Мы занимаемся производством с широким спектром материалов, что открывает путь для сложных проектов. Кроме того, мы предоставляем оперативные сроки изготовления. Каждый заказ сопровождается внимательной обработкой. Закажите 3D-печать у нас, и вы сможете воплотить любую идею: https://stayzada.com/bbs/board.php?bo_table=free&wr_id=329682. Наши специалисты выполняют печать аккуратно, точно и без брака, что делает наш сервис надежным.
MakarWig
3 Oct 25 at 4:03 pm
viralvideo
funnyvideo
funny
funnyvideo
funnyshorts
funnyvideos
nasa
নাসাভাইবিনোদোন
nasa
3 Oct 25 at 4:03 pm
yyap16 – A solid site with a fast, user-friendly design I liked.
Melvina Schunk
3 Oct 25 at 4:03 pm
купить диплом в анжеро-судженске [url=https://www.rudik-diplom4.ru]https://www.rudik-diplom4.ru[/url] .
Diplomi_iwOr
3 Oct 25 at 4:04 pm