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!
Looking for second-hand? best thrift stores near me We have collected the best stores with clothes, shoes and accessories. Large selection, unique finds, brands at low prices. Convenient catalog and up-to-date contacts.
second hand-177
6 Sep 25 at 2:41 am
Stunning quest there. What occurred after? Take care!
Online YT Video Downloader
6 Sep 25 at 2:41 am
Your way of describing the whole thing in this piece of writing is
genuinely nice, all be able to easily be aware of it, Thanks a lot.
شهریه خودگردان دانشگاه آزاد پرستاری ۱۴۰۴
6 Sep 25 at 2:44 am
Situs Togel Toto 4D [url=https://linklist.bio/inatogelbrand#]Situs Togel Toto 4D[/url] inatogel
CharlesJam
6 Sep 25 at 2:44 am
Arabian Wins
Georgererry
6 Sep 25 at 2:46 am
Je kiffe grave Amon Casino, ca balance une vibe de jeu completement folle. Il y a une avalanche de jeux de casino varies, proposant des sessions de casino en direct qui dechirent. Le support du casino est dispo 24/7, offrant des solutions claires et instantanees. Les transactions du casino sont simples comme un jeu d’enfant, de temps en temps des bonus de casino plus reguliers ca serait top. En bref, Amon Casino est un casino en ligne qui cartonne grave pour les fans de casinos en ligne ! De surcroit le site du casino est une tuerie graphique, donne envie de replonger dans le casino non-stop.
bonus amon casino|
flickergoose3zef
6 Sep 25 at 2:48 am
В Химках вывести человека из запоя с выездом на дом реально — специалисты Stop Alko работают круглосуточно, оказывая профессиональную поддержку.
Детальнее – [url=https://vyvod-iz-zapoya-himki13.ru/]анонимный вывод из запоя подольск[/url]
Joshuachisa
6 Sep 25 at 2:52 am
Je suis accro a Celsius Casino, ca degage une ambiance de jeu torride. La selection du casino est une explosion de plaisirs, proposant des slots de casino a theme volcanique. L’assistance du casino est chaleureuse et efficace, joignable par chat ou email. Les gains du casino arrivent a une vitesse torride, quand meme des bonus de casino plus frequents seraient torrides. Dans l’ensemble, Celsius Casino promet un divertissement de casino brulant pour les explorateurs du casino ! Bonus l’interface du casino est fluide et eclatante comme une flamme, facilite une experience de casino torride.
celsius casino|
zestycrow4zef
6 Sep 25 at 2:52 am
https://say.la/read-blog/131223
Jeffreyzef
6 Sep 25 at 2:52 am
Вывод из запоя в «Сибирском Докторе» происходит в несколько взаимосвязанных этапов:
Получить больше информации – [url=https://kachestvo-vyvod-iz-zapoya.ru/]наркологический вывод из запоя новосибирск[/url]
Jamesfitty
6 Sep 25 at 2:52 am
what is yoga
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
what is yoga
6 Sep 25 at 2:53 am
экстренный вывод из запоя череповец
vivod-iz-zapoya-cherepovec010.ru
экстренный вывод из запоя череповец
vivodcherepovecNeT
6 Sep 25 at 2:54 am
диплом с реестром купить [url=educ-ua13.ru]диплом с реестром купить[/url] .
Diplomi_tipn
6 Sep 25 at 2:55 am
узнать провайдера по адресу новосибирск
inernetvkvartiru-novosibirsk006.ru
подключить интернет
internetelini
6 Sep 25 at 2:56 am
The other day, while I was at work, my sister stole my
iPad and tested to see if it can survive a 40 foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views.
I know this is completely off topic but I had to share it with someone!
esta application
6 Sep 25 at 2:58 am
https://www.te-in.ru/arenda-dizel-generatorov.html/
Rolandmow
6 Sep 25 at 3:04 am
Greate post. Keep writing such kind of info on your site. Im really impressed by it.
Hello there, You have done an incredible job.
I will definitely digg it and in my opinion suggest to my friends.
I’m confident they’ll be benefited from this website.
dewascatter
6 Sep 25 at 3:07 am
dark web sites nexus darknet site darkmarket 2025 [url=https://darkmarketsdirectory.com/ ]dark web markets [/url]
BrianWeX
6 Sep 25 at 3:10 am
nexus dark darknet markets onion address bitcoin dark web [url=https://darknetmarketstore.com/ ]darknet drugs [/url]
Jamespem
6 Sep 25 at 3:11 am
Good day! This post couldn’t be written any better!
Reading this post reminds me of my old room mate!
He always kept chatting about this. I will forward this page to
him. Fairly certain he will have a good read. Thanks for sharing!
Also visit my blog; top real estate coach
top real estate coach
6 Sep 25 at 3:12 am
darkmarket 2025 dark market list nexus darknet access [url=https://darknetmarketgate.com/ ]nexus darknet [/url]
DwayneAricE
6 Sep 25 at 3:13 am
8628
youtubemfd
6 Sep 25 at 3:13 am
It’s actually a cool and useful piece of info. I’m glad that you shared this helpful info with us.
Please stay us informed like this. Thank you for sharing.
my blog post – top real estate coach
top real estate coach
6 Sep 25 at 3:14 am
https://community.wongcw.com/blogs/1143268/%D0%A1%D0%BB%D0%BE%D0%B1%D0%BE%D0%B4%D1%81%D0%BA%D0%BE%D0%B9-%D0%BA%D1%83%D0%BF%D0%B8%D1%82%D1%8C-%D0%91%D0%BE%D1%88%D0%BA%D0%B8-%D0%9C%D0%B0%D1%80%D0%B8%D1%85%D1%83%D0%B0%D0%BD%D1%83-%D0%93%D0%B0%D1%88%D0%B8%D1%88
Jeffreyzef
6 Sep 25 at 3:15 am
BARs and 7s играть в леонбетс
Jefferybig
6 Sep 25 at 3:15 am
https://linkr.bio/betawi777# betawi77
Josephagody
6 Sep 25 at 3:15 am
Um ein Video herunterzuladen, kopiert Ihr
die URL aus dem Browser, klickt im Anschluss auf “URL
einfügen” und wählt das Ausgabeformat, die Qualität des Videos sowie
den gewünschten Speicherort aus.
video downloader youtube
6 Sep 25 at 3:16 am
I loved as much as you will receive carried out right here.
The sketch is attractive, your authored subject matter stylish.
nonetheless, you command get got an edginess over that you wish be delivering the
following. unwell unquestionably come further formerly again as exactly the same nearly very often inside case you shield this hike.
Casino Bonuses
6 Sep 25 at 3:17 am
Hi there every one, here every one is sharing
such know-how, therefore it’s fastidious to read this webpage, and I used to visit this webpage every day.
강남룸싸롱
6 Sep 25 at 3:18 am
Looking for second-hand? thrift store store near me We have collected the best stores with clothes, shoes and accessories. Large selection, unique finds, brands at low prices. Convenient catalog and up-to-date contacts.
second hand-983
6 Sep 25 at 3:21 am
как зайти на blacksprut blacksprut, блэкспрут, black sprut, блэк спрут, blacksprut вход, блэкспрут ссылка, blacksprut ссылка, blacksprut onion, блэкспрут сайт, blacksprut вход, блэкспрут онион, блэкспрут дакрнет, blacksprut darknet, blacksprut сайт, блэкспрут зеркало, blacksprut зеркало, black sprout, blacksprut com зеркало, блэкспрут не работает, blacksprut зеркала, как зайти на blacksprutd
RichardPep
6 Sep 25 at 3:22 am
Je suis emballe par DBosses, ca donne un frisson inegale. La gamme est tout simplement epoustouflante, offrant des machines a sous innovantes. L’assistance est efficace et chaleureuse, repondant en un instant. Les transactions sont simples et efficaces, parfois plus de tours gratuits seraient top. Dans l’ensemble, DBosses garantit un divertissement de haut niveau pour les passionnes de sensations fortes ! Ajoutons que la navigation est intuitive et rapide, ce qui rend chaque session encore plus exaltante.
dbosses casino|
blazecrew2zef
6 Sep 25 at 3:27 am
2120
youtubegil
6 Sep 25 at 3:28 am
Je suis totalement enflamme par Celsius Casino, ca degage une ambiance de jeu torride. Il y a un torrent de jeux de casino captivants, offrant des sessions de casino en direct qui crepitent. Le support du casino est disponible 24/7, assurant un support de casino immediat et flamboyant. Les transactions du casino sont simples comme une etincelle, par moments les offres du casino pourraient etre plus genereuses. Au final, Celsius Casino est une pepite pour les fans de casino pour les explorateurs du casino ! Par ailleurs la plateforme du casino brille par son style flamboyant, amplifie l’immersion totale dans le casino.
celsius casino bonus|
zestycrow4zef
6 Sep 25 at 3:29 am
Команда клиники «Новый шанс» состоит из опытных специалистов-наркологов, которые имеют многолетнюю практику работы с пациентами, находящимися в зависимости, и регулярно совершенствуют свои знания.
Получить дополнительную информацию – [url=https://tajno-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-cena-v-rostove-na-donu.ru/]вывод из запоя вызов в ростове-на-дону[/url]
Rodneytex
6 Sep 25 at 3:37 am
Thank you, I have just been looking for info about this topic for ages and yours is the greatest I’ve discovered so far.
However, what about the conclusion? Are you certain concerning the source?
سامانه راهنمای انتخاب رشته مجازی
6 Sep 25 at 3:37 am
https://yamap.com/users/4795525
Jeffreyzef
6 Sep 25 at 3:38 am
Highly energetic blog, I enjoyed that a lot.
Will there be a part 2?
xnxx so
6 Sep 25 at 3:39 am
Нужен удобный вариант оформить медсправку удалённо? [url=https://space-group-med.ru]https://space-group-med.ru[/url] На сайте Space Group Med есть возможность оформить широкий спектр справок — от документа 001-ГСУ, документа 082/у, до справок об освобождении от физической нагрузки, справок из ПНД/ОД и КЭК-заключений. Всё это можно получить удалённо с курьерской доставкой в Москве и СПб — без хлопот, быстро и законно. Все подробности на сайте — справка через интернет, медсправка курьером, справка за 1 день.
Spravkigxr
6 Sep 25 at 3:42 am
https://linklist.bio/kratonbet777# kratonbet link
Josephagody
6 Sep 25 at 3:43 am
Looking for second-hand? second hand stores near me We have collected the best stores with clothes, shoes and accessories. Large selection, unique finds, brands at low prices. Convenient catalog and up-to-date contacts.
second hand-971
6 Sep 25 at 3:44 am
https://ihrchq.org/blog/pgs/code-promo-melbet_bonus-sportifs-et-casino.html
Howardmic
6 Sep 25 at 3:46 am
blacksprut вход blacksprut, блэкспрут, black sprut, блэк спрут, blacksprut вход, блэкспрут ссылка, blacksprut ссылка, blacksprut onion, блэкспрут сайт, blacksprut вход, блэкспрут онион, блэкспрут дакрнет, blacksprut darknet, blacksprut сайт, блэкспрут зеркало, blacksprut зеркало, black sprout, blacksprut com зеркало, блэкспрут не работает, blacksprut зеркала, как зайти на blacksprutd
RichardPep
6 Sep 25 at 3:49 am
nexus shop darknet markets 2025 darknet markets [url=https://darknetmarketsgate.com/ ]darkmarket url [/url]
Donaldfup
6 Sep 25 at 3:49 am
dark market url nexus shop url nexus darknet access [url=https://darknetmarketgate.com/ ]dark markets 2025 [/url]
DwayneAricE
6 Sep 25 at 3:51 am
Казино X слот Aztec Magic Megaways
JamesSog
6 Sep 25 at 3:52 am
дизель генератор для торгового центра
Rolandmow
6 Sep 25 at 3:54 am
https://www.bnbaccess.eu/art/code_promo-1win-bonus_de_500.html
Harryson
6 Sep 25 at 3:59 am
https://www.grepmed.com/noyycugede
Jeffreyzef
6 Sep 25 at 4:01 am
Creating Links Via Web 2 . 0 And Web Directory Submission link (Sean)
Sean
6 Sep 25 at 4:01 am