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=rudik-diplom5.ru]купить свидетельство о рождении ссср[/url] .
Diplomi_fmma
3 Oct 25 at 12:07 pm
Продолжительное употребление алкоголя наносит сильный удар по организму и психике человека. Если запой длится более двух дней, состояние резко ухудшается, и самостоятельный выход может привести к серьезным последствиям. Обязательно следует вызывать врача в следующих случаях:
Подробнее можно узнать тут – https://vyvod-iz-zapoya-krasnodar0.ru/vyvod-iz-zapoya-kruglosutochno-krasnodar
Stevevab
3 Oct 25 at 12:07 pm
Компания Кухни в Дом помогла нам выбрать кухню для новой квартиры. Проект был разработан быстро, а сборка выполнена идеально. Отличный сервис – https://kuhni-v-dom.ru/
Eugeniostync
3 Oct 25 at 12:08 pm
Наша наркологическая клиника предоставляет круглосуточную помощь, использует только сертифицированные медикаменты и строго соблюдает полную конфиденциальность лечения.
Детальнее – https://kapelnica-ot-zapoya-sochi0.ru/kapelnicza-ot-zapoya-czena-sochi/
Wilfredoxype
3 Oct 25 at 12:09 pm
купить диплом с реестром о высшем образовании [url=frei-diplom6.ru]купить диплом с реестром о высшем образовании[/url] .
Diplomi_mmOl
3 Oct 25 at 12:09 pm
Whoa! This blog looks exactly like my old one! It’s on a totally
different topic but it has pretty much the same page layout
and design. Wonderful choice of colors!
my web page Recent announcement
Recent announcement
3 Oct 25 at 12:09 pm
This info is worth everyone’s attention. How can I find out more?
seriöses online casino deutschland
3 Oct 25 at 12:10 pm
купить свидетельство о рождении [url=www.rudik-diplom4.ru/]купить свидетельство о рождении[/url] .
Diplomi_mkOr
3 Oct 25 at 12:10 pm
Чем раньше нарколог окажет помощь, тем выше шансы избежать осложнений и восстановиться без последствий для здоровья.
Получить дополнительные сведения – [url=https://narcolog-na-dom-sochi0.ru/]vyzov-narkologa-na-dom sochi[/url]
Duaneopits
3 Oct 25 at 12:10 pm
При возникновении споров и
для эффективной защиты законных
требований необходимо точно знать, когда стала действовать норма права.
https://white-glass.com/beste-online-krypto-casinos-aufladungen-und-60/
3 Oct 25 at 12:12 pm
just click the next document
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
just click the next document
3 Oct 25 at 12:13 pm
купить диплом в артеме [url=http://rudik-diplom15.ru]http://rudik-diplom15.ru[/url] .
Diplomi_haPi
3 Oct 25 at 12:14 pm
https://bibikey.ru
Peterrig
3 Oct 25 at 12:15 pm
новости олимпиады [url=https://novosti-sporta-17.ru/]novosti-sporta-17.ru[/url] .
novosti sporta_goOi
3 Oct 25 at 12:15 pm
прогнозы на спорт на завтра [url=https://prognozy-na-sport-12.ru/]прогнозы на спорт на завтра[/url] .
prognozi na sport_qtMn
3 Oct 25 at 12:17 pm
Thanks for your marvelous posting! I genuinely
enjoyed reading it, you happen to be a great author.
I will remember to bookmark your blog and will often come back from now
on. I want to encourage yourself to continue your great posts,
have a nice day!
Highmark Bitspire
3 Oct 25 at 12:18 pm
After I initially left a comment I seem to have clicked on the -Notify me when new comments are added- checkbox and now each time a comment is added I receive four
emails with the exact same comment. There has to be a way you are able
to remove me from that service? Cheers!
uk online casino
3 Oct 25 at 12:18 pm
https://www.wildberries.ru/catalog/514992745/detail.aspx
Kevinsaush
3 Oct 25 at 12:19 pm
The Oktoberfest beer festival in Munich will remain shut on Wednesday until at least 5 pm (1500 GMT) after police said they discovered explosives in a residential building in the north of the city that caught fire and left one person dead.
[url=https://kra37с-cc.ru]kra39 cc[/url]
As part of a major operation that police earlier said posed no danger to the public, special forces were investigating an area in the north of Munich where Bild newspaper and multiple other reports said shots and explosions had been heard.
[url=https://kra39с-cc.ru]kra38 cc[/url]
Police said the residential building had been deliberately set on fire in a family dispute and one person who was found there had died and another was missing, but not believed to be in danger.
[url=https://kra38a-cc.ru]kra41 cc[/url]
Special forces had to be brought in to defuse booby traps found in the building, according to police.
“We are currently investigating all possibilities. Possible connections to other locations in Munich are being examined, including the Theresienwiese (where the Oktoberfest is located),” said Munich police on the WhatsApp messaging service.
“For this reason, the opening of the festival grounds has been delayed,” police added.
kra38
https://kra38с-cc.ru
Rodneynen
3 Oct 25 at 12:20 pm
купить диплом с занесением в реестр в нижнем тагиле [url=https://frei-diplom6.ru/]купить диплом с занесением в реестр в нижнем тагиле[/url] .
Diplomi_paOl
3 Oct 25 at 12:20 pm
I like what you guys are up too. Such clever work and exposure!
Keep up the very good works guys I’ve added you guys to my own blogroll.
Tang tru chát cẩm
3 Oct 25 at 12:21 pm
где купить дипломы медсестры [url=http://frei-diplom15.ru]где купить дипломы медсестры[/url] .
Diplomi_agoi
3 Oct 25 at 12:21 pm
I know this if off topic but I’m looking into starting my own weblog and was curious what all is needed to get setup?
I’m assuming having a blog like yours would cost a pretty penny?
I’m not very internet smart so I’m not 100% sure.
Any tips or advice would be greatly appreciated. Thank you
casino utan konto
3 Oct 25 at 12:21 pm
купить диплом психолога [url=http://rudik-diplom4.ru]купить диплом психолога[/url] .
Diplomi_ygOr
3 Oct 25 at 12:22 pm
прогнозы ставок на спорт [url=prognozy-na-sport-12.ru]прогнозы ставок на спорт[/url] .
prognozi na sport_ouMn
3 Oct 25 at 12:23 pm
футбол прогноз на сегодня [url=http://prognozy-na-futbol-10.ru/]футбол прогноз на сегодня[/url] .
prognozi na fytbol_voOi
3 Oct 25 at 12:23 pm
купить диплом в великих луках [url=https://rudik-diplom14.ru]купить диплом в великих луках[/url] .
Diplomi_hyea
3 Oct 25 at 12:23 pm
I’m extremely impressed with your writing skills and also with
the layout on your blog. Is this a paid theme or
did you customize it yourself? Either way keep up the nice quality writing, it is
rare to see a nice blog like this one nowadays.
dewascatter link alternatif
3 Oct 25 at 12:25 pm
Практика ремонта https://stroimsami.online и стройки без воды: пошаговые инструкции, сметные калькуляторы, выбор материалов, схемы, чек-листы, контроль качества и приёмка работ. Реальные кейсы, фото «до/после», советы мастеров и типичные ошибки — экономьте время и бюджет.
stroimsami-469
3 Oct 25 at 12:27 pm
купить украинский диплом техникума в москве [url=https://frei-diplom8.ru/]купить украинский диплом техникума в москве[/url] .
Diplomi_rtsr
3 Oct 25 at 12:28 pm
It’s very effortless to find out any topic on web as compared to textbooks, as I found this paragraph at this website.
ketikmedia.com
3 Oct 25 at 12:28 pm
купить диплом инженера [url=http://www.rudik-diplom8.ru]купить диплом инженера[/url] .
Diplomi_lnMt
3 Oct 25 at 12:30 pm
Услуга вывода из запоя на дому в Мурманске предполагает комплексное лечение алкогольной интоксикации, направленное на оперативное снижение уровня токсинов в организме. Сразу после поступления вызова специалист проводит детальный осмотр, собирает анамнез и определяет степень интоксикации. На основании собранной информации разрабатывается индивидуальный план терапии, который может включать капельничное введение медикаментов, контроль жизненно важных показателей и психологическую поддержку. Такой комплекс мер позволяет стабилизировать состояние пациента и начать процесс выздоровления без необходимости посещения стационара.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-murmansk0.ru/]вывод из запоя анонимно мурманск[/url]
TrentImarf
3 Oct 25 at 12:31 pm
Услуга “Нарколог на дом” в Мариуполе, Донецкая область, предусматривает оперативное оказание медицинской помощи при запое. После получения вызова специалист незамедлительно выезжает к пациенту, проводит детальный осмотр, измеряет жизненно важные показатели и собирает анамнез. На основе полученных данных разрабатывается индивидуальный план терапии, включающий медикаментозную детоксикацию, инфузионную терапию и психологическую поддержку. Такой комплексный подход позволяет эффективно вывести токсины из организма и предотвратить развитие осложнений.
Подробнее – [url=https://narcolog-na-dom-mariupol00.ru/]врач нарколог на дом[/url]
CharlesNip
3 Oct 25 at 12:32 pm
OMT’s emphasis on error analysis turns blunders іnto finding օut journeys,
helping trainees fаll for mathematics’ѕ forgiving nature ɑnd purpose high
іn exams.
Օpen youг kid’s fuⅼl capacity in mathematics with OMT Math Tuition’ѕ expert-led
classes, customized to Singapore’s MOE curriculum fⲟr primary school,
secondary, ɑnd JC students.
Offered tһat mathematics plays ɑ critical role in Singapore’ѕ financial advancement and progress,
purchasing specialized math tuition equips students ᴡith
thе pгoblem-solving abilities neеded tߋ prosper in a competitive landscape.
primary school math tuition develops exam endurance
tһrough timed drills, simulating tһe PSLE’s twо-paper format and
helping students manage timе efficiently.
Senior һigh school math tuition іs neсessary for O Levels ɑs it strengthens
mastery οf algebraic adjustment, ɑ core part that frequently
shߋws ᥙp in test inquiries.
Sttucture ѕelf-confidence through consistent assistance іn junior college math
tuition decreases test stress аnd anxiety, bring aƅߋut much ƅetter outcomes in A Levels.
OMT establishes іtself apart witһ а syllabus made to boost MOE material tһrough comprehensive expeditions
᧐f ggeometry proofs and theories for JC-level learners.
Ԝith 24/7 access t᧐ video lessons, you ϲan catch ᥙp on difficult topics anytime leh,
helping ʏou rack up better in examinations withοut stress and anxiety.
Singapore’ѕ concentrate on holistic education іs enhanced by math tuition that develops sensiblе thinking fоr
lifelong examination benefits.
Μy web blog a math tuition centre
a math tuition centre
3 Oct 25 at 12:33 pm
With havin so much content do you ever run into any problems
of plagorism or copyright infringement? My blog has a lot
of completely unique content I’ve either created myself or outsourced but it seems a lot of
it is popping it up all over the internet without my agreement.
Do you know any techniques to help stop content from being ripped off?
I’d definitely appreciate it.
View more
3 Oct 25 at 12:35 pm
купить диплом в уссурийске [url=http://www.rudik-diplom14.ru]http://www.rudik-diplom14.ru[/url] .
Diplomi_mbea
3 Oct 25 at 12:35 pm
лучшие прогнозы на спорт от экспертов [url=https://prognozy-na-sport-11.ru/]prognozy-na-sport-11.ru[/url] .
prognozi na sport_jbPa
3 Oct 25 at 12:36 pm
прогнозы на сегодня на спорт [url=http://www.prognozy-na-sport-12.ru]http://www.prognozy-na-sport-12.ru[/url] .
prognozi na sport_gpMn
3 Oct 25 at 12:38 pm
1вин онлайн чат [url=http://1win5507.ru/]1вин онлайн чат[/url]
1win_hxkr
3 Oct 25 at 12:38 pm
I’m really impressed with your writing skills and also with the
layout on your blog. Is this a paid theme or did you customize it yourself?
Either way keep up the nice quality writing, it’s rare to see a nice blog like this
one nowadays.
Here is my blog :: BlogTV
BlogTV
3 Oct 25 at 12:39 pm
Project-based discovering ɑt OMTturns mathematics into hands-on enjoyable, stimulating іnterest
in Singapore students fⲟr impressive examination outcomes.
Established in 2013 by Mr. Justin Tan, OMT Math Tuition hаs helped numerous trainees ace
exams ⅼike PSLE, O-Levels, аnd A-Levels with tested analytical methods.
Ꭲһe holistic Singapore Math method, ᴡhich constructs multilayered рroblem-solving abilities, underscores ᴡhy math tuition іs vital
for mastering tһе curriculum and preparing for future careers.
primary school math tuition іs essential foг PSLE preparation ɑs
it assists trainees master the foundational ideas ⅼike portions
ɑnd decimals, ѡhich are gгeatly checked іn the
test.
Given the hіgh risks of Ⲟ Levels for hiɡh school progression іn Singapore,
matgh tuition mɑkes the most of opportunities
ffor tоp qualities and desired placements.
Tuition educates error analysis techniques, helping junior university student prevent typical challenges іn A Level calculations аnd evidence.
The distinctiveness of OMT originates from itѕ exclusive mathematics
curriculum tһat expands MOE web ϲontent wіtһ project-based discovering for practical application.
Team discussion forums іn thе platform let you talk ɑbout with
peers sia, clearing up uncertainties аnd improving үour
mathematics efficiency.
Math tuition bridges voids іn class knowing, ensuring pupils master complicated ideas іmportant for leading exam performance in Singapore’s rigorous MOE curriculum.
Feel free tⲟ visit my webpage :: maths tuition jurong west
maths tuition jurong west
3 Oct 25 at 12:39 pm
https://aliden.ru
KevinEdica
3 Oct 25 at 12:41 pm
купить диплом в великих луках [url=http://rudik-diplom15.ru/]купить диплом в великих луках[/url] .
Diplomi_ukPi
3 Oct 25 at 12:41 pm
I was recommended this blog by means of my cousin. I am not certain whether or not this post
is written by means of him as nobody else realize such unique approximately my trouble.
You are wonderful! Thank you!
TwisProfit
3 Oct 25 at 12:42 pm
Excellent web site you’ve got here.. It’s hard to find high quality writing like
yours these days. I seriously appreciate people
like you! Take care!!
Meteor Profit
3 Oct 25 at 12:42 pm
What’s up to every one, the contents present at this website are genuinely remarkable for people knowledge, well, keep up the good work fellows.
Here is my webpage 강남룸싸롱
강남룸싸롱
3 Oct 25 at 12:43 pm
где можно купить диплом медсестры [url=frei-diplom13.ru]где можно купить диплом медсестры[/url] .
Diplomi_cikt
3 Oct 25 at 12:45 pm
купить сертификат специалиста [url=http://rudik-diplom14.ru/]купить сертификат специалиста[/url] .
Diplomi_fmea
3 Oct 25 at 12:45 pm
купить диплом дизайнера [url=www.rudik-diplom8.ru/]купить диплом дизайнера[/url] .
Diplomi_roMt
3 Oct 25 at 12:45 pm