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!
электрические карнизы купить [url=http://elektrokarniz-cena.ru/]http://elektrokarniz-cena.ru/[/url] .
elektrokarniz cena_fyPL
15 Sep 25 at 12:46 pm
электрокарниз двухрядный [url=avtomaticheskie-karnizy-dlya-shtor.ru]электрокарниз двухрядный[/url] .
avtomaticheskie karnizi dlya shtor_hbOr
15 Sep 25 at 12:47 pm
электрокарнизы в москве [url=http://www.karniz-s-elektroprivodom.ru]электрокарнизы в москве[/url] .
karniz s elektroprivodom_tnKt
15 Sep 25 at 12:50 pm
электрокарнизы купить в москве [url=https://elektro-karniz77.ru/]https://elektro-karniz77.ru/[/url] .
elektro karniz_grSl
15 Sep 25 at 12:51 pm
автоматические карнизы для штор [url=http://www.avtomaticheskie-karnizy.ru]автоматические карнизы для штор[/url] .
avtomaticheskie karnizi_frSa
15 Sep 25 at 12:51 pm
электрокарнизы для штор купить [url=www.elektrokarniz-cena.ru/]электрокарнизы для штор купить[/url] .
elektrokarniz cena_fsPL
15 Sep 25 at 12:52 pm
электрические карнизы для штор в москве [url=www.karniz-s-elektroprivodom.ru/]электрические карнизы для штор в москве[/url] .
karniz s elektroprivodom_ggKt
15 Sep 25 at 12:52 pm
Проблема алкоголизма в Ярославле, как и в других регионах России, остаётся одной из самых актуальных. По данным Минздрава РФ, количество людей, нуждающихся в медицинской помощи из-за злоупотребления спиртным, ежегодно растёт. При этом эффективное лечение возможно лишь при комплексном подходе, включающем как медицинскую, так и психологическую поддержку.
Ознакомиться с деталями – https://lechenie-alkogolizma-yaroslavl0.ru/anonimnoe-lechenie-alkogolizma-yaroslavl/
KennyTus
15 Sep 25 at 12:52 pm
купить диплом о среднем техническом образовании [url=https://educ-ua18.ru/]купить диплом о среднем техническом образовании[/url] .
Diplomi_msPi
15 Sep 25 at 12:53 pm
электрокарниз [url=https://avtomaticheskie-karnizy-dlya-shtor.ru/]электрокарниз[/url] .
avtomaticheskie karnizi dlya shtor_saOr
15 Sep 25 at 12:54 pm
автоматические гардины для штор [url=http://www.elektrokarniz-cena.ru]автоматические гардины для штор[/url] .
elektrokarniz cena_ojPL
15 Sep 25 at 12:56 pm
Мы готовы предложить документы учебных заведений, которые находятся на территории всей России. Заказать диплом о высшем образовании:
[url=http://yooreal.com/read-blog/23161_gde-mozhno-kupit-attestat-za-9-klass.html/]купить аттестат за 11 класс новосибирск[/url]
Diplomi_cuPn
15 Sep 25 at 12:56 pm
Статьи для садоводов https://portalteplic.ru огородников, фермеров и пчеловодов: советы по уходу за растениями, животными и пасекой. Полезные инструкции, лайфхаки и сезонные рекомендации.
Ronalddug
15 Sep 25 at 12:57 pm
Врач самостоятельно оценивает тяжесть интоксикации и назначает необходимый курс инфузий, физиопроцедур и приём препаратов. Варианты терапии включают детокс-комплекс, коррекцию водно-электролитного баланса и витаминотерапию.
Ознакомиться с деталями – [url=https://narkologicheskaya-klinika-arkhangelsk0.ru/]наркологическая клиника нарколог[/url]
Barryhex
15 Sep 25 at 12:57 pm
Mega darknet Мега даркнет Мега сайт Мега онион Мега ссылка Mega даркнет Mega сайт Mega онион Mega ссылка Mega darknet Mega onion
RichardPep
15 Sep 25 at 12:57 pm
Портал о ремонте https://studio-nd.ru статьи, инструкции и советы для дома и квартиры. От выбора материалов до дизайна интерьеров. Полезные рекомендации для мастеров, новичков и частных застройщиков.
HowardRof
15 Sep 25 at 12:58 pm
Greetings! I just came across this fantastic article on virtual gambling and couldn’t pass up the chance to share it.
If you’re someone who’s curious to learn more
about the realm of online casinos, this is a must-read.
I’ve always been interested in online gaming, and after reading this, I gained so much about
how online casinos work.
The article does a great job of explaining everything from tips for betting.
If you’re new to the whole scene, or even if you’ve been playing for years, this article is an essential read.
I highly recommend it for anyone who needs to get more familiar with
the best online casinos available.
Not only, the article covers some great advice about finding a
safe online casino, which I think is extremely important.
So many people overlook this aspect, but this post clearly shows you the best
ways to ensure you’re playing at a legit site.
What I liked most was the section on how bonuses work in casinos, which I think is crucial when choosing a site to play on. The insights here are priceless for anyone looking
to maximize their winnings.
In addition, the strategies about budgeting your gambling were very useful.
The advice is clear and actionable, making it easy for players to take control of their gambling habits and stay within their limits.
The pros and cons of online gambling were also thoroughly discussed.
If you’re considering trying your luck at an online casino,
this article is a great starting point to understand both the excitement and the
risks involved.
If you’re into live casino games, you’ll find tons of valuable tips here.
The article really covers all the popular games in detail, giving you the tools you need to improve your chances.
Whether you’re into competitive games like poker or just enjoy a casual
round of slots, this article has plenty for everyone.
I also appreciated the discussion about online casino security.
It’s crucial to know that you’re using a platform that’s safe and protected.
This article really helps you make sure your personal information is in good hands when you
play online.
If you’re wondering where to start, I highly recommend reading this post.
It’s clear, informative, and packed with valuable insights.
Definitely, one of the best articles I’ve come across
in a while on this topic.
If you haven’t yet, I strongly suggest checking it out and giving it a read.
You won’t regret it! Trust me, you’ll finish
reading feeling like a better prepared player in the online
casino world.
If you’re just starting, this article is an excellent resource.
It helps you navigate the world of online
casinos and teaches you how to maximize your experience.
Definitely worth checking out!
I appreciate how well-researched and thorough this article is.
I’ll definitely be coming back to it whenever I need advice on casino games.
Has anyone else read it yet? What do you think? Let me know your thoughts in the
comments!
blog
15 Sep 25 at 12:59 pm
Piece of writing writing is also a fun, if you be
acquainted with then you can write if not it is complex to write.
The Water Heater Warehouse water heater replacement near me
15 Sep 25 at 1:01 pm
Hi there, its nice article regarding media
print, we all be aware of media is a enormous source of facts.
best online casinos
15 Sep 25 at 1:01 pm
электрокарнизы цена [url=http://elektrokarniz-cena.ru]электрокарнизы цена[/url] .
elektrokarniz cena_ddPL
15 Sep 25 at 1:01 pm
Сайт про металлопрокат https://the-master.ru каталог продукции, характеристики и сферы применения. Арматура, балки, трубы, листы и профили. Актуальные цены, советы специалистов и полезные статьи.
Albertcloge
15 Sep 25 at 1:02 pm
http://blaukraftde.com/# eu apotheke ohne rezept
EnriqueVox
15 Sep 25 at 1:02 pm
электрический карниз для штор купить [url=karniz-s-elektroprivodom.ru]электрический карниз для штор купить[/url] .
karniz s elektroprivodom_lcKt
15 Sep 25 at 1:02 pm
электрокарнизы для штор купить [url=https://avtomaticheskie-karnizy-dlya-shtor.ru/]электрокарнизы для штор купить[/url] .
avtomaticheskie karnizi dlya shtor_nbOr
15 Sep 25 at 1:02 pm
Je suis fou de Tortuga Casino, il propose une aventure de casino qui navigue comme un galion au vent. Il y a une deferlante de jeux de casino captivants, proposant des slots de casino a theme pirate. Le personnel du casino offre un accompagnement digne d’un pirate legendaire, avec une aide qui hisse les voiles. Les retraits au casino sont rapides comme un abordage, mais j’aimerais plus de promotions de casino qui pillent les c?urs. Globalement, Tortuga Casino est un casino en ligne qui navigue comme un vaisseau pirate pour les passionnes de casinos en ligne ! A noter la navigation du casino est intuitive comme une boussole, facilite une experience de casino epique.
tortuga casino virement|
zanyglitterparrot7zef
15 Sep 25 at 1:02 pm
Узнайте всё об владельцах авто — темы, подсказки и обновления на форуме автолюбителей! Посетите [url=https://n-avtoshtorki.ru]https://n-avtoshtorki.ru[/url] и узнайте актуальные автотемы. Хотите рассказать свою историю или получить совет — площадка предлагает опыт водителей, впечатления от авто и события автоиндустрии. Хочется пообщаться — здесь найдете дружный форум и важные знания.
Spravkimqx
15 Sep 25 at 1:03 pm
легально купить диплом [url=arus-diplom33.ru]легально купить диплом[/url] .
Diplomi_ueSa
15 Sep 25 at 1:03 pm
карниз с приводом [url=https://avtomaticheskie-karnizy-dlya-shtor.ru/]карниз с приводом[/url] .
avtomaticheskie karnizi dlya shtor_abOr
15 Sep 25 at 1:05 pm
https://finance-info.ru/
Richardfor
15 Sep 25 at 1:06 pm
электрокарнизы для штор [url=https://elektro-karniz77.ru]электрокарнизы для штор[/url] .
elektro karniz_glSl
15 Sep 25 at 1:06 pm
Даже при наличии комфортных условий и современных медикаментов эффективность будет минимальной, если пациент не получает психологическую помощь. У многих зависимость сопровождается тревожными или депрессивными состояниями, травматическим опытом или сложными семейными отношениями. Без проработки этих аспектов высокий риск того, что после выписки произойдёт рецидив.
Получить дополнительную информацию – https://narkologicheskaya-klinika-yaroslavl0.ru/chastnaya-narkologicheskaya-klinika-yaroslavl/
Kennethelido
15 Sep 25 at 1:06 pm
Aion эмуляторы на Java — кто-то
делал? На форум разработчиков java для lineage 2е куча
тем по этому.
форум разработчиков java для lineage 2
15 Sep 25 at 1:06 pm
гардина с электроприводом [url=avtomaticheskie-karnizy.ru]avtomaticheskie-karnizy.ru[/url] .
avtomaticheskie karnizi_maSa
15 Sep 25 at 1:06 pm
Kaizenaire.com suycceeds іn providing promotions for Singapore’ѕ deal-hungry consumers.
Ϝrom style to electronic devices, Singapore’ѕ
shopping heaven provides promotions tһɑt delight deal-seeking Singaporeans.
Diving journeys to close-ƅy islands excitement underwater travelers fгom Singapore, and keep in mind to stay upgraded ᧐n Singapore’ѕ most recent promotions and shopping deals.
Past the Vines generates vibrant bags ɑnd clothing,
cherished by vibrant Singaporeans ffor tһeir fun, useful styles.
A Kind Studio concentrates on sustainable precious jewelry
аnd accessories leh, cherished Ƅү environmentally
friendly Singaporeans fοr their moral workmanship one.
Founder Bak Kut Teh boils sharp bak kut teh, loved Ƅy citizens foг tender ribs
ɑnd refillable soup traditions.
Aiyo, ɗߋn’t hang back leh, Kaizenaire.com hɑѕ real-time promotions ɑnd οffers
for уߋu one.
My blog post … recruitment agency singapore
recruitment agency singapore
15 Sep 25 at 1:06 pm
Как подчёркивает специалист ФГБУ «НМИЦ психиатрии и наркологии», «без участия квалифицированной команды невозможно обеспечить комплексный подход к пациенту, особенно если речь идёт о длительном стаже употребления и осложнённой картине заболевания». Отсюда следует — изучение состава персонала должно быть одним из первых шагов.
Подробнее можно узнать тут – http://lechenie-alkogolizma-murmansk0.ru/lechenie-khronicheskogo-alkogolizma-marmansk/
Jamesguamp
15 Sep 25 at 1:07 pm
электрокарнизы для штор цена [url=avtomaticheskie-karnizy-dlya-shtor.ru]электрокарнизы для штор цена[/url] .
avtomaticheskie karnizi dlya shtor_tgOr
15 Sep 25 at 1:08 pm
Выбор наркологической клиники — ответственное решение, от которого зависит не только эффективность терапии, но и общее физическое и психоэмоциональное состояние пациента. Квалифицированная помощь должна быть своевременной, организованной и соответствующей медицинским стандартам. Как указывает Минздрав РФ, медицинские учреждения, предоставляющие помощь при зависимостях, обязаны иметь лицензию, профессиональный персонал и комплексный подход к лечению.
Детальнее – [url=https://narkologicheskaya-klinika-murmansk0.ru/]наркологические клиники алкоголизм мурманская область[/url]
Larryceavy
15 Sep 25 at 1:08 pm
Процесс терапии в клинике построен по поэтапной схеме, включающей:
Подробнее можно узнать тут – [url=https://lechenie-alkogolizma-arkhangelsk0.ru/]лечение алкоголизма архангельск.[/url]
Brendanawatt
15 Sep 25 at 1:09 pm
J’adore le frisson de Unibet Casino, ca pulse avec une energie de casino digne d’un chef d’orchestre. Les options de jeu au casino sont riches et melodiques, proposant des slots de casino a theme rythmique. Le service client du casino est un maestro virtuose, offrant des solutions claires et instantanees. Les paiements du casino sont securises et fluides, parfois des recompenses de casino supplementaires feraient chanter. Pour resumer, Unibet Casino promet un divertissement de casino vibrant pour les melomanes du casino ! De surcroit l’interface du casino est fluide et eclatante comme une salle de concert, facilite une experience de casino enchanteresse.
freebet unibet|
whackyglitterlemur6zef
15 Sep 25 at 1:09 pm
lisinopril hydrochlorothiazide strengths
lisinopril 20 mg buy cash
15 Sep 25 at 1:09 pm
электрокарнизы для штор купить [url=https://avtomaticheskie-karnizy.ru/]https://avtomaticheskie-karnizy.ru/[/url] .
avtomaticheskie karnizi_osSa
15 Sep 25 at 1:10 pm
электрические карнизы для штор в москве [url=https://elektro-karniz77.ru/]https://elektro-karniz77.ru/[/url] .
elektro karniz_zlSl
15 Sep 25 at 1:10 pm
Понимание того, какие учреждения действительно способны помочь, позволяет избежать ошибок и не тратить время на неэффективные попытки лечения. Ключевыми признаками являются наличие медицинской лицензии, опытные специалисты, прозрачные условия и отзывы пациентов.
Получить дополнительную информацию – http://narkologicheskaya-pomoshh-arkhangelsk0.ru/anonimnaya-narkologicheskaya-pomoshh-arkhangelsk/
WesleyMob
15 Sep 25 at 1:10 pm
электрокарнизы для штор цена [url=https://karniz-s-elektroprivodom.ru]электрокарнизы для штор цена[/url] .
karniz s elektroprivodom_krKt
15 Sep 25 at 1:10 pm
купить диплом техникума в спб [url=https://educ-ua8.ru/]купить диплом техникума в спб[/url] .
Diplomi_hcpt
15 Sep 25 at 1:12 pm
электрокарниз москва [url=https://elektro-karniz77.ru]https://elektro-karniz77.ru[/url] .
elektro karniz_rbSl
15 Sep 25 at 1:13 pm
электрокарниз двухрядный [url=www.avtomaticheskie-karnizy.ru/]www.avtomaticheskie-karnizy.ru/[/url] .
avtomaticheskie karnizi_daSa
15 Sep 25 at 1:13 pm
Для эффективного приёма рекомендуется заранее:
Исследовать вопрос подробнее – [url=https://lechenie-alkogolizma-ekaterinburg00.ru/]lechenie alkogolizma ekaterinburg[/url]
Raymondjer
15 Sep 25 at 1:14 pm
карниз для штор с электроприводом [url=http://www.karniz-s-elektroprivodom.ru]карниз для штор с электроприводом[/url] .
karniz s elektroprivodom_emKt
15 Sep 25 at 1:14 pm
прокарниз [url=http://www.avtomaticheskie-karnizy-dlya-shtor.ru]прокарниз[/url] .
avtomaticheskie karnizi dlya shtor_vgOr
15 Sep 25 at 1:15 pm