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!
I am really pleased to glance at this web site posts which contains tons of
valuable data, thanks for providing these statistics.
derila pillow
31 Aug 25 at 3:25 am
Мы предлагаем документы университетов, расположенных в любом регионе РФ. Купить диплом о высшем образовании:
[url=http://hot9jajob.com/employer/ukrdiplom/]аттестат 10 11 класс с реестром купить[/url]
Diplomi_ybPn
31 Aug 25 at 3:29 am
купить диплом москва легально [url=http://octavia-club.ru/id/143121]купить диплом москва легально[/url] .
Priobresti diplom o visshem obrazovanii!_jmkt
31 Aug 25 at 3:34 am
I am not sure where you’re getting your information, but great topic.
I needs to spend some time learning more or understanding more.
Thanks for excellent information I was looking for this information for my mission.
Flow Trade AI
31 Aug 25 at 3:35 am
как купить диплом с занесением в реестр [url=www.arus-diplom31.ru]как купить диплом с занесением в реестр[/url] .
Diplomi_lbpl
31 Aug 25 at 3:36 am
https://1wbona.shop/# 1wbona
Alfredrew
31 Aug 25 at 3:36 am
It’s going to be end of mine day, but before finish I am reading this great piece of writing
to increase my know-how.
local basement water damage
31 Aug 25 at 3:37 am
сколько стоит купить аттестат за 11 класс [url=http://arus-diplom23.ru]сколько стоит купить аттестат за 11 класс[/url] .
Diplomi_gsol
31 Aug 25 at 3:41 am
Заказать диплом можно используя сайт компании. [url=http://igrosoft.getbb.ru/viewtopic.php?f=11&t=4965/]igrosoft.getbb.ru/viewtopic.php?f=11&t=4965[/url]
Sazrlen
31 Aug 25 at 3:42 am
Этап вывода из запоя
Выяснить больше – [url=https://vyvod-iz-zapoya-shchelkovo6.ru/]vyvod-iz-zapoya-na-domu[/url]
JarvisStove
31 Aug 25 at 3:45 am
https://www.betterplace.org/en/organisations/67037
Josephpef
31 Aug 25 at 3:47 am
[url=https://paks-tore.ru/]straightforward upkeep ideas[/url] that worked well with this guidance, making my home upkeep routine more consistent. i believe adding such suggestions to everyday routines can make upkeep far less stressful and much more rewarding. advice like this not only helps with current problems but also builds confidence for tackling new challenges in the future. This time I stayed and thought it adds value to the overall topic. — In longer discussions I usually skip, but thanks for the hands-on and plain guidance. many avoid residence fixes due to lack of confidence, but this post helps overcome that. i also found some
Alvingek
31 Aug 25 at 3:48 am
I’ve been browsing online greater than three hours lately, but I by no means discovered any
fascinating article like yours. It’s pretty value enough for me.
In my opinion, if all site owners and bloggers made just right content as you did, the
net will likely be a lot more useful than ever before.
water damage restoration near me
31 Aug 25 at 3:48 am
Капельницы, применяемые при выходе из запоя — это ключевым моментом в лечении алкоголизма, который нуждается в внимательном подходе. Вызов нарколога необходим для оценки здоровья пациента и назначения соответствующей терапии. Основные компоненты капельниц помогают detoxication, снижая симптомы запоя, такие как головная боль, тошнота и тревога. Несмотря на эффективность, существуют противопоказания: серьезные болезни сердца, почек и печени могут усложнить лечение. Риски терапии включают побочные эффекты, такие как аллергические реакции или обострение состояния. Поэтому безопасность процедуры должна быть приоритетом. Медицинская помощь включает не только вывод из запоя, но и реабилитацию, направленную на восстановление здоровья пациента и предотвращение рецидивов. Следует помнить, что каждый случай уникален, и лечение должно проводиться под контролем опытного нарколога.
vivodzapojtulaNeT
31 Aug 25 at 3:48 am
Мы можем предложить документы ВУЗов, которые расположены в любом регионе РФ. Заказать диплом ВУЗа:
[url=http://techfestcitp.com/read-blog/19172_kupit-attestat-11-klassov-cena.html/]купить аттестат 10 11 класс вечерней школы[/url]
Diplomi_pjPn
31 Aug 25 at 3:50 am
где купить аттестат за 11 класс в новосибирске [url=http://arus-diplom24.ru]где купить аттестат за 11 класс в новосибирске[/url] .
Diplomi_xmsa
31 Aug 25 at 3:54 am
рейтинг онлайн слотов
RichardKap
31 Aug 25 at 3:57 am
bonaslot situs bonus terbesar Indonesia: bonaslot link resmi mudah diakses – bonaslot jackpot harian jutaan rupiah
Ramonatowl
31 Aug 25 at 3:58 am
купить диплом ижевск с занесением в реестр [url=http://arus-diplom31.ru/]купить диплом ижевск с занесением в реестр[/url] .
Diplomi_wvpl
31 Aug 25 at 4:01 am
When I initially commented I clicked the “Notify me when new comments are added” checkbox
and now each time a comment is added I get several e-mails with the same comment.
Is there any way you can remove people from that service?
Thanks!
login loket88
31 Aug 25 at 4:06 am
Hello, i read your blog occasionally and i own a
similar one and i was just wondering if you get a lot of spam comments?
If so how do you stop it, any plugin or anything you can advise?
I get so much lately it’s driving me crazy so any
assistance is very much appreciated.
32WIN
31 Aug 25 at 4:07 am
https://form.jotform.com/252385557031053
Josephpef
31 Aug 25 at 4:09 am
Simply want to say your article is as astounding.
The clarity in your post is simply great and i can assume you are an expert on this subject.
Well with your permission let me to grab your feed to keep updated with forthcoming
post. Thanks a million and please continue the
enjoyable work.
סוכן בטים
31 Aug 25 at 4:11 am
диплом купить харьков цена [url=http://www.educ-ua1.ru]диплом купить харьков цена[/url] .
Diplomi_atei
31 Aug 25 at 4:12 am
аттестат за 11 класс 2003 купить [url=https://arus-diplom24.ru/]аттестат за 11 класс 2003 купить[/url] .
Diplomi_pmsa
31 Aug 25 at 4:16 am
В Самаре решение есть — наркологическая клиника. Здесь помогают людям выйти из запоя без страха и осуждения. Всё анонимно, грамотно и с заботой о каждом пациенте.
Подробнее тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara17.ru/]samara[/url]
Justingof
31 Aug 25 at 4:19 am
My partner and I stumbled over here from a different web address and thought I should check things out.
I like what I see so now i am following you. Look forward to looking into your web page for a second time.
iridium recycling
31 Aug 25 at 4:21 am
Самостоятельно выйти из запоя — почти невозможно. В Самаре врачи клиники проводят медикаментозный вывод из запоя с круглосуточным выездом. Доверяйте профессионалам.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara16.ru/]срочный вывод из запоя[/url]
Pablotug
31 Aug 25 at 4:22 am
купить диплом с проводкой моих [url=http://arus-diplom31.ru]купить диплом с проводкой моих[/url] .
Diplomi_zqpl
31 Aug 25 at 4:23 am
Your mode of explaining everything in this paragraph is actually fastidious,
all be capable of easily know it, Thanks a lot.
Feel free to visit my webpage dewispin
dewispin
31 Aug 25 at 4:27 am
Amazing! Its truly amazing piece of writing, I have got much clear idea about from this article.
dougelkinschoreography.com lừa đảo công an truy quét cấm người chơi tham gia
31 Aug 25 at 4:27 am
Самостоятельно выйти из запоя — почти невозможно. В Самаре врачи клиники проводят медикаментозный вывод из запоя с круглосуточным выездом. Доверяйте профессионалам.
Углубиться в тему – [url=https://vyvod-iz-zapoya-v-stacionare-samara15.ru/]вывод из запоя на дому недорого[/url]
Michaelamoma
31 Aug 25 at 4:28 am
I do consider all of the ideas you have introduced for your post.
They’re very convincing and can certainly work. Still, the
posts are too quick for beginners. Could you please extend
them a bit from next time? Thanks for the post.
my homepage pink salt trick
pink salt trick
31 Aug 25 at 4:29 am
диплом о среднем образовании купить легально [url=http://arus-diplom31.ru]http://arus-diplom31.ru[/url] .
Diplomi_gapl
31 Aug 25 at 4:31 am
https://form.jotform.com/252406677033052
Josephpef
31 Aug 25 at 4:31 am
Детокс-капельница на дому в Подольске от клиники «Частный Медик 24» — это быстрый способ вернуть здоровье после длительных возлияний. Мы подбираем индивидуальные составы инфузий, восстанавливаем работу печени, сердца и нервной системы. Вызвать нарколога можно круглосуточно, без записи и лишних формальностей.
Узнать больше – [url=https://kapelnica-ot-zapoya-podolsk13.ru/]капельница от запоя город. московская область[/url]
ZacharyBep
31 Aug 25 at 4:32 am
Liv Pure seems to be getting a lot of attention for its unique approach to supporting liver health and natural fat-burning.
I like that it focuses on cleansing and optimizing liver function, since
that’s such a key organ for metabolism and overall wellness.
It looks like a solid option for people who want a more natural way
to boost energy, digestion, and weight management.
Liv Pure
31 Aug 25 at 4:34 am
купить диплом ижевск с занесением в реестр [url=http://vidogs.forum24.ru/?1-15-0-00001609-000-0-0-1752571096]купить диплом ижевск с занесением в реестр[/url] .
Kypit diplom o visshem obrazovanii!_mekt
31 Aug 25 at 4:36 am
История и праздники в июле История фотографии: от первых снимков до цифровых изображений Как фотография изменила представление о мире.
Williammus
31 Aug 25 at 4:39 am
Мы готовы предложить документы институтов, расположенных на территории всей РФ. Купить диплом о высшем образовании:
[url=http://t98223u0.beget.tech/2025/07/09/diplom-s-proverkoy-podlinnosti-cherez-fis-frdo.html/]купить аттестаты за 11 с егэ[/url]
Diplomi_zlPn
31 Aug 25 at 4:40 am
купить аттестат за 11 класс 2000 года [url=www.arus-diplom24.ru]www.arus-diplom24.ru[/url] .
Diplomi_hrsa
31 Aug 25 at 4:40 am
Существуют различные методы и стратегии, которые применяются для устранения зависимостей. Каждый случай уникален, поэтому важно проводить глубокую диагностику и индивидуально разрабатывать план лечения. Мы понимаем, что борьба с зависимостью — это длительный процесс, требующий как медицинской, так и психологической поддержки.
Получить больше информации – [url=https://zavisim-alko.ru/]вывод из запоя с выездом[/url]
KennethGlolo
31 Aug 25 at 4:46 am
Мы можем предложить документы институтов, которые находятся на территории всей РФ. Заказать диплом любого ВУЗа:
[url=http://blog.nataraj.ru/~/Interest/Купитьдипломсзанесениемвреестр/]как можно купить аттестат за 11 класс[/url]
Diplomi_hzPn
31 Aug 25 at 4:48 am
Thanks for ones marvelous posting! I certainly enjoyed reading it,
you can be a great author. I will make sure to bookmark your blog and definitely will come back
sometime soon. I want to encourage that you continue your great posts, have a
nice day!
Also visit my web page :: تولیدی کاپشن
تولیدی کاپشن
31 Aug 25 at 4:52 am
https://www.grepmed.com/ahteifah
Josephpef
31 Aug 25 at 4:53 am
высшее образование купить диплом с занесением в реестр [url=https://arus-diplom31.ru]высшее образование купить диплом с занесением в реестр[/url] .
Diplomi_jcpl
31 Aug 25 at 4:59 am
Straight to the point — I appreciate that!
http://littlebournebenefice.org.uk/littlebourne-benefice-hosts-a-memorable-community-gala/
31 Aug 25 at 4:59 am
купить аттестат 11 классов с занесением в реестр [url=www.arus-diplom24.ru]www.arus-diplom24.ru[/url] .
Diplomi_wwsa
31 Aug 25 at 5:02 am
купить диплом с занесением в реестр украина [url=rosseia.forumex.ru/viewtopic.php?f=3&t=4261]купить диплом с занесением в реестр украина[/url] .
Bistro zakazat diplom instityta!_lskt
31 Aug 25 at 5:05 am
купить аттестат 11 классов в тольятти [url=https://www.arus-diplom24.ru]купить аттестат 11 классов в тольятти[/url] .
Diplomi_qqsa
31 Aug 25 at 5:09 am