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://arus-diplom34.ru/]диплом купить в реестре[/url] .
Diplomi_poer
14 Aug 25 at 1:49 am
https://hub.docker.com/u/ptrslearta
Kevincat
14 Aug 25 at 1:50 am
You need to take part in a contest for one of the best blogs on the internet.
I most certainly will highly recommend this blog!
https://rkindustrialsolutions.com/pvc-strip-curtains-for-industrial-use-in-bengaluru
14 Aug 25 at 1:51 am
купить диплом с реестром о высшем образовании [url=www.arus-diplom31.ru]купить диплом с реестром о высшем образовании[/url] .
Diplomi_owpl
14 Aug 25 at 1:57 am
Мы можем предложить документы ВУЗов, расположенных в любом регионе РФ. Купить диплом любого ВУЗа:
[url=http://demo.emunot.com/casestudies/kupit-diplom-s-zaneseniem-v-reestr-53/]где можно купить аттестат за 10 11 класс[/url]
Diplomi_irPn
14 Aug 25 at 1:59 am
Hurrah, that’s what I was looking for, what a data! present here
at this webpage, thanks admin of this web page.
Also visit my homepage; Concrete in cedar city Utah
Concrete in cedar city Utah
14 Aug 25 at 2:01 am
Внутривенная инфузия – это один из самых быстрых и безопасных способов очистки организма от алкоголя и его токсичных продуктов распада. Она позволяет:
Углубиться в тему – [url=https://kapelnica-ot-zapoya-krasnoyarsk6.ru/]сколько стоит капельница от запоя[/url]
Ernestcek
14 Aug 25 at 2:03 am
как купить аттестаты за 11 класс [url=http://arus-diplom22.ru]как купить аттестаты за 11 класс[/url] .
Diplomi_qjsl
14 Aug 25 at 2:03 am
https://beteiligung.stadtlindau.de/profile/%D0%9A%D1%83%D0%BF%D0%B8%D1%82%D1%8C%20%D0%AD%D0%BA%D1%81%D1%82%D0%B0%D0%B7%D0%B8%20%D0%9C%D0%94%D0%9C%D0%90%20%D0%9A%D0%BE%D0%BA%D0%B0%D0%B8%D0%BD%20%D0%A2%D0%B8%D0%BB%D0%B1%D1%83%D1%80%D0%B3/
VanceTox
14 Aug 25 at 2:03 am
Good information. Lucky me I came across your blog by
accident (stumbleupon). I’ve saved it for later!
web page
14 Aug 25 at 2:05 am
Excellent post. I was checking constantly this blog
and I’m impressed! Extremely useful info specially the last part 🙂
I care for such information a lot. I was looking for
this certain information for a long time. Thank you and
good luck.
link building services
14 Aug 25 at 2:09 am
Заказать диплом об образовании!
Мы изготавливаем дипломы психологов, юристов, экономистов и других профессий по приятным тарифам— [url=http://a-submarine.ru/]a-submarine.ru[/url]
Lazrdqn
14 Aug 25 at 2:11 am
Для пациентов, нуждающихся в полном погружении в лечебный процесс, в клинике предусмотрен круглосуточный стационар. Палаты — индивидуальные и на два человека, оборудованы современной мебелью, кондиционерами и телевизорами. Организовано сбалансированное питание с возможностью коррекции по медицинским показаниям. Пациенты ежедневно проходят процедуры, сессии и получают консультации. В свободное время организуются арт-занятия, йога, дыхательные практики. Такой режим позволяет не только восстановить физическое здоровье, но и снизить уровень тревожности, вернуть интерес к жизни и стимулировать мотивацию к выздоровлению.
Детальнее – [url=https://lechenie-narkomanii-novokuzneczk0.ru/]запой лечение наркомания в новокузнецке[/url]
Chrisfup
14 Aug 25 at 2:12 am
купить проведенный диплом весь [url=www.arus-diplom34.ru]купить проведенный диплом весь[/url] .
Priobresti diplom instityta!_ugkn
14 Aug 25 at 2:16 am
После стабилизации состояния пациенту предлагается пройти этап реабилитации. В клинике он может занять от 30 до 180 дней, в зависимости от тяжести зависимости, стажа употребления и социальной ситуации. Реабилитационный блок построен по принципам когнитивной реструктуризации: меняются привычные модели мышления, формируются новые способы реагирования на стресс, прорабатываются неразрешённые психологические конфликты. Используются методы психодрамы, арт-терапии, телесно-ориентированной терапии и даже нейропсихологической гимнастики.
Разобраться лучше – [url=https://lechenie-narkomanii-samara0.ru/]лечение наркомании клиника[/url]
Loganvip
14 Aug 25 at 2:19 am
купить аттестат об окончании 11 классов спб [url=https://arus-diplom25.ru/]купить аттестат об окончании 11 классов спб[/url] .
Diplomi_pzot
14 Aug 25 at 2:19 am
купить диплом с проводкой кого [url=http://www.arus-diplom33.ru]купить диплом с проводкой кого[/url] .
Diplomi_hjSa
14 Aug 25 at 2:20 am
Быстро заказать диплом ВУЗа!
Мы можем предложить дипломы любой профессии по приятным тарифам— [url=http://11ege.ru/]11ege.ru[/url]
Lazryjb
14 Aug 25 at 2:22 am
Экстренная помощь при алкоголизме от Narcology Clinic в Москве — выезд врачей в любую точку города, купирование острых состояний, поддержка пациента до стабильного состояния, профессионально и в конфиденциальности.
Узнать больше – [url=https://skoraya-narkologicheskaya-pomoshch-moskva.ru/]наркологическая помощь московская область[/url]
BobbySturb
14 Aug 25 at 2:23 am
Во многих случаях пациент или его родственники не решаются сразу вызвать врача. Для таких ситуаций предусмотрена услуга онлайн-консультации. Она проводится через защищённую видеосвязь, при желании — анонимно. На связи — врач-нарколог или психиатр, который отвечает на вопросы, оценивает ситуацию по визуальным и вербальным признакам, рекомендует план действий. Консультация может стать отправной точкой для дальнейшего вызова врача на дом или записи в клинику. Это особенно удобно для родственников, которые не знают, как подступиться к проблеме и убедить человека в необходимости помощи.
Выяснить больше – [url=https://narkologicheskaya-pomoshh-tver0.ru/]наркологическая клиника клиника помощь тверь[/url]
ArchiekEs
14 Aug 25 at 2:23 am
аттестат за 11 класс купить нижний новгород [url=https://arus-diplom22.ru/]аттестат за 11 класс купить нижний новгород[/url] .
Diplomi_blsl
14 Aug 25 at 2:26 am
Хотите [url=https://licenz.pro/med-litsenziya/]получить мед лицензию[/url] без стресса? Мы перевели процесс в современный формат: онлайн-документы, удалённые консультации, прозрачные сроки. Вы всегда знаете, на каком этапе находитесь. С нами вы получаете результат быстро, безопасно и по-новому — так, как это должно быть в XXI веке.
Licenz.pro
14 Aug 25 at 2:27 am
проект реконструкции квартиры [url=www.taksafonchik.borda.ru/?1-19-0-00000148-000-0-0-1754486136/]проект реконструкции квартиры[/url] .
proekt pereplanirovki v Moskve _eqpn
14 Aug 25 at 2:27 am
Generally I don’t learn article on blogs, but I wish to say that this write-up very forced me
to check out and do so! Your writing style has been surprised me.
Thanks, quite nice post.
adameve coupon
14 Aug 25 at 2:27 am
Yesterday, while I was at work, my cousin stole my iPad and tested to
see if it can survive a forty foot drop, just so she can be a youtube sensation. My iPad is now destroyed and
she has 83 views. I know this is entirely off topic but
I had to share it with someone!
Functional Nutrition and Health Coaching
14 Aug 25 at 2:28 am
купить диплом о высшем образовании с занесением в реестр в калуге [url=arus-diplom35.ru]купить диплом о высшем образовании с занесением в реестр в калуге[/url] .
Diplomi_cvOn
14 Aug 25 at 2:29 am
https://shootinfo.com/author/tabouidormer/?pt=ads
Kevincat
14 Aug 25 at 2:29 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 emails with the same comment.
Is there any way you can remove me from that service?
Bless you!
1win-apk-chily.xyz
14 Aug 25 at 2:31 am
google sites unblocked
Its like you read my mind! You appear to know a lot about
this, like you wrote the book in it or something.
I think that you can do with some pics to drive the
message home a bit, but other than that, this is magnificent blog.
An excellent read. I’ll definitely be back.
google sites unblocked
14 Aug 25 at 2:33 am
Highly energetic post, I loved that bit. Will there be a part 2?
footfinder
14 Aug 25 at 2:37 am
высшее образование купить диплом с занесением в реестр [url=http://arus-diplom34.ru/]высшее образование купить диплом с занесением в реестр[/url] .
Diplomi_xger
14 Aug 25 at 2:39 am
купить диплом о высшем образовании с занесением в реестр в москве [url=http://arus-diplom35.ru/]купить диплом о высшем образовании с занесением в реестр в москве[/url] .
Zakazat diplom lubogo instityta!_doot
14 Aug 25 at 2:39 am
купить диплом техникума в реестре цена [url=http://www.arus-diplom35.ru]купить диплом техникума в реестре цена[/url] .
Diplomi_fzOn
14 Aug 25 at 2:40 am
fnaf unblocked
Thank you a lot for sharing this with all people you actually recognise what you are talking about!
Bookmarked. Kindly additionally talk over with my web site =).
We can have a hyperlink change contract between us
fnaf unblocked
14 Aug 25 at 2:40 am
расчЮт оклада военнослужащего
Willardken
14 Aug 25 at 2:41 am
yohoho unblocked 76
I love your blog.. very nice colors & theme. Did you make this website yourself or did you hire someone to do it for you?
Plz answer back as I’m looking to design my own blog and would like to find out where u got this from.
kudos
yohoho unblocked 76
14 Aug 25 at 2:41 am
Современная жизнь, особенно в крупном городе, как Красноярск, часто становится причиной различных зависимостей. Работа в условиях постоянного стресса, высокий ритм жизни и эмоциональные перегрузки могут привести к проблемам, которые требуют неотложной медицинской помощи. Одним из наиболее удобных решений в такой ситуации является вызов нарколога на дом.
Подробнее – [url=https://narcolog-na-dom-v-krasnoyarske55.ru/]нарколог на дом красноярский край[/url]
DuaneGem
14 Aug 25 at 2:43 am
https://muckrack.com/person-27450849
VanceTox
14 Aug 25 at 2:44 am
Finding the best testosterone booster can help improve energy, muscle strength, and overall vitality naturally.
When paired with regular exercise and a healthy diet,
it can support long-term hormonal balance and performance.
best testosterone booster
14 Aug 25 at 2:48 am
paper.io
Thank you for another great article. The place else could anyone get that type
of info in such a perfect approach of writing?
I have a presentation next week, and I am at the look for such information.
paper.io
14 Aug 25 at 2:54 am
github.io unblocked
This is very interesting, You are a very skilled blogger.
I’ve joined your feed and look forward to seeking more of your magnificent post.
Also, I’ve shared your site in my social networks!
github.io unblocked
14 Aug 25 at 2:57 am
Состав инфузии подбирается квалифицированным врачом строго индивидуально для каждого пациента, с учетом его текущего состояния, степени тяжести алкогольной интоксикации, длительности запоя, возраста, наличия сопутствующих хронических заболеваний и индивидуальной переносимости лекарственных препаратов, что позволяет обеспечить максимально эффективное и безопасное лечение, учитывающее все особенности конкретного случая.
Подробнее – [url=https://kapelnica-ot-zapoya-ekb55.ru/]капельницы от запоя в красноярске[/url]
Andrewacino
14 Aug 25 at 3:03 am
экстренный вывод из запоя
vivod-iz-zapoya-omsk004.ru
лечение запоя омск
izzapoyaomskNeT
14 Aug 25 at 3:04 am
yohoho
Hello mates, its enormous post about educationand completely explained, keep
it up all the time.
yohoho
14 Aug 25 at 3:07 am
https://git.project-hobbit.eu/udacsaafo
Kevincat
14 Aug 25 at 3:08 am
экстренный вывод из запоя
vivod-iz-zapoya-orenburg004.ru
экстренный вывод из запоя
narkologiyaorenburgNeT
14 Aug 25 at 3:08 am
Hi, i believe that i noticed you visited my
weblog thus i got here to go back the want?.I am attempting to to find things to enhance my web site!I guess
its ok to make use of a few of your concepts!!
osaka789
14 Aug 25 at 3:09 am
купить диплом с занесением в реестр в уфе [url=http://arus-diplom35.ru]купить диплом с занесением в реестр в уфе[/url] .
Diplomi_qxOn
14 Aug 25 at 3:11 am
Basket Bros
Heya i’m for the first time here. I found this
board and I in finding It truly useful &
it helped me out much. I hope to offer one thing again and help others like you helped me.
Basket Bros
14 Aug 25 at 3:23 am
https://ucgp.jujuy.edu.ar/profile/fycueuhda/
VanceTox
14 Aug 25 at 3:24 am