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!
I have read several just right stuff here. Definitely price bookmarking for revisiting.
I surprise how a lot attempt you set to create the sort of fantastic
informative website.
canadian pharmacies online
15 Sep 25 at 8:51 am
Hey There. I found your weblog the use of msn. This
is an extremely neatly written article. I’ll be sure to bookmark it and come back to learn extra of your
helpful information. Thanks for the post. I’ll definitely return.
24 hour plumber
15 Sep 25 at 8:52 am
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 excellent
info I was looking for this info for my mission.
wga crystal
15 Sep 25 at 8:52 am
Greetings! Very useful advice within this article!
It is the little changes which will make the most important changes.
Many thanks for sharing!
telegram thc
15 Sep 25 at 8:52 am
https://judahbpph919.iamarrows.com/como-prepararte-la-semana-previa-a-un-control-sorpresa
Gestionar una prueba preocupacional puede ser arriesgado. Por eso, ahora tienes un metodo de enmascaramiento probada en laboratorios.
Su mezcla potente combina carbohidratos, lo que prepara tu organismo y disimula temporalmente los rastros de THC. El resultado: una orina con parametros normales, lista para entregar tranquilidad.
Lo mas destacado es su capacidad inmediata de respuesta. A diferencia de metodos caseros, no promete resultados permanentes, sino una estrategia de emergencia que funciona cuando lo necesitas.
Miles de estudiantes ya han comprobado su rapidez. Testimonios reales mencionan resultados exitosos en pruebas preocupacionales.
Si quieres proteger tu futuro, esta solucion te ofrece respaldo.
JuniorShido
15 Sep 25 at 8:53 am
Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех!
Ознакомиться с полной информацией – https://burnett.cc/?p=1
WilliamTwepe
15 Sep 25 at 8:53 am
Добрый день!
Долго анализировал как поднять сайт и свои проекты и нарастить ИКС Яндекса и узнал от друзей профессионалов,
топовых ребят, именно они разработали недорогой и главное буст прогон Хрумером – https://short33.site
Прогон ссылок для роста позиции улучшает видимость сайта. Xrumer: полное руководство помогает новичкам освоить инструмент. Создание ссылок массовыми методами экономит время. Как настроить Xrumer для рассылок становится понятным после инструкции. Генерация ссылок через Xrumer ускоряет продвижение.
сайт dr deco, сео классы, линкбилдинг статьи
сервис линкбилдинг, продвижение сайтов в по всей россии, продвижение сайта контент маркетинг
!!Удачи и роста в топах!!
Michaelbor
15 Sep 25 at 8:54 am
Узнайте всю информацию об сайте Авто-Фокус — широкий ассортимент автотоваров, аксессуаров и комплектующих для любых машин! Зайдите на [url=https://avto-fokus.ru]https://avto-fokus.ru[/url] и ознакомьтесь каталог запчастей. Нужна защита от угона или апгрейд звука? — интернет-ресурс предлагает противоугонные системы, аудио-системы и детали интерьера. Ищете надёжные запчасти — здесь найдёте качественные аналоги и хорошие условия заказа.
Spravkizxv
15 Sep 25 at 8:55 am
купить диплом училища [url=http://www.educ-ua10.ru]купить диплом училища[/url] .
Diplomi_qdKl
15 Sep 25 at 8:57 am
Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
Нажмите, чтобы узнать больше – https://dancingstarslinedance.dk/galleri/billeder/soendagsdans-januar-2018
JamesWek
15 Sep 25 at 8:57 am
It’s no secret how President Donald Trump feels about sports teams turning away from Native American mascots. He’s repeatedly called for the return of the Washington Redskins and Cleveland Indians, claiming their recent rebrands were part of a “woke” agenda designed to erase history.
[url=https://kra20at.org]kra38 at [/url]
But one surprising team has really gotten the president’s attention: the Massapequa Chiefs.
The Long Island school district has refused to change its logo and name under a mandate from New York state banning schools from using team mascots appropriating Indigenous culture. Schools were given two years to rebrand, but Massapequa is the lone holdout, having missed the June 30 deadline to debut a new logo.
[url=https://kra40-at.net]kra40[/url]
The district lost an initial lawsuit it filed against the state but now has the federal government on its side. In May, Trump’s Department of Education intervened on the district’s behalf, claiming the state’s mascot ban is itself discriminatory.
Massapequa’s Chiefs logo — an American Indian wearing a yellow feathered headdress — is expected to still be prominently displayed when the fall sports season kicks off soon, putting the quiet Long Island hamlet at the center of a political firestorm.
[url=https://kra39-cc.net]kra40[/url]
The district is now a key “battleground,” said Oliver Roberts, a Massapequa alum and the lawyer representing the school board in its fresh lawsuit against New York claiming that the ban is unconstitutional and discriminatory.
The Trump administration claims New York’s mascot ban violates Title VI of the Civil Rights Act of 1964, which prohibits recipients of federal funds from engaging in discriminatory behavior based on race, color or national origin — teeing up a potentially precedent-setting fight.
The intervention on behalf of Massapequa follows a pattern for a White House that has aggressively applied civil rights protections to police “reverse discrimination” and coerced schools and universities into policy concessions by withholding federal funds.
“Our goal is to assist nationally,” Roberts said. “It’s us putting forward our time and effort to try and assist with this national movement and push back against the woke bureaucrats trying to cancel our country’s history and tradition.”
kra39 сс
kra39 сс
ScottZib
15 Sep 25 at 8:58 am
That is really attention-grabbing, You are an overly professional blogger.
I’ve joined your feed and sit up for in the hunt for more of your fantastic post.
Additionally, I have shared your website in my social networks
Fundspire Axivon
15 Sep 25 at 8:58 am
мостбет скачат [url=http://mostbet12010.ru/]http://mostbet12010.ru/[/url]
mostbet_hmPt
15 Sep 25 at 9:00 am
https://truenorthpharm.com/# canadian pharmacy 24
JeremyBip
15 Sep 25 at 9:00 am
Мы предлагаем вам подробное руководство, основанное на проверенных источниках и реальных примерах. Каждая часть публикации направлена на то, чтобы помочь вам разобраться в сложных вопросах и применить знания на практике.
Лучшее решение — прямо здесь – https://fbre.be/uncategorized/hello-world-2
Kevinsok
15 Sep 25 at 9:01 am
SaludFrontera [url=http://saludfrontera.com/#]mexican pharmacy[/url] SaludFrontera
Michaelphype
15 Sep 25 at 9:01 am
Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
Все материалы собраны здесь – https://remarkablepeople.de/portra%CC%88t_beitrag
JaredBuh
15 Sep 25 at 9:01 am
Новости Украины и мира https://globalnewshome.com всё самое важное сегодня. Политика, экономика, региональные события, спорт и культура. Объективные статьи и аналитика в удобном формате.
FidelCag
15 Sep 25 at 9:05 am
скачать приложение мостбет [url=https://www.mostbet12011.ru]https://www.mostbet12011.ru[/url]
mostbet_vdOt
15 Sep 25 at 9:08 am
купить диплом в техникуме [url=www.educ-ua7.ru]купить диплом в техникуме[/url] .
Diplomi_zrEr
15 Sep 25 at 9:10 am
Портал для женщин https://womanfashionista.com всё самое важное в одном месте: уход за собой, мода, дом, семья и карьера. Читайте полезные статьи, находите вдохновение и делитесь опытом.
MatthewTok
15 Sep 25 at 9:11 am
гардина с электроприводом [url=www.elektro-karniz77.ru/]www.elektro-karniz77.ru/[/url] .
elektro karniz_ihSl
15 Sep 25 at 9:14 am
электрокарнизы москва [url=avtomaticheskie-karnizy.ru]avtomaticheskie-karnizy.ru[/url] .
avtomaticheskie karnizi_fkSa
15 Sep 25 at 9:16 am
SaludFrontera: tijuana pharmacy online – farmacia mexicana en linea
Charlesdyelm
15 Sep 25 at 9:18 am
First off I would like to say wonderful blog! I had a quick
question that I’d like to ask if you don’t mind. I was interested to find out how you center
yourself and clear your head prior to writing.
I have had trouble clearing my thoughts in getting my ideas out there.
I do take pleasure in writing however it just seems like the first 10 to 15 minutes tend to
be wasted simply just trying to figure out how to begin. Any recommendations or
tips? Appreciate it!
dewascatter link alternatif
15 Sep 25 at 9:19 am
https://truenorthpharm.com/# canada pharmacy world
CarlosPreom
15 Sep 25 at 9:20 am
электрический карниз для штор купить [url=https://elektro-karniz77.ru/]elektro-karniz77.ru[/url] .
elektro karniz_puSl
15 Sep 25 at 9:20 am
электрокарнизы для штор [url=www.avtomaticheskie-karnizy.ru/]электрокарнизы для штор[/url] .
avtomaticheskie karnizi_zjSa
15 Sep 25 at 9:22 am
This blog was… how do I say it? Relevant!! Finally I’ve found something that helped me.
Thank you!
Clarte Nexive
15 Sep 25 at 9:23 am
Generally I do not learn article on blogs, however I would like
to say that this write-up very compelled me to take a look at
and do it! Your writing taste has been surprised me.
Thank you, very great article.
WhatsApp网页版
15 Sep 25 at 9:24 am
Сайт детского сада https://malush16.ru МКДОУ 16 «Малыш» Омутнинского района — документы, образовательные стандарты, новости, фотогалерея и полезные материалы для родителей и педагогов.
Jamesseath
15 Sep 25 at 9:24 am
Wow! This blog looks exactly like my old one! It’s on a entirely different subject but it has pretty much the
same page layout and design. Great choice of colors!
Here is my website :: Alternatives to lifevests for ship safety
Alternatives to lifevests for ship safety
15 Sep 25 at 9:25 am
электронный карниз для штор [url=http://elektro-karniz77.ru/]http://elektro-karniz77.ru/[/url] .
elektro karniz_mdSl
15 Sep 25 at 9:31 am
электрокарниз двухрядный [url=https://www.avtomaticheskie-karnizy.ru]https://www.avtomaticheskie-karnizy.ru[/url] .
avtomaticheskie karnizi_lgSa
15 Sep 25 at 9:32 am
электронный карниз для штор [url=www.elektrokarniz-cena.ru]электронный карниз для штор[/url] .
elektrokarniz cena_pnPL
15 Sep 25 at 9:33 am
диплом техникума старого образца купить [url=educ-ua10.ru]диплом техникума старого образца купить[/url] .
Diplomi_mxKl
15 Sep 25 at 9:33 am
Xakerplus.com вам специалиста представляет, который приличным опытом обладает, качественно и оперативно работу осуществляет. XakVision анонимные услуги по взлому платформ и аккаунтов предлагает. Ищете взломать счет и вернуть деньги? Xakerplus.com/threads/uslugi-xakera-vzlom-tajnaja-slezhka.13001/page-3 – здесь представлена детальная информация о специалисте, ознакомьтесь с ней. XakVision оказывает услуги хакера по востребованным направлениям. Специалист применяет проверенные методы для достижения результата. Обращайтесь к нему!
rayeyFlist
15 Sep 25 at 9:33 am
электрокарнизы купить в москве [url=http://www.elektro-karniz77.ru]http://www.elektro-karniz77.ru[/url] .
elektro karniz_zzSl
15 Sep 25 at 9:34 am
Узнайте все подробности об площадке Авто-Фокус — большой каталог автотоваров, аксессуаров и комплектующих для разных авто! Перейдите на [url=https://avto-fokus.ru]https://avto-fokus.ru[/url] и узнайте доступные позиции. Нужна безопасность автомобиля или обновление аудиосистемы? — площадка предлагает сигналки, музыку в авто и аксессуары. Ищете надёжные запчасти — здесь найдёте оригинальные бренды и удобную отправку.
Spravkidkm
15 Sep 25 at 9:34 am
These are genuinely enormous ideas in concerning blogging.
You have touched some pleasant factors here.
Any way keep up wrinting.
123 b
15 Sep 25 at 9:36 am
карниз для штор электрический [url=https://avtomaticheskie-karnizy.ru]https://avtomaticheskie-karnizy.ru[/url] .
avtomaticheskie karnizi_ozSa
15 Sep 25 at 9:36 am
автоматические карнизы для штор [url=http://www.elektrokarniz-cena.ru]автоматические карнизы для штор[/url] .
elektrokarniz cena_uwPL
15 Sep 25 at 9:39 am
Kaizenaire.cߋm սseѕ Singaporeans thе finest promotions, mɑking it
tһe best website for deals.
Singaporeans’ exhilaration fⲟr deals iѕ palpable іn Singapore’s
dynamic shopping heaven.
Singaporeans relish weekend brunches аt elegant eateries ar᧐und town, and
bear in mind to stay updated ᧐n Singapore’s most current promotions and shopping deals.
Love, Bonito ⲣrovides females’ѕ clothing witһ flexible styles, favored Ьү Singaporean women fⲟr
theiг flattering fits аnd modern style.
Ginlee crafts ageless females’ѕ wear ᴡith high quality textiles leh, preferred ƅү advanced Singaporeans fоr their lօng-lasting style one.
Pokka revitalizes ԝith teas and juices іn hassle-free packs, treasured Ьy busy Singaporeans f᧐r their
refreshing, vitamin-packed options ⲟn the go.
Wah lao, so shiok sіa, Kaizenaire.сom deals waiting lor.
my webpage recruitment agency in raffles place singapore
recruitment agency in raffles place singapore
15 Sep 25 at 9:39 am
Новости Украины и мира https://globalnewshome.com всё самое важное сегодня. Политика, экономика, региональные события, спорт и культура. Объективные статьи и аналитика в удобном формате.
FidelCag
15 Sep 25 at 9:40 am
tele4
טלגראס כיוונים רמת גן
15 Sep 25 at 9:42 am
Новости Украины и мира https://globalnewshome.com всё самое важное сегодня. Политика, экономика, региональные события, спорт и культура. Объективные статьи и аналитика в удобном формате.
FidelCag
15 Sep 25 at 9:42 am
Kaizenaire.com excels as the ultimate manager ߋf Singapore’s shopping promotions.
Singapore stands honored аѕ a shopping utopia, where deals spark Singaporean enthusiasm.
Τaking ρart in marathons builds endurance fоr figured out Singaporeans, ɑnd bear in mind to stay upgraded ߋn Singapore’s most recent promotions and shopping deals.
Adidas offers sportswear and tennis shoes, cherished ƅy Singaporeans fоr tһeir elegant activewear аnd recommendation ƅү
regional professional athletes.
Banyan Tree useѕ deluxe resorts and medspa services lah, adored Ƅy Singaporeans
f᧐r their serene gets away and health therapies lor.
Boon Tong Kee conveniences ԝith smooth chicken rice ɑnd sides, beloved by families fⲟr cozy tastes ɑnd generous
sections.
Aunties understand lah, Kaizenaire.сom has the neweѕt deals leh.
my web site … office chair promotions
office chair promotions
15 Sep 25 at 9:42 am
купить диплом образование купить проведенный диплом [url=www.arus-diplom31.ru/]купить диплом образование купить проведенный диплом[/url] .
Kypit diplom ob obrazovanii!_zoOl
15 Sep 25 at 9:43 am
Новости Украины и мира https://globalnewshome.com всё самое важное сегодня. Политика, экономика, региональные события, спорт и культура. Объективные статьи и аналитика в удобном формате.
FidelCag
15 Sep 25 at 9:44 am
электрокарниз [url=http://avtomaticheskie-karnizy-dlya-shtor.ru/]электрокарниз[/url] .
avtomaticheskie karnizi dlya shtor_hyOr
15 Sep 25 at 9:44 am