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!
продвижение сайтов в топ 10 москва [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]продвижение сайтов в топ 10 москва[/url] .
agentstvo poiskovogo prodvijeniya_fyKt
21 Oct 25 at 8:33 pm
startyourdreamproject – I found fresh ideas here that helped me imagine a new creative direction.
Leida Vice
21 Oct 25 at 8:34 pm
В Самаре в «Частном Медике 24» пациент получает детоксикацию, восстановительное лечение и круглосуточное наблюдение врачей.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]наркология вывод из запоя в стационаре[/url]
JamesNic
21 Oct 25 at 8:35 pm
inspiredailyandgrow.click – Mobile browsing was smooth, site seems responsive which is a plus for me.
Orpha Chevarie
21 Oct 25 at 8:37 pm
seo продвижение россия [url=http://reiting-seo-agentstv.ru]seo продвижение россия[/url] .
reiting seo agentstv_mbsa
21 Oct 25 at 8:37 pm
рейтинг агентств digital [url=luchshie-digital-agencstva.ru]рейтинг агентств digital[/url] .
lychshie digital agentstva_stoi
21 Oct 25 at 8:37 pm
сео продвижение сайта москва [url=http://www.reiting-seo-agentstv-moskvy.ru]сео продвижение сайта москва[/url] .
reiting seo agentstv moskvi_ocMl
21 Oct 25 at 8:38 pm
seo продвижение рейтинг [url=http://reiting-seo-kompanii.ru]seo продвижение рейтинг[/url] .
reiting seo kompanii_hlsn
21 Oct 25 at 8:39 pm
Hi there! This is kind of off topic but I need some advice from an established blog.
Is it hard to set up your own blog? I’m not very
techincal but I can figure things out pretty fast.
I’m thinking about making my own but I’m not sure where to begin.
Do you have any tips or suggestions? Thank you
app tài xỉu
21 Oct 25 at 8:39 pm
СПб все ровно процветания магазину. Амф на 5+
https://volnovakhazy.ru
суббота, воскресение у них выходной
Donaldmoire
21 Oct 25 at 8:40 pm
Appreciation to my father who informed me on the topic
of this web site, this weblog is actually amazing.
Finxor Gpt
21 Oct 25 at 8:41 pm
Где купить Клад в Камень-на-Обие?Вот, обнаружил сайт https://eronis.ru
– по ценам устроило, доставляют быстро. Кто-нибудь тестил у них? Насколько качественный товар?
Stevenref
21 Oct 25 at 8:43 pm
web marketing seo [url=www.reiting-runeta-seo.ru/]web marketing seo[/url] .
reiting ryneta seo_ipma
21 Oct 25 at 8:43 pm
https://baidak.ru/
Eugenioves
21 Oct 25 at 8:44 pm
Greetings from Carolina! I’m bored to death at work so I decided to browse your website on my iphone during lunch break.
I love the knowledge you present here and can’t
wait to take a look when I get home. I’m surprised at how fast your blog
loaded on my phone .. I’m not even using WIFI, just 3G ..
Anyhow, amazing blog!
industrial kitchen exhaust
21 Oct 25 at 8:44 pm
https://medtronik.ru/ полный обзор доступных акций 1xBet
Aaronawads
21 Oct 25 at 8:45 pm
seo продвижение в москве [url=http://seo-prodvizhenie-reiting-kompanij.ru]seo продвижение в москве[/url] .
seo prodvijenie reiting kompanii_mlst
21 Oct 25 at 8:45 pm
купить диплом техникума советского образца [url=http://frei-diplom8.ru]купить диплом техникума советского образца[/url] .
Diplomi_zmsr
21 Oct 25 at 8:45 pm
топ компаний по продвижению сайтов [url=https://seo-prodvizhenie-reiting.ru/]https://seo-prodvizhenie-reiting.ru/[/url] .
seo prodvijenie reiting_neEa
21 Oct 25 at 8:47 pm
Goodness, no matter if institution proves һigh-end, maths serves as the decisive subject in building poise
regarding figures.
Alas, primary maths educates practical implementations including money management, tһus ensure уοur youngster grasps іt
correctly fгom young.
Eunoia Junior College represents contemporary innovation іn education, with its hіgh-rise
campus incorporating neighborhood аreas fоr collaborative knowing ɑnd
development. Tһe college’ѕ focus on lovely thinking fosters intellectual
curiosity ɑnd goodwill, supported Ƅy vibrant programs іn arts,
sciences, and leadership. Modern facilities,
consisting ⲟf carrying oսt arts places, аllow students to check oᥙt passions
and develop skills holistically. Partnerships ԝith esteemed organizations provide enriching opportunities fоr гesearch and global
direct exposure. Trainees emerge ɑѕ thoughtful leaders, prepared t᧐ contribute positively tο a varied ᴡorld.
Anglo-Chinese School (Independent) Junior College ⲣrovides ɑn enriching education deeply rooted іn faith, wheгe intellectual exploration is
harmoniously balanced ԝith core ethical concepts,
assisting trainees towaгds Ƅecoming understanding ɑnd responsibⅼе global people equipped tο attend tօ complicated
social obstacles. Τhe school’s prestigious International
Baccalaureate Diploma Programme promotes innovative іmportant thinking, reseɑrch
study skills, аnd interdisciplinary knowing, boosted Ьу extraordinary resources ⅼike devoted innovation hubs аnd skilled faculty who mentor students in attaining academic distinction. Α
broad spectrum of co-curricular offerings, fгom addvanced robotics ϲlubs that encourage
technological creativity tߋ symphony orchestras
tһat refine musical talents, аllows students to discover ɑnd fіne-tune tһeir unique capabilities in a
encouraging ɑnd stimulating environment. By incorporating service learning initiatives, ѕuch aѕ community outreach projects ɑnd volunteer programs Ƅoth
in your area and worldwide, tһe college cultivates a strong sense
ߋf social duty, compassion, аnd active citizenship аmong its student body.
Graduates оf Anglo-Chinese School (Independent) Junior College ɑre
exceptionally welⅼ-prepared fօr entry іnto elite universities аll over thhe woгld, carrying with them a distinguished
tradition of academic excellence, individual integrity, ɑnd a dedication to lߋng-lasting learning аnd
contribution.
Mums and Dads, fearful of losing mode ߋn lah, solid primary math leads for Ƅetter scientific comprehension ρlus engineering goals.
Ⲟh, math acts likе tһe base stone in primary education, assisting kids іn spatial analysis fоr
design careers.
Aiyo, mіnus robust mathematics ɗuring Junior College, even prestigious institution kids
mаy stumble at next-level calculations, thus develop it now leh.
Parents, kiasu mode оn lah, robust primary
maths гesults foг better STEM understanding ρlus engineering dreams.
Օh, mathematics acts ⅼike tһe base pillar in primary learning, assisting
children f᧐r dimensional thinking fοr design routes.
Without Math proficiency, options fоr economics majors shrink dramatically.
Wah lao, no matter ԝhether establishment іs hіgh-end, mathematics serves as tһе decisive
subject in developing poise ԝith numbers.
Alas, primary math instructs practical implementations ⅼike budgeting, ѕо ensure your child gеts thiѕ properly
from young age.
Feel free tο surf tߋ my website; Catholic Junior College
Catholic Junior College
21 Oct 25 at 8:49 pm
best seo agency [url=http://reiting-runeta-seo.ru/]http://reiting-runeta-seo.ru/[/url] .
reiting ryneta seo_phma
21 Oct 25 at 8:49 pm
топ агентств россии [url=http://www.luchshie-digital-agencstva.ru]http://www.luchshie-digital-agencstva.ru[/url] .
lychshie digital agentstva_jsoi
21 Oct 25 at 8:50 pm
seo продвижение агентство услуга [url=http://reiting-seo-agentstv.ru]seo продвижение агентство услуга[/url] .
reiting seo agentstv_kwsa
21 Oct 25 at 8:50 pm
infinitalink.click – The layout is clean and loading was quick, first impression is positive.
Willian Vettel
21 Oct 25 at 8:50 pm
Excellent post! We are linking to this great content on our website.
Keep up the good writing.
casino utan svensk licens
21 Oct 25 at 8:52 pm
seo firm ranking [url=http://reiting-seo-kompanii.ru/]http://reiting-seo-kompanii.ru/[/url] .
reiting seo kompanii_tksn
21 Oct 25 at 8:53 pm
https://britmedsuk.com/# licensed online pharmacy UK
LanceHek
21 Oct 25 at 8:53 pm
DRINKIO стал для меня настоящим спасением, когда нужно быстро что-то заказать к празднику. Всё оформляется моментально, доставка работает даже ночью. Курьеры пунктуальные, общение приятное. Чувствуется, что компания заботится о клиентах и их времени https://drinkio105.ru/
Arthurtok
21 Oct 25 at 8:55 pm
seo агентство москва [url=https://reiting-seo-agentstv-moskvy.ru/]seo агентство москва[/url] .
reiting seo agentstv moskvi_dbMl
21 Oct 25 at 8:57 pm
Je suis accro a VBet Casino, on dirait une eruption de plaisirs incandescents. Il y a une deferlante de jeux de casino captivants, comprenant des jeux de casino adaptes aux cryptomonnaies. Le personnel du casino offre un accompagnement digne d’un volcan, assurant un support de casino immediat et incandescent. Les paiements du casino sont securises et fluides, parfois plus de tours gratuits au casino ce serait volcanique. En somme, VBet Casino est une pepite pour les fans de casino pour ceux qui cherchent l’adrenaline enflammee du casino ! Bonus l’interface du casino est fluide et eclatante comme un cratere en fusion, ajoute une touche de feu au casino.
vbet автомати україна|
fizzyglitterlemur9zef
21 Oct 25 at 8:58 pm
Выездная наркологическая помощь в Нижнем Новгороде — капельница от запоя с выездом на дом. Мы обеспечиваем быстрое и качественное лечение без необходимости посещения клиники.
Разобраться лучше – [url=https://vyvod-iz-zapoya-nizhnij-novgorod11.ru/]вывод из запоя[/url]
Norbertavoig
21 Oct 25 at 8:59 pm
«Частный Медик 24» — это медицинский контроль, поддержка и лечение на всех этапах вывода из запоя.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-v-stacionare21.ru/]вывод из запоя в стационаре анонимно нижний новгород[/url]
Eduardonibre
21 Oct 25 at 9:02 pm
компании по продвижению сайта [url=https://seo-prodvizhenie-reiting.ru/]компании по продвижению сайта[/url] .
seo prodvijenie reiting_sqEa
21 Oct 25 at 9:02 pm
В стационаре «Частного Медика 24» пациент получает комплексное лечение, включая капельницы и медикаменты.
Подробнее можно узнать тут – https://vyvod-iz-zapoya-v-stacionare-voronezh23.ru
Edwardnalia
21 Oct 25 at 9:02 pm
Клиника «Детокс» в Сочи предлагает услугу вывода из запоя в стационаре. Под наблюдением профессиональных врачей пациент получит необходимую медицинскую помощь и поддержку. Услуга доступна круглосуточно, анонимно и начинается от 2000 ?.
Детальнее – [url=https://vyvod-iz-zapoya-sochi24.ru/]вывод из запоя с выездом в сочи[/url]
DavidExarl
21 Oct 25 at 9:02 pm
рейтинг сео [url=https://seo-prodvizhenie-reiting.ru/]https://seo-prodvizhenie-reiting.ru/[/url] .
seo prodvijenie reiting_wsEa
21 Oct 25 at 9:04 pm
агентства контекстная реклама продвижение сайтов [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/[/url] .
agentstvo poiskovogo prodvijeniya_atKt
21 Oct 25 at 9:05 pm
I relish, result in I discovered exactly what I used to be having a look for.
You’ve ended my 4 day long hunt! God Bless you man.
Have a nice day. Bye
kraken32
21 Oct 25 at 9:06 pm
рекламное агентство seo [url=reiting-seo-kompanii.ru]рекламное агентство seo[/url] .
reiting seo kompanii_kfsn
21 Oct 25 at 9:06 pm
продвижение в топ [url=http://www.reiting-seo-agentstv.ru]продвижение в топ[/url] .
reiting seo agentstv_insa
21 Oct 25 at 9:07 pm
Hi i am kavin, its my first time to commenting anyplace,
when i read this piece of writing i thought i could also create comment due to this
good piece of writing.
web page
21 Oct 25 at 9:07 pm
خرید ویپ
شاپور لواسانی
21 Oct 25 at 9:07 pm
продвижение сайтов компания [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru]https://reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_egKt
21 Oct 25 at 9:08 pm
оптимизация продвижение сайтов поисковых системах [url=https://reiting-runeta-seo.ru]https://reiting-runeta-seo.ru[/url] .
reiting ryneta seo_qama
21 Oct 25 at 9:08 pm
установка кондиционера в москве недорого Закладка и Прокладка Трассы: Важный Этап для Эстетики и Долговечности Закладка трассы и прокладка трассы для кондиционера – это ключевая задача, от которой зависит внешний вид и надежность всей системы. Мы проводим работы аккуратно и эффективно, минимизируя видимые коммуникации и обеспечивая долговечность трассы. Мы используем современные технологии и материалы, чтобы гарантировать эстетичный вид и бесперебойную работу кондиционера.
Johnniemuh
21 Oct 25 at 9:09 pm
smarttechmukesh.xyz – I like the clean typography and balanced white space all around.
Shalonda Dellen
21 Oct 25 at 9:09 pm
сео компания москва [url=https://reiting-seo-agentstv-moskvy.ru]https://reiting-seo-agentstv-moskvy.ru[/url] .
reiting seo agentstv moskvi_arMl
21 Oct 25 at 9:10 pm
https://bluepeakmeds.shop/# order viagra
LanceHek
21 Oct 25 at 9:12 pm
2rss5ge.xyz – The layout looks clean and professional, nice first impression overall.
Trey Vavro
21 Oct 25 at 9:12 pm
можно купить диплом техникума lr 63 [url=http://frei-diplom7.ru]можно купить диплом техникума lr 63[/url] .
Diplomi_gvei
21 Oct 25 at 9:13 pm