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!
This is very interesting, You are a very skilled blogger.
I have joined your rss feed and look forward to seeking more
of your magnificent post. Also, I have shared your website
in my social networks!
Feel free to visit my web site … organic matcha green tea
organic matcha green tea
15 Sep 25 at 7:31 pm
slotguru.ru
JerryBic
15 Sep 25 at 7:35 pm
Hello There. I found your blog using msn. This is a very well written article.
I’ll be sure to bookmark it and return to read more
of your useful info. Thanks for the post. I will definitely comeback.
Hitomi Tanaka
15 Sep 25 at 7:35 pm
купить диплом колледжа [url=www.educ-ua4.ru/]купить диплом колледжа[/url] .
Diplomi_rtPl
15 Sep 25 at 7:36 pm
купить диплом о высшем образовании специалиста [url=www.educ-ua20.ru]купить диплом о высшем образовании специалиста[/url] .
Diplomi_ynEn
15 Sep 25 at 7:38 pm
карниз с приводом [url=https://www.karnizy-s-elektroprivodom-cena.ru]https://www.karnizy-s-elektroprivodom-cena.ru[/url] .
karnizi s elektroprivodom cena_bpkr
15 Sep 25 at 7:40 pm
Наркологический центр в владимире предлагает комплексную наркологическую помощь, включая вызов нарколога на дом и анонимное лечение. Опытные специалисты позволяют успешно лечить зависимость от алкоголя. Центр предлагает программы реабилитации, которые включают психотерапевтическую помощь, адаптацию в обществе и поддержку зависимых. Консультация нарколога поможет определить текущее состояние пациента и выбрать оптимальные методы лечения при алкоголизме. Важно уделять внимание профилактике зависимости от алкоголя и восстановлении после зависимости. вызов нарколога владимир
zapojvladimirNeT
15 Sep 25 at 7:40 pm
Greetings I am so excited I found your blog, I really found you by error, while I was looking on Aol for something else,
Anyways I am here now and would just like to say kudos for a incredible post and a
all round entertaining blog (I also love the theme/design),
I don’t have time to look over it all at the minute but I have saved it and also added in your RSS feeds, so
when I have time I will be back to read much more, Please do keep up the great work.
fb303
15 Sep 25 at 7:41 pm
Great blog! Is your theme custom made or did you download it from somewhere?
A theme like yours with a few simple adjustements would really make my
blog shine. Please let me know where you
got your theme. Bless you
CanBenefits
15 Sep 25 at 7:42 pm
I love what you guys tend to be up too. This sort of
clever work and exposure! Keep up the good works guys I’ve added you guys to blogroll.
standby generator maintenance Richmond
15 Sep 25 at 7:43 pm
карнизы для штор с электроприводом [url=https://www.karnizy-s-elektroprivodom-cena.ru]карнизы для штор с электроприводом[/url] .
karnizi s elektroprivodom cena_hpkr
15 Sep 25 at 7:44 pm
I know this if off topic but I’m looking into starting my own weblog and was wondering what all
is needed to get setup? I’m assuming having a blog like
yours would cost a pretty penny? I’m not very web savvy so I’m not 100% positive.
Any recommendations or advice would be greatly appreciated.
Thank you
bokep online
15 Sep 25 at 7:45 pm
автоматические гардины для штор [url=www.karniz-s-elektroprivodom-kupit.ru/]www.karniz-s-elektroprivodom-kupit.ru/[/url] .
karniz s elektroprivodom kypit_jeEr
15 Sep 25 at 7:45 pm
Unlock Singapore’s shopping tricks at Kaizenaire.com, the leading curator օf promotions, deals, and events fߋr
customers.
In tһe customer’ѕ sanctuary of Singapore, citizens’ love for promotions tᥙrns every
deal іnto a celebrated triumph.
Singaporeans ɑppreciate kite flying at Marina Barrage օn windy ԁays, ɑnd remember to remаin upgraded օn Singapore’s ⅼatest promotions аnd shopping deals.
FairPrice, ɑ popular supermarket chain, supplies groceries аnd family basics
at affordable rates, enjoyed ƅy Singaporeans
for their daily vɑlue аnd neighborhood support.
Aalst Chocolate сreates costs artisanal delicious chocolates lah,
valued ƅy sweet-toothed Singaporeans fоr their rich flavors аnd neighborhood craftsmanship lor.
Nation Foods processes fowl ɑnd meats, precious for fresh supplies іn neighborhood markets.
Ɗo not say I never ever tell mah, search Kaizenaire.cօm fⲟr shopping deals lah.
Ꮇy web-site; ice skating promotions (davidpawson.org)
davidpawson.org
15 Sep 25 at 7:47 pm
электрические рулонные шторы купить [url=elektricheskie-rulonnye-shtory15.ru]elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_brEi
15 Sep 25 at 7:50 pm
Сначала врач проводит экспресс-диагностику. Измеряются давление, пульс, сатурация, температура, оценивается неврологический статус и уровень обезвоживания. Уточняются аллергии, хронические заболевания, длительность и объём употребления, принимаемые препараты. При необходимости выполняется ЭКГ, чтобы исключить острые риски со стороны сердечно-сосудистой системы.
Получить дополнительную информацию – [url=https://narkolog-na-dom-krasnogorsk6.ru/]нарколог на дом[/url]
Raymondfem
15 Sep 25 at 7:52 pm
гардина с электроприводом [url=https://karniz-s-elektroprivodom-kupit.ru]https://karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_cxEr
15 Sep 25 at 7:52 pm
come posso ottenere cipro
dove posso trovare la pillola di cipro generico
15 Sep 25 at 7:53 pm
Алгоритм одинаково прозрачен в обоих форматах. Сначала — экспресс-диагностика: уровень сознания, сатурация, пульс, давление, температура, оценка неврологического статуса и обезвоживания. Затем врач формирует индивидуальную инфузионную схему: регидратационные растворы, коррекция электролитов, поддержка печени и нервной системы, адресная симптоматическая помощь (сон, тревога, тошнота, головная боль). Темп и объём подбираются по переносимости — без «универсальных коктейлей» и лишних препаратов.
Детальнее – [url=https://vyvod-iz-zapoya-pushkino7.ru/]vyvod-iz-zapoya-na-donu[/url]
LeslieSoG
15 Sep 25 at 7:55 pm
рулонные шторы на пластиковые окна на кухню [url=www.avtomaticheskie-rulonnye-shtory5.ru]www.avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_vtsr
15 Sep 25 at 7:56 pm
тканевые жалюзи рулонные на окна цена [url=https://www.elektricheskie-rulonnye-shtory15.ru]https://www.elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_pbEi
15 Sep 25 at 7:57 pm
Самостоятельно выйти из запоя — почти невозможно. В Краснодаре врачи клиники проводят медикаментозный вывод из запоя с круглосуточным выездом. Доверяйте профессионалам.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-krasnodar17.ru/]нарколог на дом вывод город краснодар[/url]
Keithbut
15 Sep 25 at 7:59 pm
http://evakuatorhelp.ru/ Мы предлагаем различные тарифы на эвакуацию, чтобы каждому клиенту было удобно выбрать подходящий вариант
Jamiedaymn
15 Sep 25 at 8:00 pm
рулонные шторы на окна на заказ [url=www.avtomaticheskie-rulonnye-shtory5.ru/]www.avtomaticheskie-rulonnye-shtory5.ru/[/url] .
avtomaticheskie rylonnie shtori_ltsr
15 Sep 25 at 8:03 pm
электрокарниз двухрядный [url=www.karniz-s-elektroprivodom-kupit.ru/]www.karniz-s-elektroprivodom-kupit.ru/[/url] .
karniz s elektroprivodom kypit_hmEr
15 Sep 25 at 8:03 pm
Excellent, what a web site it is! This webpage
gives helpful data to us, keep it up.
bokep ter update
15 Sep 25 at 8:04 pm
автоматический карниз для штор [url=https://karnizy-s-elektroprivodom-cena.ru/]https://karnizy-s-elektroprivodom-cena.ru/[/url] .
karnizi s elektroprivodom cena_lwkr
15 Sep 25 at 8:05 pm
карниз для штор с электроприводом [url=www.karniz-s-elektroprivodom-kupit.ru/]www.karniz-s-elektroprivodom-kupit.ru/[/url] .
karniz s elektroprivodom kypit_xzEr
15 Sep 25 at 8:08 pm
Awesome article.
turkey visa for australian
15 Sep 25 at 8:08 pm
рулонные шторы автоматические купить [url=https://elektricheskie-rulonnye-shtory15.ru/]https://elektricheskie-rulonnye-shtory15.ru/[/url] .
elektricheskie rylonnie shtori_mfEi
15 Sep 25 at 8:08 pm
карнизы для штор купить в москве [url=http://karnizy-s-elektroprivodom-cena.ru/]карнизы для штор купить в москве[/url] .
karnizi s elektroprivodom cena_unkr
15 Sep 25 at 8:12 pm
888starz скачать на айфон http://www.ferrum.com.pg/index.php/2025/09/06/888starz-poluchayte-sotke-bonus-poluchite-i-raspishites-pervyy-evrodollar-khot-zavtra/
888starzzzzzzzzzzzzz
15 Sep 25 at 8:12 pm
купить рольшторы цены [url=https://www.elektricheskie-rulonnye-shtory15.ru]https://www.elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_rlEi
15 Sep 25 at 8:12 pm
купить рулонные шторы в москве [url=https://avtomaticheskie-rulonnye-shtory5.ru/]купить рулонные шторы в москве[/url] .
avtomaticheskie rylonnie shtori_uksr
15 Sep 25 at 8:13 pm
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://kra40-cc.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://kra-40cc.ru]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://kra-34cc.ru]kra38 at[/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.”
kra38
kra39 at
ScottZib
15 Sep 25 at 8:14 pm
рулонные шторы на окна москва [url=https://avtomaticheskie-rulonnye-shtory5.ru/]avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_sbsr
15 Sep 25 at 8:17 pm
электрокарнизы цена [url=karnizy-s-elektroprivodom-cena.ru]электрокарнизы цена[/url] .
karnizi s elektroprivodom cena_ywkr
15 Sep 25 at 8:18 pm
стоимость согласования перепланировки квартиры [url=www.angelladydety.getbb.ru/viewtopic.php?f=42&t=59347&p=109062/]стоимость согласования перепланировки квартиры[/url] .
soglasovanie pereplanirovki kvartiri moskva _qaka
15 Sep 25 at 8:21 pm
where can i get generic eriacta without dr prescription
can you get eriacta without insurance
15 Sep 25 at 8:25 pm
CanCan Saloon TR
Donaldbow
15 Sep 25 at 8:25 pm
Butterfly Lovers online Az
Derekjency
15 Sep 25 at 8:25 pm
Brick Snake 2000 играть в Максбет
GeorgeDum
15 Sep 25 at 8:25 pm
Казино Mostbet
EdwardTix
15 Sep 25 at 8:26 pm
Мы предлагаем дипломы любых профессий по доступным тарифам. Покупка документа, подтверждающего окончание института, – это рациональное решение. Заказать диплом любого университета: [url=http://wow.t-mobility.co.il/read-blog/35405_diplom-oficialno-kupit.html/]wow.t-mobility.co.il/read-blog/35405_diplom-oficialno-kupit.html[/url]
Mazrako
15 Sep 25 at 8:27 pm
Book of Wisdom casinos TR
Edgarclome
15 Sep 25 at 8:28 pm
карниз с приводом для штор [url=https://karniz-s-elektroprivodom-kupit.ru/]https://karniz-s-elektroprivodom-kupit.ru/[/url] .
karniz s elektroprivodom kypit_tnEr
15 Sep 25 at 8:29 pm
Hey just wanted to give you a quick heads up. The text
in your content seem to be running off the screen in Opera.
I’m not sure if this is a format issue or something
to do with browser compatibility but I figured I’d post to let you know.
The layout look great though! Hope you get the problem
resolved soon. Kudos
slut
15 Sep 25 at 8:32 pm
cost of generic dilantin pills
can you get generic dilantin without rx
15 Sep 25 at 8:32 pm
обслуживание инженерных систем
Rolandmow
15 Sep 25 at 8:33 pm
шторы на окна купить [url=https://elektricheskie-rulonnye-shtory15.ru/]https://elektricheskie-rulonnye-shtory15.ru/[/url] .
elektricheskie rylonnie shtori_iiEi
15 Sep 25 at 8:34 pm