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://rudik-diplom14.ru/]купить диплом в кинешме[/url] .
Diplomi_vyea
3 Oct 25 at 2:58 pm
купить диплом в норильске [url=https://rudik-diplom8.ru/]купить диплом в норильске[/url] .
Diplomi_gnMt
3 Oct 25 at 2:59 pm
Длительное употребление алкоголя наносит серьезный удар по организму, приводя к нарушению функций печени, сердечно-сосудистой и нервной системы. Чем дольше продолжается запой, тем тяжелее последствия для здоровья, и тем сложнее пациенту самостоятельно вернуться к трезвости. Капельница от запоя на дому в Сочи — это быстрая, безопасная и эффективная процедура, которая позволяет снять алкогольную интоксикацию, стабилизировать состояние и вернуть контроль над организмом. Врачи клиники «ТрезвоПрофи» работают круглосуточно, обеспечивая профессиональную поддержку и абсолютную конфиденциальность.
Подробнее можно узнать тут – http://kapelnica-ot-zapoya-sochi00.ru/
VictorApevy
3 Oct 25 at 2:59 pm
yyap16 – Looks professional yet simple, which is always a good balance.
Era Cathers
3 Oct 25 at 3:00 pm
fghakgaklif – The layout is neat, with everything clearly placed and easy to spot.
John Schoolfield
3 Oct 25 at 3:01 pm
купить диплом с занесением в реестр краснодар [url=frei-diplom4.ru]frei-diplom4.ru[/url] .
Diplomi_ijOl
3 Oct 25 at 3:02 pm
sildenafil where to buy: sildenafil – Sildenafil 100mg price
BruceMaivy
3 Oct 25 at 3:03 pm
Ремонт и строительство https://nastil69.ru от А до Я: планирование, закупка, логистика, контроль и приёмка. Калькуляторы смет, типовые договора, инструкции по инженерным сетям. Каталог подрядчиков, отзывы, фото-примеры и советы по снижению бюджета проекта.
nastil69-140
3 Oct 25 at 3:03 pm
Highly descriptive blog, I liked that bit. Will there be a part 2?
slottower8
3 Oct 25 at 3:04 pm
https://t.me/s/z_official_1xbet
Dennissturo
3 Oct 25 at 3:05 pm
купить диплом в нижнекамске [url=www.rudik-diplom8.ru/]www.rudik-diplom8.ru/[/url] .
Diplomi_fbMt
3 Oct 25 at 3:05 pm
купить диплом с реестром отзывы [url=www.frei-diplom5.ru/]купить диплом с реестром отзывы[/url] .
Diplomi_jaPa
3 Oct 25 at 3:06 pm
united statesn gambling news, $150 free no deposit hard rock social casino promo Code australia and arcade slot machines for sale
uk, or united kingdom online pokies paypal
hard rock social casino promo Code
3 Oct 25 at 3:06 pm
cangjigedh – This site feels exciting, very different from anything I’ve seen.
Tyson Steff
3 Oct 25 at 3:07 pm
Для эффективного лечения алкогольной интоксикации и восстановления организма врачи клиники «АлкоДоктор» используют комплекс препаратов, которые индивидуально подбираются с учетом состояния пациента.
Исследовать вопрос подробнее – [url=https://kapelnica-ot-zapoya-sochi0.ru/]вызвать капельницу от запоя на дому[/url]
Wilfredoxype
3 Oct 25 at 3:07 pm
Ремонт и строительство https://nastil69.ru от А до Я: планирование, закупка, логистика, контроль и приёмка. Калькуляторы смет, типовые договора, инструкции по инженерным сетям. Каталог подрядчиков, отзывы, фото-примеры и советы по снижению бюджета проекта.
nastil69-540
3 Oct 25 at 3:07 pm
alusstore – I like the modern style, everything feels polished and fresh.
Synthia Halbershtam
3 Oct 25 at 3:07 pm
купить легальный диплом техникума [url=http://frei-diplom1.ru]купить легальный диплом техникума[/url] .
Diplomi_dcOi
3 Oct 25 at 3:08 pm
Fine way of describing, and good piece of writing to get data
concerning my presentation subject, which
i am going to present in college.
79king
3 Oct 25 at 3:08 pm
Курс по обретению внутренней гармонии — это про покой. Чувствую себя уравновешенной.
курс по телесной терапии для начинающих
Arthuraduch
3 Oct 25 at 3:09 pm
Первое, на что нужно обратить внимание — авторство
и происхождение информации.
Перейти по ссылке
3 Oct 25 at 3:10 pm
OMT’s exclusive рroblem-solving strategies mɑke tackling hard questions ѕeem ⅼike
a game, helping pupils ⅽreate an authentic love for mathematics ɑnd inspiration to
radiate іn exams.
Discover tһe benefit of 24/7 online math tuition at OMT,
ᴡһere engaging resources make discovering enjoyable ɑnd
reliable for alⅼ levels.
With math integrated flawlessly іnto Singapore’s class
settings to benefit bօth instructors and students, committed math tuition amplifies tһese gains by using tailored support fоr continual accomplishment.
primary school math tuition boosts ѕensible thinking, essential f᧐r interpreting PSLE concerns involving sequences аnd logical deductions.
Tuition promotes advanced analytical abilities, essential fօr fixing
tһe complex, multi-step inquiries tһɑt define O Level mathematics obstacles.
Math tuition ɑt tһe junior college degree emphasizes theoretical clearness
օver rote memorization, vital fⲟr dealing ԝith application-based A Level inquiries.
OMT’s personalized syllabus distinctively straightens wwith MOE structure Ьy ɡiving bridging components for smooth shifts іn Ƅetween primary, secondary,
and JC mathematics.
Integration ᴡith school homework leh, mаking tuition ɑ smooth expansion fߋr grade enhancement.
Tuition programs in Singapore supply simulated exams ᥙnder timed prߋblems, mimicing actual
test circumstances fоr improved performance.
mү paցe maths tuition assignments – deifiction.com,
deifiction.com
3 Oct 25 at 3:10 pm
купить диплом колледжа с занесением в реестр [url=frei-diplom4.ru]купить диплом колледжа с занесением в реестр[/url] .
Diplomi_pjOl
3 Oct 25 at 3:11 pm
купить диплом средне техническое [url=www.rudik-diplom14.ru]купить диплом средне техническое[/url] .
Diplomi_clea
3 Oct 25 at 3:12 pm
купить диплом медсестры [url=frei-diplom15.ru]купить диплом медсестры[/url] .
Diplomi_aeoi
3 Oct 25 at 3:12 pm
купить диплом в заречном [url=http://rudik-diplom4.ru]купить диплом в заречном[/url] .
Diplomi_zjOr
3 Oct 25 at 3:12 pm
купить диплом в королёве [url=https://rudik-diplom1.ru]купить диплом в королёве[/url] .
Diplomi_ader
3 Oct 25 at 3:13 pm
You’re so cool! I don’t think I’ve read anything like that before.
So great to discover somebody with some unique thoughts on this subject.
Seriously.. thank you for starting this up. This web site is one thing that’s needed on the web, someone with some originality!
dewascatter login
3 Oct 25 at 3:13 pm
local-website – Browsing here feels effortless, I didn’t face any issues.
Dan Hedon
3 Oct 25 at 3:14 pm
eljiretdulces – I like the colorful vibe, it gives a cheerful touch.
Leonora Dallmeyer
3 Oct 25 at 3:14 pm
купить диплом в новосибирске [url=www.rudik-diplom5.ru/]купить диплом в новосибирске[/url] .
Diplomi_zvma
3 Oct 25 at 3:15 pm
купить диплом в воткинске [url=www.rudik-diplom15.ru/]купить диплом в воткинске[/url] .
Diplomi_ewPi
3 Oct 25 at 3:15 pm
В Королёве мы запускаем помощь без «многоходовок». С первого контакта дежурный врач аккуратно уточняет жалобы, длительность эпизода, принимаемые лекарства и сопутствующие диагнозы, после чего предлагает безопасную точку входа: выезд на дом, дневной формат или круглосуточный стационар. Каждое действие объясняется простым языком: зачем оно нужно, какого эффекта ждать в ближайшие часы и что будет считаться нормальной динамикой. Конфиденциальность заложена в процесс по умолчанию: минимально необходимый объём персональных данных, нейтральная коммуникация, ограниченный доступ к медкарте и отсутствие постановки на учёт. Такой порядок снимает лишнее напряжение у семьи и экономит самое ценное — время.
Исследовать вопрос подробнее – http://narkologicheskaya-klinika-korolyov0.ru/narkologicheskaya-klinika-na-dom-v-korolyove/
JoshuaSah
3 Oct 25 at 3:15 pm
Обратились за SEO продвижением, так как сайт практически не приносил заявок. Специалисты сделали полный аудит, исправили ошибки, доработали структуру и добавили оптимизированный контент. Уже через пару месяцев пошёл стабильный рост трафика и звонков. Теперь мы уверенно обходим конкурентов и видим реальную отдачу от вложений – https://mihaylov.digital/
Steventob
3 Oct 25 at 3:16 pm
Нужен аккумулятор? аккумуляторы автомобильные купить в спб с доставкой в наличии: топ-бренды, все размеры, правый/левый токовывод. Бесплатная проверка генератора при установке, trade-in старого АКБ. Гарантия до 3 лет, честные цены, быстрый самовывоз и курьер. Поможем выбрать за 3 минуты.
dostavka-akb-h
3 Oct 25 at 3:17 pm
диплом с внесением в реестр купить [url=http://frei-diplom4.ru]диплом с внесением в реестр купить[/url] .
Diplomi_dbOl
3 Oct 25 at 3:17 pm
Хочешь сдать акб? сдать аккумулятор спб честная цена за кг, моментальная выплата, официальная утилизация. Самовывоз от 1 шт. или приём на пункте, акт/квитанция. Безопасно и законно. Узнайте текущий тариф и ближайший адрес.
priem-akb-514
3 Oct 25 at 3:17 pm
I am not sure where you’re getting your info, but good topic.
I needs to spend some time learning much more or understanding more.
Thanks for magnificent information I was looking for this information for my mission.
تعمیرات لوازم خانگی در تهران
3 Oct 25 at 3:18 pm
https://al-material.ru
KevinEdica
3 Oct 25 at 3:18 pm
Нужен аккумулятор? купить аккумулятор для автомобиля с доставкой в наличии: топ-бренды, все размеры, правый/левый токовывод. Бесплатная проверка генератора при установке, trade-in старого АКБ. Гарантия до 3 лет, честные цены, быстрый самовывоз и курьер. Поможем выбрать за 3 минуты.
dostavka-akb-q
3 Oct 25 at 3:20 pm
Хочешь сдать акб? сдать б у аккумулятор честная цена за кг, моментальная выплата, официальная утилизация. Самовывоз от 1 шт. или приём на пункте, акт/квитанция. Безопасно и законно. Узнайте текущий тариф и ближайший адрес.
priem-akb-737
3 Oct 25 at 3:20 pm
купить диплом во владимире [url=http://rudik-diplom5.ru]купить диплом во владимире[/url] .
Diplomi_mfma
3 Oct 25 at 3:22 pm
купить диплом с занесением в реестр новосибирск [url=http://frei-diplom1.ru]купить диплом с занесением в реестр новосибирск[/url] .
Diplomi_wrOi
3 Oct 25 at 3:23 pm
купить диплом занесенный реестр [url=frei-diplom5.ru]купить диплом занесенный реестр[/url] .
Diplomi_kcPa
3 Oct 25 at 3:25 pm
купить бланк диплома [url=http://rudik-diplom14.ru]купить бланк диплома[/url] .
Diplomi_kxea
3 Oct 25 at 3:26 pm
newbalance550 – A smooth browsing experience, everything works well from start to finish.
Heidi Pinelli
3 Oct 25 at 3:26 pm
купить диплом в энгельсе [url=http://rudik-diplom8.ru/]http://rudik-diplom8.ru/[/url] .
Diplomi_nxMt
3 Oct 25 at 3:29 pm
купить диплом в сургуте [url=https://www.rudik-diplom5.ru]купить диплом в сургуте[/url] .
Diplomi_ktma
3 Oct 25 at 3:29 pm
fghakgaklif – The structure is clear, makes moving between pages quick and easy.
Gretchen Botha
3 Oct 25 at 3:29 pm
диплом техникума старого образца купить [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_ydea
3 Oct 25 at 3:29 pm