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!
за1мы онлайн [url=www.zaimy-16.ru]www.zaimy-16.ru[/url] .
zaimi_jzMi
18 Sep 25 at 5:44 pm
: Clear Meds Hub –
DerekStops
18 Sep 25 at 5:45 pm
http://evertrustmeds.com/# Ever Trust Meds
RichardceaNy
18 Sep 25 at 5:45 pm
[url=https://fx-rebate.ru/]Сервис возврата спреда FX-Rebate[/url] открывает возможность ощутимо снизить издержки на Forex и повысить доходность сделок Он ориентирован на пользователей, которые ценят прозрачные условия и стабильные начисления Платформа работает по принципу максимальной открытости и полностью исключает непредвиденные удержания Проект взаимодействует только с проверенными компаниями, что позволяет трейдерам не беспокоиться о сохранности средств Опытные трейдеры активно используют платформу для увеличения прибыли и снижения затрат Каждый клиент получает доступ к функциональной панели управления, где все данные представлены максимально прозрачно Используя сервис, трейдеры значительно снижают торговые расходы и усиливают эффективность собственных стратегий Команда сервиса всегда готова ответить на запросы и предоставить необходимую помощь в короткие сроки Сегодня проект по праву занимает лидирующие позиции среди всех Rebate сервисов, предлагая трейдерам действительно максимальные выплаты Для тех, кто стремится к дополнительному доходу и ценит честные условия, сервис открывает новые возможности.
https://fx-rebate.ru/
Stevespani
18 Sep 25 at 5:45 pm
психика Психотерапевт онлайн – это ваш личный проводник в лабиринтах подсознания. Специалист, который поможет разобраться в глубинных причинах ваших проблем, преодолеть травмы и научиться эффективно справляться с жизненными трудностями. Онлайн-терапия – это возможность изменить свою жизнь к лучшему, независимо от вашего местонахождения и занятости.
AntoniohoF
18 Sep 25 at 5:46 pm
Unquestionably believe that which you stated. Your favorite reason seemed to be on the net the simplest thing to
be aware of. I say to you, I certainly get annoyed while people consider worries that they just
do not know about. You managed to hit the nail upon the top
as well as defined out the whole thing without having side-effects , people can take a signal.
Will probably be back to get more. Thanks
Meteor Profit
18 Sep 25 at 5:47 pm
щетки
щетки
18 Sep 25 at 5:52 pm
Howdy! I understand this is kind of off-topic however I needed to ask.
Does operating a well-established website
such as yours require a massive amount work? I am brand new to
writing a blog however I do write in my diary on a daily basis.
I’d like to start a blog so I can easily share my own experience and feelings online.
Please let me know if you have any suggestions or tips for
brand new aspiring blog owners. Appreciate it!
Redgate Bitcore
18 Sep 25 at 5:52 pm
wonderful points altogether, you just received a emblem new reader.
What could you suggest about your publish that you simply made a few
days in the past? Any sure?
دانشگاه تهران جنوب کجاست
18 Sep 25 at 5:52 pm
Thanks for the auspicious writeup. It Probate Law in Utah reality was a leisure account it.
Glance complicated to more added agreeable from you!
By the way, how can we communicate?
Probate Law in Utah
18 Sep 25 at 5:52 pm
After I originally left a comment I appear to have clicked on the -Notify me when new comments are added- checkbox and
from now on whenever a comment is added I receive
4 emails with the exact same comment. Perhaps there is a way you are
able to remove me from that service? Many thanks!
Good
18 Sep 25 at 5:54 pm
Goodness, еᴠen іf institution remains fancy, mathematics is tһe decisive topic fоr developing poise regаrding calculations.
Hwa Chong Institution Junior College іs renowned for іts integrated program tһat perfectly combines academic rigor ᴡith character development, producing global scholars аnd leaders.
Ϝirst-rate facilities аnd professional professors support quality іn research study, entrepreneurship, аnd bilingualism.
Trainees tаke advantage ⲟf comprehensive international exchanges ɑnd competitions, expanding point of views and developing skills.
The organization’ѕ focus оn innovation and service cultivates resilience аnd ethical worths.
Alumni networks оpen doors to leading universities and
prominent proessions worldwide.
Temasek Junior College influences а generation of trailblazers Ьy fusing timе-honored customs witfh cutting-edge innovation,
offering strenuous scholastic programs instilled ѡith ethical
worths that assist students t᧐wards meaningful and impactful futures.
Advanced proving ground, language labs, аnd optional courses in internatijonal languages ɑnd
carrying out arts offer platforms fοr deep intellectual engagement,
іmportant analysis, ɑnd innovative exploration ᥙnder tһe mentorship οf recognized educators.
Ꭲhe vibrant сߋ-curricular landscape, featuring competitive sports,
artistic societies, ɑnd entrepreneurship ϲlubs, cultivates teamwork,
management, аnd а spirit of development
thаt matches class knowing. International
cooperations, ѕuch as joint reseаrch study jobs with
abroad organizations and cultural exchange programs, boost trainees’ global proficiency,cultural sensitivity,
аnd networking capabilities. Alumni fгom Temasek
Junior College grow іn elite greater education institutions ɑnd
diverse expert fields, personifying tһе school’s devotion tⲟ excellence, service-oriented
leadership, and the pursuit οf individual and social betterment.
Οh no, primary mathematics educates everyday implementations ⅼike money management, tһerefore ensure your
child gets tһіѕ right beginning young age.
Eh eh, composed pom рi pi, math is pаrt fгom the top topics at Junior
College, establishing groundwork fօr A-Level advanced math.
Alas, lacking robust maths dսring Junior College, гegardless prestigious establishment kids mіght falter ᴡith next-level calculations, ѕo build thіs now leh.
Heey hey, Singapore folks, mathematics гemains рerhaps tһе most important primary subject, promoting imagination fⲟr issue-resolving
fоr innovative careers.
Ɗo not tɑke lightly lah, combine a excellent Junior College ѡith maths proficiency іn order tο ensure һigh Α Levels results plus smooth cһanges.
Mums and Dads, worry ɑbout tһе difference
hor, math base remаins critical at Junior College tо understanding data, vital for modern tech-driven economy.
Hey hey, composed pom рi ⲣi, mathematics remains paгt of the leading topics at Junior College, building
base t᧐ A-Level calculus.
Αpart from institution amenities, concentrate ԝith math to prevent common errors ⅼike inattentive mistakes
ɗuring tests.
A-level success stories іn Singapore often start with
kiasu study habits fгom JC days.
Oh dear, lacking strong math at Junior College, rеgardless leading school kids mіght falter ѡith secondary calculations, tһerefore build tһat promptly leh.
my webpage … physics and maths tutor solutionbank
physics and maths tutor solutionbank
18 Sep 25 at 5:57 pm
Такая схема позволяет последовательно и безопасно восстановить силы организма и стабилизировать психическое состояние пациента.
Углубиться в тему – [url=https://vyvod-iz-zapoya-tver0.ru/]нарколог вывод из запоя тверь[/url]
Erwinerype
18 Sep 25 at 5:58 pm
https://aisikopt.ru
EugeneErast
18 Sep 25 at 6:01 pm
I’m truly enjoying the design and layout of your site.
It’s a very easy on the eyes which makes it much more pleasant for me
to come here and visit more often. Did you hire out a
designer to create your theme? Great work!
wps 激活
18 Sep 25 at 6:01 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best
bs2best.at blacksprut marketplace Official
CharlesNarry
18 Sep 25 at 6:03 pm
При ряде клинических признаков требуется ускоренное подключение специалистов и проведение детоксикации под контролем.
Подробнее – [url=https://vyvod-iz-zapoya-lugansk0.ru/]vyvod-iz-zapoya-lugansk0.ru/[/url]
ThomasCrees
18 Sep 25 at 6:04 pm