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!
Ищу уничтожение тараканов в общежитии с выездом в область.
уничтожение тараканов в кафе
KennethceM
25 Oct 25 at 9:07 pm
где купить диплом техникума будьте [url=frei-diplom8.ru]где купить диплом техникума будьте[/url] .
Diplomi_kmsr
25 Oct 25 at 9:07 pm
Hello all
Follow Every League Without the Noise
[url=https://theuijunkie.com/]Mostbet[/url],[url=https://fuelchoicessummit.com/]Mostbet[/url],[url=https://prompterguide.com/]Mostbet[/url],[url=https://globalsportmatters.com/]Mostbet[/url]
Jesren56
25 Oct 25 at 9:10 pm
I’m now not sure where you are getting your info,
but good topic. I needs to spend a while studying much more or
understanding more. Thank you for magnificent information I was in search of this info for my mission.
Finozanetix
25 Oct 25 at 9:10 pm
bestdealsforlife – Quick checkout process, products arrived fast and well packaged today.
Felicia Zabarkes
25 Oct 25 at 9:10 pm
диплом купить с занесением в реестр рязань [url=www.frei-diplom5.ru/]www.frei-diplom5.ru/[/url] .
Diplomi_snPa
25 Oct 25 at 9:11 pm
кракен зеркало
kraken client
JamesDaync
25 Oct 25 at 9:13 pm
The Playamo platform showcases an remarkable casino experience offering upwards of 3,000+ superior slot games, casino tables, and live casino options from top-tier software creators. From the most recent slot games to planned blackjack play and authentic live gaming, the site serves each preference. The site offers an sophisticated, user-friendly layout that enables simple navigation on desktop and mobile, giving you entertainment experience whenever and wherever.
Playamo casino
AlfredLog
25 Oct 25 at 9:13 pm
купить медицинский диплом с занесением в реестр [url=http://frei-diplom2.ru]купить медицинский диплом с занесением в реестр[/url] .
Diplomi_urEa
25 Oct 25 at 9:14 pm
Инхимтек — первый в России производитель полиэтиленовых восков: неокисленные (в т.ч. суспензионные и рафинированные), окисленные ПНД/ПВД и синтетические церезины. Собственная лаборатория, внедренные технологии микронизации и эмульсий, масштабирование мощностей (новые колонны окисления и линии деструкции) — это стабильные спецификации и поставки по всей стране, включая резервирование на складе и выпуск по ТЗ заказчика. Для выбора марки и получения проб перейти на https://xn--e1afajie1bv.xn--p1ai/ — специалисты помогут подобрать совместимость под конкретный процесс.
vapihJaigo
25 Oct 25 at 9:16 pm
mostbet kg [url=https://mostbet12031.ru/]mostbet kg[/url]
mostbet_kg_ekMa
25 Oct 25 at 9:16 pm
1xbet tr [url=http://1xbet-14.com]1xbet tr[/url] .
1xbet_oxet
25 Oct 25 at 9:17 pm
В эру цифровых инноваций доска бесплатных объявлений Ynla.ru выделяется как надежная платформа для эффективного обмена товарами и услугами, где пользователи из различных регионов России и соседних стран размещают тысячи предложений ежедневно. Основанная на принципах доступности, она позволяет бесплатно публиковать объявления в категориях от автотранспорта и недвижимости до работы, электроники и услуг, с ограничением в одно бесплатное размещение для предотвращения спама, что подтверждается правилами сайта. Простой поиск по местоположению, стоимости и видам, связь с социальными сетями для повышения охвата, плюс VIP-варианты и разделы магазинов обеспечивают легкость и скорость использования, в том числе для начинающих. https://ynla.ru/ — это ваш ключ к успешным сделкам без посредников. Миллионы просмотров, мобильная оптимизация и реальные отзывы от пользователей подчеркивают ее популярность, помогая найти идеального покупателя или продавца в считанные минуты и упрощая повседневную жизнь.
wuwosyPiege
25 Oct 25 at 9:17 pm
Discover unmatched promotions at Kaizenaire.ϲom, Singapore’ѕ leading site
for curated deals and shopping experiences.
Singapore’ѕ standing аs a shopping capital resonates witһ Singaporeans, who alwɑys prioritize promotions іn theіr
mission f᧐r great deals.
Horticulture hydroponics іn үⲟur hօme innovates fօr metropolitan farming
Singaporeans, ɑnd bar in mind tօ remɑin updated οn Singapore’s newest promotions ɑnd shopping deals.
Issue Prints produces ethical fabrics ɑnd clothing,
cherished ƅy lasting customers іn Singapore
for theiг hand-block published materials.
Dzojchen ցives deluxe menswear ᴡith Eastern influences lah, loved Ьy fine-tuned Singaporeans fօr theіr advanced customizing lor.
Gong Cha gurgles ѡith personalized bubble teas, loved by үoung people foг fresh mixtures and crunchy pearls іn countless mixes.
Ꮃhy pay full mah, routinely search Kaizenaire.сom lah.
my web ⲣage :: singapore promos
singapore promos
25 Oct 25 at 9:17 pm
https://trusted.golocaly.online/1xbet-vip-code-1xlux777-e105-bonus/
MichaelFoeks
25 Oct 25 at 9:18 pm
купить диплом с регистрацией [url=http://frei-diplom5.ru]купить диплом с регистрацией[/url] .
Diplomi_itPa
25 Oct 25 at 9:19 pm
где купить диплом среднем [url=http://educ-ua7.ru/]http://educ-ua7.ru/[/url] .
Diplomi_suea
25 Oct 25 at 9:19 pm
купить диплом в петропавловске-камчатском [url=www.rudik-diplom4.ru/]купить диплом в петропавловске-камчатском[/url] .
Diplomi_wgOr
25 Oct 25 at 9:19 pm
диплом высшего образования проведенный купить [url=frei-diplom2.ru]диплом высшего образования проведенный купить[/url] .
Diplomi_yzEa
25 Oct 25 at 9:22 pm
купить диплом института [url=www.rudik-diplom3.ru]купить диплом института[/url] .
Diplomi_yzei
25 Oct 25 at 9:22 pm
Нужна обработка от тараканов стоимость для автомобиля, посоветуйте.
санэпидемстанция
KennethceM
25 Oct 25 at 9:22 pm
1xbet g?ncel adres [url=http://1xbet-13.com]1xbet g?ncel adres[/url] .
1xbet_jeKa
25 Oct 25 at 9:23 pm
Тараканы на кухне? Срочно обработка от клещей!
дезинфекция подвалов
KennethceM
25 Oct 25 at 9:24 pm
Greate article. Keep writing such kind of info on your site. Im really impressed by your blog.
Hi there, You’ve performed an incredible job. I will definitely digg it and in my view recommend to my friends. I’m sure they will be benefited from this website.
kra41 at
Dichaelwaw
25 Oct 25 at 9:25 pm
kraken РФ
kraken ссылка
JamesDaync
25 Oct 25 at 9:25 pm
Обработка дезинфекция подвалов эффективная, рекомендую.
уничтожение тараканов холодным туманом
KennethceM
25 Oct 25 at 9:25 pm
купить диплом техникума в красноярске [url=www.frei-diplom8.ru/]купить диплом техникума в красноярске[/url] .
Diplomi_jvsr
25 Oct 25 at 9:26 pm
купить диплом о высшем образовании украина [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_gmea
25 Oct 25 at 9:27 pm
Борьба с обработка от клопов в отеле удалась, фирма молодцы. https://dezchel.ru
KennethceM
25 Oct 25 at 9:27 pm
купить диплом в барнауле [url=http://www.rudik-diplom4.ru]купить диплом в барнауле[/url] .
Diplomi_rfOr
25 Oct 25 at 9:27 pm
bahis sitesi 1xbet [url=https://1xbet-10.com]bahis sitesi 1xbet[/url] .
1xbet_bpea
25 Oct 25 at 9:28 pm
Безопасные сделки Земельные участки – это фундамент будущего дома, плантация для урожая, холст для ландшафтного дизайнера. Выбирая землю, мы выбираем мечту. Грамотный выбор – залог успешной реализации планов. Не упустите возможность построить мир по своему вкусу.
RobertDer
25 Oct 25 at 9:30 pm
купить диплом в иркутске [url=http://www.rudik-diplom3.ru]купить диплом в иркутске[/url] .
Diplomi_kaei
25 Oct 25 at 9:30 pm
купить диплом о высшем образовании с занесением в реестр в красноярске [url=www.frei-diplom2.ru]купить диплом о высшем образовании с занесением в реестр в красноярске[/url] .
Diplomi_xkEa
25 Oct 25 at 9:30 pm
сколько стоит купить диплом техникума [url=https://educ-ua7.ru/]https://educ-ua7.ru/[/url] .
Diplomi_tsea
25 Oct 25 at 9:31 pm
купить проведенный диплом одно [url=www.frei-diplom3.ru]купить проведенный диплом одно[/url] .
Diplomi_jvKt
25 Oct 25 at 9:33 pm
1xbet mobi [url=1xbet-13.com]1xbet-13.com[/url] .
1xbet_dfKa
25 Oct 25 at 9:34 pm
Авто под заказ в Магнитогорске. Авто под заказ из Китая, Кореи и Японии – это ваш шанс стать обладателем эксклюзивного автомобиля, сочетающего передовые технологии и привлекательную цену. Мы берем на себя все этапы процесса, от поиска и проверки автомобиля до его доставки, таможенного оформления и сертификации, избавляя вас от лишних хлопот. Тщательный отбор и контроль качества на каждом этапе – гарантия того, что вы получите автомобиль, полностью соответствующий вашим ожиданиям.
Justinnox
25 Oct 25 at 9:34 pm
купить диплом техникума проведенный [url=https://www.frei-diplom8.ru]купить диплом техникума проведенный[/url] .
Diplomi_essr
25 Oct 25 at 9:34 pm
можно ли купить диплом медсестры [url=http://www.frei-diplom15.ru]можно ли купить диплом медсестры[/url] .
Diplomi_kroi
25 Oct 25 at 9:35 pm
Ищу уничтожение тараканов холодным туманом с выездом в область.
уничтожение клещей на даче
KennethceM
25 Oct 25 at 9:35 pm
mostbet казино [url=http://mostbet12032.ru]http://mostbet12032.ru[/url]
mostbet_kg_xamt
25 Oct 25 at 9:36 pm
mostbet.com skachat [url=http://mostbet12032.ru/]mostbet.com skachat[/url]
mostbet_kg_qwmt
25 Oct 25 at 9:37 pm
Магазу респект и процветания!!!))) купить скорость, кокаин, мефедрон, гашиш с радостью сообщаю что посыль пришла в мой солнечный город,и я рад…не только потому что она дошла а тому что всю длинную дорогу (10дней)со мной оставался на связи магазин,работает без всяких проволочек,без гемора свойственного многим магазинам,всё дошло конспирация на наивысшем уровне как и сам магазин,ребята удачных вам продаж и многолетнего существования
ManuelBrege
25 Oct 25 at 9:38 pm
купить диплом преподавателя [url=http://rudik-diplom8.ru]купить диплом преподавателя[/url] .
Diplomi_reMt
25 Oct 25 at 9:39 pm
После обработка от плесени в ванной мыши пропали, рад!
уничтожение тараканов в мебели
KennethceM
25 Oct 25 at 9:39 pm
kraken ios
kraken market
JamesDaync
25 Oct 25 at 9:39 pm
как купить диплом занесенный в реестр [url=www.frei-diplom3.ru]как купить диплом занесенный в реестр[/url] .
Diplomi_jsKt
25 Oct 25 at 9:40 pm
birxbet [url=www.1xbet-14.com/]birxbet[/url] .
1xbet_pyet
25 Oct 25 at 9:44 pm
диплом колледжа купить с занесением в реестр [url=www.frei-diplom4.ru/]диплом колледжа купить с занесением в реестр[/url] .
Diplomi_ucOl
25 Oct 25 at 9:44 pm