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!
For latest information you have to pay a visit internet and on world-wide-web I
found this web site as a finest website for most recent updates.
vovan casino официальный сайт
8 Oct 25 at 1:57 pm
вывод из запоя цены москва [url=www.vyvod-iz-zapoya-9.ru]www.vyvod-iz-zapoya-9.ru[/url] .
vivod iz zapoya_nqEl
8 Oct 25 at 1:58 pm
Informative article, totally what I needed.
http://www.xsmoli.com/
8 Oct 25 at 1:58 pm
Мы как производитель — отечественный разработчик, которая уже более десяти лет занимается [url=https://18ps.ru/about/stati/6608/]проекты по переработке пластика[/url] и изготовлением оборудования полного цикла. Проектируем, производим и тестируем линии, дробилки, смесители и пресс-формы, которые превращают пластиковые отходы в новые полезные материалы. Сотрудничаем с клиентами по всей стране, помогаем клиентам начинать устойчивый бизнес на вторсырье и выйти на экологичный рынок с разумным бюджетом.
Вся техника выпускается на нашем заводе, проходит испытания и запускается без длительной настройки. Мы контролируем процесс от начала до запуска: помогаем выбрать комплектацию, даём практические инструкции и оказываем технологическую поддержку. При необходимости можно [url=https://18ps.ru/]производство полимерпесчаных изделий производители оборудования[/url] с учётом особенностей проекта — от малого цеха до промышленного завода.
Мы ценим надёжность, прозрачные условия и долгосрочные отношения. Поэтому клиенты ценят нас за готовые решения, а надёжный пакет услуг и техническую поддержку на всех этапах работы.
Leronzacop
8 Oct 25 at 2:02 pm
online pharmacy Prednisone fast delivery: Prednisone tablets online USA – Prednisone tablets online USA
Morrisluh
8 Oct 25 at 2:03 pm
Yes! Finally something about family physician Vaughan.
allergy specialist Vaughan
8 Oct 25 at 2:05 pm
Госпитализация в стационар помогает быстрее и надежнее справиться с последствиями запоя.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-stacionare21.ru/]вывод из запоя в стационаре анонимно[/url]
CharlesElage
8 Oct 25 at 2:06 pm
new online canadian casino, 888 casino nz and casino frenzy 250 free spins,
or united statesn casino guide roulette
Take a look at my homepage :: probability of winning craps
game – Morgan –
Morgan
8 Oct 25 at 2:06 pm
https://t.me/kupinos_kz Снюс Алматы – это поисковый запрос, указывающий на интерес к приобретению снюса в городе Алматы, Казахстан. Важно отметить, что законодательство Казахстана регулирует продажу и употребление табачных изделий, и, возможно, существуют ограничения или требования к реализации снюса. Потребителям необходимо убедиться в законности покупки и употребления этой продукции в Алматы, а также осознавать риски для здоровья, связанные с употреблением никотина. Рекомендуется проконсультироваться со специалистами, чтобы получить объективную информацию о влиянии снюса на организм.
Charlesjom
8 Oct 25 at 2:06 pm
[url=https://mad1994.top ]Детское порно[/url]
Stephenneift
8 Oct 25 at 2:07 pm
закодироваться в москве [url=http://narkologicheskaya-klinika-20.ru]http://narkologicheskaya-klinika-20.ru[/url] .
narkologicheskaya klinika _amPr
8 Oct 25 at 2:07 pm
новости футбола [url=www.sportivnye-novosti-1.ru]новости футбола[/url] .
sportivnie novosti_sfpi
8 Oct 25 at 2:09 pm
Prednisone tablets online USA [url=http://predniwellonline.com/#]online pharmacy Prednisone fast delivery[/url] Prednisone tablets online USA
Michaelriz
8 Oct 25 at 2:10 pm
Joined $MTAUR rush—prizes await. ICO’s tokenomics sound. Mazes challenging.
mtaur coin
WilliamPargy
8 Oct 25 at 2:11 pm
купить диплом в йошкар-оле [url=https://www.rudik-diplom5.ru]купить диплом в йошкар-оле[/url] .
Diplomi_irma
8 Oct 25 at 2:11 pm
купить диплом медсестры [url=http://rudik-diplom1.ru]купить диплом медсестры[/url] .
Diplomi_erer
8 Oct 25 at 2:12 pm
http://neurocaredirect.com/# gabapentin capsules for nerve pain
RobertHixeD
8 Oct 25 at 2:12 pm
Oh my goodness! Impressive article dude! Many thanks, However I am having difficulties
with your RSS. I don’t understand the reason why I cannot join it.
Is there anybody else getting identical RSS issues?
Anyone who knows the solution will you kindly respond?
Thanks!!
crypto blackmail scam
8 Oct 25 at 2:16 pm
高級 ラブドール“The researchers concluded that femcels share some beliefs with radical feminists,particularly pertaining to patriarchy,
ラブドール
8 Oct 25 at 2:17 pm
новости киберспорта [url=https://www.sportivnye-novosti-1.ru]новости киберспорта[/url] .
sportivnie novosti_qqpi
8 Oct 25 at 2:19 pm
These social-media posts can help to spread knowledge to people who wouldn’t have gotten the chance otherwise.リアル ドールIt also normalizes the therapy process.
ラブドール
8 Oct 25 at 2:21 pm
kruisefest – You’ve captured the festival spirit well online.
Beulah Zeimetz
8 Oct 25 at 2:21 pm
I am truly happy to read this blog posts which carries plenty of useful data, thanks for providing such data.
CanQubit Review
8 Oct 25 at 2:22 pm
Greetings! Very useful advice in this particular post! It is the little changes which will
make the most important changes. Many thanks for sharing!
casino utan svensk licens snabba uttag
8 Oct 25 at 2:25 pm
создать карточку товара на wildberries с помощью нейросети Обложки маркетплейс – это визуальные элементы, представляющие товары на страницах маркетплейсов, таких как Wildberries, Ozon и другие. Они играют ключевую роль в привлечении внимания потенциальных покупателей и формировании первого впечатления о товаре. Обложки должны быть привлекательными, информативными, соответствовать требованиям маркетплейса и отражать суть предлагаемого продукта. Важно использовать качественные изображения, грамотно расположенные элементы дизайна и учитывать психологию потребителей при создании обложек для маркетплейсов.
JeromeThatt
8 Oct 25 at 2:26 pm
Nice blog here! Also your website lots up
very fast! What web host are you using? Can I get your associate hyperlink for your host?
I wish my site loaded up as quickly as yours lol
Solid Max
8 Oct 25 at 2:26 pm
linebet app apk download
linebet app
8 Oct 25 at 2:28 pm
1win futbol mərcləri [url=https://www.1win5001.com]https://www.1win5001.com[/url]
1win_fhEt
8 Oct 25 at 2:30 pm
What’s up to all, how is all, I think every one is getting more
from this web page, and your views are good in support of new users.
Immutable Azopt
8 Oct 25 at 2:33 pm
I savor, cause I found exactly what I used to be
taking a look for. You have ended my 4 day lengthy hunt!
God Bless you man. Have a great day. Bye
Where to order dmt vape pen online
8 Oct 25 at 2:34 pm
[url=https://casinomad.top/registracia
]Детское порно[/url]
BrianWer
8 Oct 25 at 2:35 pm
Escort service Dubai
LarryOrism
8 Oct 25 at 2:36 pm
What’s up everyone, it’s my first pay a visit at this site, and piece of writing is truly fruitful designed for me,
keep up posting these articles or reviews.
PestonoxPro TEST
8 Oct 25 at 2:37 pm
спорт новости [url=https://sportivnye-novosti-1.ru/]спорт новости[/url] .
sportivnie novosti_gqpi
8 Oct 25 at 2:38 pm
прогнозы футбола точные на сегодня [url=https://kompyuternye-prognozy-na-futbol23.ru]https://kompyuternye-prognozy-na-futbol23.ru[/url] .
komputernie prognozi na fytbol_hlPi
8 Oct 25 at 2:38 pm
Hello there! This post couldn’t be written any better! Looking through this article reminds me of my previous
roommate! He always kept talking about this.
I’ll forward this article to him. Fairly certain he’ll have a great read.
I appreciate you for sharing!
no prescription lorazepam
8 Oct 25 at 2:38 pm
When someone writes an piece of writing he/she keeps the image of a user in his/her brain that how a user can understand it.
Therefore that’s why this piece of writing is great.
Thanks!
Hydratačná maska
8 Oct 25 at 2:38 pm
нарколог на дом вывод из запоя москва [url=www.vyvod-iz-zapoya-9.ru]www.vyvod-iz-zapoya-9.ru[/url] .
vivod iz zapoya_vhEl
8 Oct 25 at 2:39 pm
promo code linebet
linebet kenya
8 Oct 25 at 2:40 pm
As the admin of this website is working, no question very soon it
will be famous, due to its quality contents.
Best Escort Agency in Jaipur
8 Oct 25 at 2:40 pm
Very soon this web page will be famous among all blogging viewers, due to it’s good content
독학기숙학원
8 Oct 25 at 2:40 pm
футбол завтра прогнозы на матчи [url=https://kompyuternye-prognozy-na-futbol23.ru/]https://kompyuternye-prognozy-na-futbol23.ru/[/url] .
komputernie prognozi na fytbol_toPi
8 Oct 25 at 2:43 pm
новости футбольных клубов [url=sportivnye-novosti-1.ru]sportivnye-novosti-1.ru[/url] .
sportivnie novosti_pypi
8 Oct 25 at 2:43 pm
вывод из запоя на дому в москве [url=https://vyvod-iz-zapoya-9.ru/]https://vyvod-iz-zapoya-9.ru/[/url] .
vivod iz zapoya_ryEl
8 Oct 25 at 2:44 pm
консультация психиатра
psychiatr-moskva008.ru
стационарное психиатрическое лечение
psihiatrmskNeT
8 Oct 25 at 2:44 pm
OMT’s documented sessions аllow trainees review motivating explanations anytime, growing tһeir
love f᧐r mathematics and fueling tһeir
ambition for examination accomplishments.
Broaden your horizons with OMT’ѕ upcoming brand-new physical area opening in Ⴝeptember
2025, ᥙsing muhch more opportunities fοr hands-on math expedition.
Ꮃith math integrated perfectly іnto Singapore’s classroom
settings tօ benefit both instructors ɑnd students,
dedicated math tuition enhances tһese gains by offering tailored support fоr sustained achievement.
primary school tuition іs impⲟrtant f᧐r developing strength versus PSLE’ѕ difficult concerns, suϲһ as those
on probability ɑnd basic stats.
Building self-assurance throuցh regular tuition support іs important,
as O Levels can be demanding, and confident pupils execute Ƅetter under stress.
Tuition incorporates pure аnd usеd mathematics perfectly, preparing trainees
fоr thee interdisciplinary nature οf A Level troubles.
OMT sticks ᧐ut with its proprietary mathematics curriculum, tһoroughly created to match the
Singapore MOE syllabus Ƅy filling in conceptual gaps tһat basic school lessons maү forget.
The sүstem’ѕ resources aгe updated regularly օne, maintaining yоu aligned wіth most
current syllabus fօr grade boosts.
Math tuition offeгs targeted exercise ԝith ρast examination papers, acquainting students ᴡith
concern patterns ѕeen in Singapore’s national evaluations.
mү website math tuition primary school
math tuition primary school
8 Oct 25 at 2:45 pm
точные ставки на спорт футбол [url=http://kompyuternye-prognozy-na-futbol23.ru/]http://kompyuternye-prognozy-na-futbol23.ru/[/url] .
komputernie prognozi na fytbol_mrPi
8 Oct 25 at 2:46 pm
анонимный. вывод. из. запоя. москва. [url=https://vyvod-iz-zapoya-9.ru]https://vyvod-iz-zapoya-9.ru[/url] .
vivod iz zapoya_dsEl
8 Oct 25 at 2:47 pm
детокс на дому [url=http://www.narkolog-na-dom-1.ru]http://www.narkolog-na-dom-1.ru[/url] .
narkolog na dom_exkt
8 Oct 25 at 2:47 pm
[url=https://gracie.digital/]диджитал агентство по созданию сайтов[/url]
JamesClazy
8 Oct 25 at 2:48 pm