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!
A lot of users worldwide are actively searching for reliable
ways to enjoy get Faphouse premium at zero cost
without having to spend money. If you also want to activate Faphouse premium without paying, there are now several legit ways available that provide direct premium access at no
charge.
free faphouse premium
18 Sep 25 at 8:56 pm
It’s awesome for me to have a site, which is good
designed for my knowledge. thanks admin
My blog post solar farms NZ
solar farms NZ
18 Sep 25 at 8:56 pm
https://xn--krken23-bn4c.com
Howardreomo
18 Sep 25 at 8:58 pm
Great post.
Massage Outcall Bangkok
18 Sep 25 at 8:58 pm
Привет всем!
Оцените комфорт виртуальной связи с нашими услугами. Постоянный виртуальный номер для смс – это практичное решение для общения и бизнеса. У нас вы можете купить виртуальный номер навсегда, чтобы обеспечить стабильность контактов. Наши предложения созданы для вашего удобства. Начните пользоваться преимуществами виртуальных номеров прямо сейчас.
Полная информация по ссылке – https://andyumra71603.arwebo.com/49830340/alles-over-het-49-nummer-een-complete-gids
купить номер телефона навсегда, виртуальный номер, купить виртуальный номер навсегда
купить виртуальный номер телефона, купить постоянный виртуальный номер, постоянный виртуальный номер
Удачи и комфорта в общении!
SimInjum
18 Sep 25 at 9:00 pm
Thanks for your marvelous posting! I actually enjoyed reading it,
you are a great author. I will make sure to bookmark your
blog and definitely will come back later in life.
I want to encourage you to ultimately continue your great posts, have a nice afternoon!
Feel free to visit my blog post – solar farms Auckland
solar farms Auckland
18 Sep 25 at 9:01 pm
Пенсия и ипотека онлайн: рассчитал, что пенсия покроет платёж по ипотеке полностью. новости военная служба
Brentagila
18 Sep 25 at 9:02 pm
I am curious to find out what blog platform you have been working with?
I’m having some small security issues with my latest website and I’d like to find something more safe.
Do you have any recommendations?
royalqq
18 Sep 25 at 9:02 pm
лучшие казино для игры Capymania Green
Eddiefen
18 Sep 25 at 9:02 pm
накрутка подписчиков тг живые без отписок
JohnnyPhido
18 Sep 25 at 9:02 pm
https://form.jotform.com/252514817972060
Timothytag
18 Sep 25 at 9:06 pm
микрозайм все [url=https://zaimy-15.ru]https://zaimy-15.ru[/url] .
zaimi_yvpn
18 Sep 25 at 9:10 pm
Асфальтирование – это многоэтапный процесс, требующий соблюдения технологических норм и использования специализированной техники. Качественно уложенный асфальт – это залог долговечности дорожного покрытия, его устойчивости к нагрузкам и неблагоприятным погодным условиям.
Подготовка основания: Этот этап – фундамент будущего покрытия. Сначала производится очистка территории от мусора, растительности и старого покрытия. Затем выполняется выравнивание основания с использованием геодезических инструментов. При необходимости, проводится укрепление грунта, например, с помощью геосетки. Важно обеспечить хороший дренаж, чтобы избежать скопления воды под асфальтом.
Укладка щебёночного основания: Щебень служит дренажным слоем и распределяет нагрузку от транспорта. Сначала укладывается крупная фракция, затем более мелкая. Каждый слой тщательно утрамбовывается катком. Толщина щебёночного основания зависит от предполагаемой нагрузки на дорогу.
Укладка асфальтобетонной смеси: Асфальтобетонная смесь доставляется на место укладки в специальных термоизолированных машинах. Смесь равномерно распределяется по основанию с помощью асфальтоукладчика. Важно соблюдать температурный режим укладки, чтобы обеспечить оптимальную плотность и прочность покрытия.
Уплотнение асфальта: Уплотнение асфальта производится с помощью катков различных типов. Сначала используются лёгкие катки для предварительного уплотнения, затем более тяжёлые – для окончательного. Уплотнение необходимо проводить до полного остывания смеси.
Контроль качества: На каждом этапе укладки асфальта необходимо проводить контроль качества. Проверяется ровность основания, толщина слоёв, температура смеси и степень уплотнения. Делитесь своим опытом и подрядчиками на [url=https://taksafonchik.borda.ru/?1-15-0-00000788-000-0-0-1756456590]укладка асфальта санкт петербург[/url]
StevenFog
18 Sep 25 at 9:10 pm
http://vitaledgepharma.com/# VitalEdgePharma
AntonioRaX
18 Sep 25 at 9:13 pm
Моды на игры для Android дают новые
функции, позволяя полностью изменить привычный игровой процесс.
Открывают премиум возможности, открывать скрытые элементы, и менять правила игры, в обычных играх
нельзя. Особенно востребованы где скачать моды для игр, которые позволяют
наслаждаться геймплеем в любом месте, без сети, удобно в дороге.
Бесконечные ресурсы, интегрированные
мод меню и специально подготовленные мод apk дают свободу действий, позволяя адаптировать игру под собственные предпочтения.
Использование таких модификаций не только повышает комфорт и динамику игры,
и делает процесс индивидуальным.
Для современного геймера
скачивание модов становится не просто технической процедурой, а способом расширить возможности и получить максимальное удовольствие от
любимых игр.
где скачать моды для игр
18 Sep 25 at 9:15 pm
Hello! I could have sworn I’ve been to this site
before but after reading through some of the post I realized it’s new to me.
Anyhow, I’m definitely happy I found it and I’ll be book-marking and checking back
often!
Kudos
18 Sep 25 at 9:16 pm
Вывод из запоя в Луганске рассматривается как последовательное медицинское вмешательство, направленное на снижение интоксикации, стабилизацию витальных показателей и профилактику острых осложнений. На фоне длительного употребления алкоголя у пациента формируются нарушения водно-электролитного баланса, колебания артериального давления, тахикардия, расстройства сна и повышенная тревожность. Коррекция этих состояний требует наблюдаемого формата помощи, применения стандартизированных протоколов и междисциплинарного взаимодействия.
Получить дополнительную информацию – http://vyvod-iz-zapoya-lugansk0.ru/vyvod-iz-zapoya-na-domu-lugansk/https://vyvod-iz-zapoya-lugansk0.ru
ThomasCrees
18 Sep 25 at 9:18 pm
Интернет-маркетинг https://internet-marketing1.ru SEO, контекстная реклама, SMM, email-рассылки и аналитика. Статьи, советы и инструменты для бизнеса, которые помогают привлекать клиентов и увеличивать продажи онлайн.
AaronsaiNI
18 Sep 25 at 9:19 pm
Такая помощь обеспечивает безопасность пациента и снижает риски осложнений, связанных с запойным состоянием.
Исследовать вопрос подробнее – http://vyvod-iz-zapoya-tver0.ru
Erwinerype
18 Sep 25 at 9:20 pm
Very nice post. I just stumbled upon your weblog and wanted to
say that I’ve really enjoyed surfing around your blog posts.
In any case I will be subscribing to your rss feed and I hope you write again soon!
SEO
18 Sep 25 at 9:23 pm
https://xn--krken23-bn4c.com
Howardreomo
18 Sep 25 at 9:23 pm
раздвижной карниз [url=www.razdvizhnoj-elektrokarniz.ru]www.razdvizhnoj-elektrokarniz.ru[/url] .
razdvijnoi elektrokarniz_ijei
18 Sep 25 at 9:24 pm
щетки
щетки
18 Sep 25 at 9:24 pm
I’ll immediately grab your rss as I can’t to find your e-mail
subscription hyperlink or newsletter service. Do you have any?
Kindly permit me understand in order that I may
subscribe. Thanks.
online casino echtgeld
18 Sep 25 at 9:32 pm
https://pubhtml5.com/homepage/ofigs
Timothytag
18 Sep 25 at 9:32 pm
https://clearmedshub.shop/# ClearMedsHub
AntonioRaX
18 Sep 25 at 9:33 pm
щетки
щетки
18 Sep 25 at 9:33 pm
Hi to every one, as I am actually eager of reading this blog’s post to be updated daily.
It includes good stuff.
Download The Globalization and Development Reader (Perspectives on Development and Global Change) (2nd Edition) Roberts PDF
18 Sep 25 at 9:36 pm
Cashpot Kegs Megaways играть в Казино Х
Davidfes
18 Sep 25 at 9:38 pm
Chest Hunter играть в Вавада
JoshuaStism
18 Sep 25 at 9:38 pm
займ всем [url=http://zaimy-15.ru/]http://zaimy-15.ru/[/url] .
zaimi_vwpn
18 Sep 25 at 9:41 pm
Поддержка мобильных устройств обеспечивает доступ к любимым развлечениям в любое время и в
любом месте.
7к казино скачать
18 Sep 25 at 9:42 pm
Квартира по НИС в 2025 — калькулятор помог выбрать вариант за 3,5 млн, накопления покрывают 60%. расчёт НИС онлайн
Brentagila
18 Sep 25 at 9:44 pm
Казино X слот Chilli Fiesta
BrandonLum
18 Sep 25 at 9:45 pm
J’adore a fond 7BitCasino, il offre une aventure pleine de sensations. Il y a une profusion de titres varies, incluant des slots de pointe. Le support est ultra-reactif et professionnel, repondant en un clin d’?il. Les retraits sont ultra-rapides, bien que davantage de recompenses seraient appreciees, comme des offres de cashback plus avantageuses. Pour conclure, 7BitCasino ne decoit jamais pour les adeptes de sensations fortes ! Ajoutons que le design est visuellement attrayant avec une touche vintage, facilite chaque session de jeu.
7bitcasino spiele|
criskis7zef
18 Sep 25 at 9:46 pm
Hey there! Do you know if they make any plugins to safeguard against hackers?
I’m kinda paranoid about losing everything I’ve worked hard on. Any recommendations?
Feel free to surf to my page … waste management systems
waste management systems
18 Sep 25 at 9:46 pm
https://clearmedshub.com/# ClearMedsHub
AntonioRaX
18 Sep 25 at 9:47 pm
Superb post however I was wanting to know if you could write a litte more on this topic?
I’d be very thankful if you could elaborate a little bit further.
Thanks!
Order Fentanyl Patches online
18 Sep 25 at 9:49 pm
Je trouve phenomenal DBosses, on ressent une vibe unique. Le catalogue est d’une diversite impressionnante, comprenant des jeux optimises pour les cryptos. Le service client est d’une classe exceptionnelle, offrant des solutions claires et rapides. Les gains arrivent en un eclair, cependant j’aimerais plus de promotions variees. Globalement, DBosses garantit un divertissement de haut niveau pour les passionnes de sensations fortes ! En plus la navigation est intuitive et rapide, ce qui rend chaque session encore plus exaltante.
dbosses casino review|
blazecrew2zef
18 Sep 25 at 9:49 pm
Je suis carrement scotche par Gamdom, c’est une plateforme qui envoie du lourd. Le catalogue de jeux est juste enorme, incluant des jeux de table qui en jettent. L’assistance est au top du top, repondant en mode eclair. Les retraits sont rapides comme un ninja, mais bon plus de tours gratos ca serait ouf. Pour resumer, Gamdom est un spot a ne pas louper pour ceux qui kiffent parier avec style ! A noter aussi le design est une bombe visuelle, facilite le delire total.
rain notifier gamdom|
fuzzypanda7zef
18 Sep 25 at 9:50 pm
What you posted was very logical. However, consider this, suppose you added a little content?
I mean, I don’t want to tell you how to run your website, but
suppose you added something that grabbed folk’s attention?
I mean PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
is a little plain. You ought to peek at Yahoo’s home page and watch how they create
news headlines to get people to click. You might add a video
or a related pic or two to get readers interested about what you’ve
written. In my opinion, it might make your blog a little livelier.
best online casinos
18 Sep 25 at 9:50 pm
Magnificent goods from you, man. I’ve understand your stuff previous to and you are just
too wonderful. I really like what you have acquired here,
really like what you’re saying and the way in which you say
it. You make it enjoyable and you still take care of to keep it smart.
I cant wait to read far more from you. This is actually a wonderful website.
Here is my website – sustainable waste management
sustainable waste management
18 Sep 25 at 9:54 pm
Интернет-маркетинг https://internet-marketing1.ru SEO, контекстная реклама, SMM, email-рассылки и аналитика. Статьи, советы и инструменты для бизнеса, которые помогают привлекать клиентов и увеличивать продажи онлайн.
AaronsaiNI
18 Sep 25 at 9:56 pm
https://www.brownbook.net/business/54257313/лирика-таблетки-купить-в-москве/
Timothytag
18 Sep 25 at 9:57 pm
https://xn--krken21-bn4c.com
Howardreomo
18 Sep 25 at 9:58 pm
vhq cocaine in prague buy cocaine in telegram
prague-drugs-81
18 Sep 25 at 9:59 pm
Интернет-маркетинг https://internet-marketing1.ru SEO, контекстная реклама, SMM, email-рассылки и аналитика. Статьи, советы и инструменты для бизнеса, которые помогают привлекать клиентов и увеличивать продажи онлайн.
AaronsaiNI
18 Sep 25 at 9:59 pm
займы россии [url=zaimy-14.ru]zaimy-14.ru[/url] .
zaimi_fySr
18 Sep 25 at 10:00 pm
I visited many sites however the audio quality for audio songs current at this web
page is in fact wonderful.
Look into my web-site :: source
source
18 Sep 25 at 10:00 pm
Интернет-маркетинг https://internet-marketing1.ru SEO, контекстная реклама, SMM, email-рассылки и аналитика. Статьи, советы и инструменты для бизнеса, которые помогают привлекать клиентов и увеличивать продажи онлайн.
AaronsaiNI
18 Sep 25 at 10:00 pm