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=http://arus-diplom33.ru]купить легальный диплом[/url] .
Diplomi_ptSa
14 Aug 25 at 12:58 am
купить государственный диплом с занесением в реестр [url=https://arus-diplom31.ru/]купить государственный диплом с занесением в реестр[/url] .
Diplomi_gepl
14 Aug 25 at 12:59 am
Мы предлагаем документы учебных заведений, расположенных в любом регионе РФ. Заказать диплом ВУЗа:
[url=http://quikconnect.us/employer/diplomiki/]аттестат об окончании 11 классов купить[/url]
Diplomi_zyPn
14 Aug 25 at 1:00 am
можно ли купить легальный диплом [url=https://arus-diplom34.ru/]https://arus-diplom34.ru/[/url] .
Diplomi_hzer
14 Aug 25 at 1:00 am
Custom Royal Portrait turnyouroyal.com an exclusive portrait from a photo in a royal style. A gift that will impress! Realistic drawing, handwork, a choice of historical costumes.
turnyouroyal-880
14 Aug 25 at 1:01 am
купить диплом без внесения в реестр [url=http://arus-diplom35.ru/]купить диплом без внесения в реестр[/url] .
Diplomi_auOn
14 Aug 25 at 1:02 am
купить аттестат в шелехов 11 классов недорого [url=https://arus-diplom23.ru]купить аттестат в шелехов 11 классов недорого[/url] .
Diplomi_uaSr
14 Aug 25 at 1:04 am
где купить аттестат о среднем образовании [url=https://educ-ua5.ru/]где купить аттестат о среднем образовании[/url] .
Diplomi_nfEa
14 Aug 25 at 1:04 am
аттестат за 11 купить спб [url=www.arus-diplom22.ru/]аттестат за 11 купить спб[/url] .
Diplomi_pmsl
14 Aug 25 at 1:06 am
We’re a group of volunteers and opening a new scheme in our community.
Your website provided us with valuable information to work on. You have done
a formidable job and our entire community will be thankful to you.
Dreamproxies.com
14 Aug 25 at 1:06 am
Открыть онлайн брокерский счёт – ваш первый шаг в мир инвестиций. Доступ к биржам, широкий выбор инструментов, аналитика и поддержка. Простое открытие и надёжная защита средств.
besarte-835
14 Aug 25 at 1:08 am
Hello there, I discovered your site via Google whilst looking for a related matter,
your website got here up, it seems to be good. I have bookmarked
it in my google bookmarks.
Hello there, simply turned into aware of your blog through Google, and
located that it is really informative. I’m going to watch out for brussels.
I will appreciate when you continue this in future. Lots
of other people might be benefited from your writing. Cheers!
Vip Bet Casino
14 Aug 25 at 1:09 am
Заказать диплом возможно используя сайт компании. [url=http://veraciousrp.listbb.ru/posting.php?mode=post&f=82&sid=eb617ca0d9587a60b313e25d4b71abe3/]veraciousrp.listbb.ru/posting.php?mode=post&f=82&sid=eb617ca0d9587a60b313e25d4b71abe3[/url]
Sazrsxx
14 Aug 25 at 1:10 am
Custom Royal Portrait http://www.turnyouroyal.com an exclusive portrait from a photo in a royal style. A gift that will impress! Realistic drawing, handwork, a choice of historical costumes.
turnyouroyal-239
14 Aug 25 at 1:10 am
سه فازدات کام : مرجع تخصصی تجهیزات اتوماسیون صنعتی در لالهزار تهران
فروشگاه اینترنتی سه فاز دات کام، واقع در قلب بازار لالهزار تهران، با
سالها تجربه درخشان، مرجعی مطمئن و تخصصی برای تأمین انواع
تجهیزات اتوماسیون صنعتی از برندهای
معتبر جهانی است.
با سه فاز دات کام ، آینده صنعت خود را
تضمین کنید!محصولاتی باکیفیت جهانی، در دستان شما:ما در سه فاز،
افتخار داریم که نماینده انحصاری برندهای
مطرحی همچون AUTONICS، KOINO، CONOTEC، SHIHLIN,
SAMWON، WACHENDORFF، FENAC، SENSYS، KACON و ELIMKO هستیم.
این به این معنی است که شما به مجموعهای
کامل از تجهیزات اتوماسیون صنعتی با
بالاترین کیفیت و اصالت، دسترسی
خواهید داشت.گارانتی یک ساله، ضامن آرامش خاطر شما:تمامی
محصولات ارائه شده در فروشگاه اینترنتی سه
فاز دات کام ، با گارانتی یک ساله ارائه
میشوند. این گارانتی، نشان از اطمینان ما به
کیفیت محصولات و تعهد ما به رضایت شما مشتریان گرامی دارد.خرید آسان و سریع، تحویل فوری:با مراجعه به
وبسایت سه فاز دات کام ، به راحتی و در کمترین زمان
ممکن، محصول مورد نظر خود را انتخاب و خریداری کنید.
ارسال فوری سفارشات به سراسر کشور، از دیگر مزایای خرید از سه فاز
دات کام است.تجربه خرید حضوری در قلب بازار لالهزار:علاوه بر امکان خرید آنلاین، شما میتوانید برای مشاهده و خرید حضوری محصولات، به فروشگاه
ما در بازار لالهزار تهران مراجعه کنید.پشتیبانی و خدمات رایگان، در کنار
شما:تیم متخصص و مجرب سه فاز دات
کام ، در تمامی مراحل خرید و پس از آن،
به صورت رایگان پاسخگوی
سوالات شما و ارائه دهنده خدمات پشتیبانی فنی
هستند.همین حالا به فروشگاه اینترنتی سه فاز دات کام مراجعه کنید و
از مزایای خریدی مطمئن و آسان بهرهمند شوید.
سه فاز دات کام: انتخابی هوشمندانه برای آینده صنعت شما!
آتونیکس
14 Aug 25 at 1:11 am
https://www.brownbook.net/business/54160730/сиде-купить-амфетамин-кокаин-экстази/
Kevincat
14 Aug 25 at 1:12 am
купить аттестат за 11 класс в иркутске [url=www.arus-diplom21.ru/]www.arus-diplom21.ru/[/url] .
Zakazat diplom lubogo yniversiteta!_crpn
14 Aug 25 at 1:13 am
п»їlegitimate online pharmacies india: world pharmacy india – Indian Meds One
JamesHeelo
14 Aug 25 at 1:14 am
indian pharmacies safe [url=https://indianmedsone.com/#]mail order pharmacy india[/url] Indian Meds One
Houstonfloma
14 Aug 25 at 1:15 am
Открыть онлайн брокерский счёт – ваш первый шаг в мир инвестиций. Доступ к биржам, широкий выбор инструментов, аналитика и поддержка. Простое открытие и надёжная защита средств.
besarte-640
14 Aug 25 at 1:16 am
купить аттестат 11 класса 2012 [url=https://arus-diplom23.ru/]купить аттестат 11 класса 2012[/url] .
Diplomi_kuol
14 Aug 25 at 1:19 am
купить диплом с занесением в реестр [url=http://arus-diplom34.ru/]купить диплом с занесением в реестр[/url] .
Zakazat diplom lubogo yniversiteta!_dlkn
14 Aug 25 at 1:20 am
https://pxlmo.com/turanvale.1992
VanceTox
14 Aug 25 at 1:22 am
купить аттестат 11 класса челябинск [url=www.arus-diplom25.ru]купить аттестат 11 класса челябинск[/url] .
Diplomi_lhot
14 Aug 25 at 1:23 am
купить диплом в архангельске с занесением в реестр [url=arus-diplom33.ru]купить диплом в архангельске с занесением в реестр[/url] .
Diplomi_tsSa
14 Aug 25 at 1:23 am
Мы можем предложить документы любых учебных заведений, расположенных в любом регионе Российской Федерации. Приобрести диплом о высшем образовании:
[url=http://news1.listbb.ru/viewtopic.php?f=3&t=2623/]купить аттестат 11 класс в новосибирске[/url]
Diplomi_faPn
14 Aug 25 at 1:23 am
купить диплом с регистрацией [url=arus-diplom34.ru]купить диплом с регистрацией[/url] .
Diplomi_bher
14 Aug 25 at 1:24 am
купить аттестаты 11 класс [url=www.arus-diplom24.ru]купить аттестаты 11 класс[/url] .
Diplomi_lpKn
14 Aug 25 at 1:25 am
купить диплом магистра дешево [url=www.educ-ua5.ru/]купить диплом магистра дешево[/url] .
Diplomi_hvEa
14 Aug 25 at 1:25 am
Greetings from Ohio! I’m bored at work so I decided to check out your blog on my
iphone during lunch break. I enjoy the knowledge you provide here and can’t wait to take a look when I get home.
I’m surprised at how quick your blog loaded on my phone ..
I’m not even using WIFI, just 3G .. Anyhow, great site!
نتایج آزمون نظام مهندسی ۱۴۰۴
14 Aug 25 at 1:25 am
диплом о высшем образовании с занесением в реестр купить [url=www.arus-diplom31.ru]диплом о высшем образовании с занесением в реестр купить[/url] .
Diplomi_gupl
14 Aug 25 at 1:27 am
купить диплом с занесением в реестр в нижнем тагиле [url=www.arus-diplom34.ru]купить диплом с занесением в реестр в нижнем тагиле[/url] .
Priobresti diplom ob obrazovanii!_idkn
14 Aug 25 at 1:27 am
Its such as you read my mind! You appear to know a
lot approximately this, like you wrote the e-book in it or something.
I believe that you could do with a few p.c.
to drive the message house a bit, but other than that, that is great blog.
A great read. I’ll definitely be back.
post2415
14 Aug 25 at 1:27 am
После первичной диагностики начинается активная фаза лечения. Современные медикаменты вводятся капельничным методом для быстрого выведения токсинов из организма и восстановления нормальных обменных процессов. Этот этап критически важен для нормализации работы печени, почек и сердечно-сосудистой системы.
Разобраться лучше – https://reabcentr-narko.ru/vyvod-iz-zapoya-tver-staczionar/
Stephenzes
14 Aug 25 at 1:27 am
аттестат за 11 класс купить питер [url=https://arus-diplom22.ru]аттестат за 11 класс купить питер[/url] .
Diplomi_yhsl
14 Aug 25 at 1:28 am
Мы предлагаем документы любых учебных заведений, которые находятся в любом регионе России. Купить диплом ВУЗа:
[url=http://maminmir.getbb.ru/viewtopic.php?f=1&t=3437/]купить аттестат в тюмени за 11 класс[/url]
Diplomi_kgPn
14 Aug 25 at 1:29 am
I have learn several just right stuff here. Definitely worth bookmarking for revisiting.
I wonder how a lot attempt you put to create one of
these fantastic informative web site.
local orthodontics near me
14 Aug 25 at 1:30 am
Заказать диплом можно используя сайт компании. [url=http://betterlifenija.org.ng/profile/jakepuckett70/]betterlifenija.org.ng/profile/jakepuckett70[/url]
Sazrefo
14 Aug 25 at 1:31 am
Выгодно приобрести диплом ВУЗа!
Мы предлагаем дипломы любой профессии по приятным ценам— [url=http://ohmylove.ru/]ohmylove.ru[/url]
Lazrpoc
14 Aug 25 at 1:32 am
купить аттестат 11 класса 2003 года [url=http://arus-diplom21.ru]купить аттестат 11 класса 2003 года[/url] .
Zakazat diplom ob obrazovanii!_urpn
14 Aug 25 at 1:33 am
купить аттестат за 11 класс в иваново [url=https://arus-diplom22.ru]купить аттестат за 11 класс в иваново[/url] .
Diplomi_aesl
14 Aug 25 at 1:35 am
купить диплом с занесением в реестр в спб [url=https://www.arus-diplom35.ru]купить диплом с занесением в реестр в спб[/url] .
Diplomi_dkOn
14 Aug 25 at 1:38 am
купить в москве аттестат за 11 класс [url=https://arus-diplom24.ru]купить в москве аттестат за 11 класс[/url] .
Diplomi_zwsa
14 Aug 25 at 1:38 am
Если требуется экстренная помощь при алкогольном кризисе — Narcology Clinic Москва предоставляет срочную помощь на дому: выезд нарколога, купирование симптомов, мониторинг состояния, без очередей и задержек.
Исследовать вопрос подробнее – [url=https://skoraya-narkologicheskaya-pomoshch15.ru/]вызвать наркологическую помощь москве[/url]
Davidpoido
14 Aug 25 at 1:38 am
самополивающийся горшок [url=http://www.kashpo-s-avtopolivom-kazan.ru]самополивающийся горшок[/url] .
gorshok s avtopolivom_tdei
14 Aug 25 at 1:38 am
Indian Meds One: top online pharmacy india – Indian Meds One
JamesHeelo
14 Aug 25 at 1:40 am
что будет если купить диплом о высшем образовании с занесением в реестр [url=arus-diplom33.ru]что будет если купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_iaSa
14 Aug 25 at 1:43 am
Зависимость от психоактивных веществ — серьёзное заболевание, затрагивающее как физическое, так и психологическое состояние человека. При отсутствии своевременной наркологической помощи в клинике возможно ухудшение здоровья, развитие тяжелых осложнений и социальная деградация пациента.
Исследовать вопрос подробнее – [url=https://narkologicheskaya-pomoshh-novokuzneczk0.ru/]наркологическая психиатрическая помощь в новокузнецке[/url]
JosephSeilk
14 Aug 25 at 1:43 am
купить проведенный диплом высокие [url=arus-diplom35.ru]купить проведенный диплом высокие[/url] .
Zakazat diplom lubogo VYZa!_jqot
14 Aug 25 at 1:44 am
купить аттестат за 11 класс уфа [url=www.arus-diplom25.ru/]купить аттестат за 11 класс уфа[/url] .
Diplomi_zuot
14 Aug 25 at 1:49 am