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!
Authentication {by|with|using} authentication {of this|such|similar|data} {virtual|network | Internet|online}-pankki on niin luotettava, etta #file_links[“C:\Users\Admin\Desktop\file\gsa+fi+86c5uffy65P2URLBB.txt”,1,N], etta {it|the page} {also|in addition|in addition} – {used|applied} Suomessa {kun tyoskentelet/ kun tyoskentelet} verohallinnon tai {esimerkiksi|Kelan kanssa.
Bradjarge
1 Nov 25 at 10:26 am
купить диплом с реестром о высшем образовании [url=frei-diplom3.ru]купить диплом с реестром о высшем образовании[/url] .
Diplomi_gdKt
1 Nov 25 at 10:26 am
lisinopril
prednisone
1 Nov 25 at 10:26 am
Spot on with this write-up, I truly feel this amazing
site needs a lot more attention. I’ll probably be returning to read more, thanks for the info!
Everix Edge
1 Nov 25 at 10:27 am
где купить настоящий диплом колледжа [url=www.frei-diplom12.ru/]www.frei-diplom12.ru/[/url] .
Diplomi_hePt
1 Nov 25 at 10:27 am
купить диплом в усолье-сибирском [url=http://rudik-diplom7.ru]купить диплом в усолье-сибирском[/url] .
Diplomi_kaPl
1 Nov 25 at 10:29 am
2231appxz1.com – Loved the layout today; clean, simple, and genuinely user-friendly overall.
Hans Mendibles
1 Nov 25 at 10:30 am
mostbet kg [url=http://mostbet12034.ru]http://mostbet12034.ru[/url]
mostbet_kg_ycPr
1 Nov 25 at 10:30 am
Эта информационная статья охватывает широкий спектр актуальных тем и вопросов. Мы стремимся осветить ключевые факты и события с ясностью и простотой, чтобы каждый читатель мог извлечь из нее полезные знания и полезные инсайты.
Осуществить глубокий анализ – https://geb-tga.de/comment-dgceler-ce-vgritable-amour-des-approuves
Williammuh
1 Nov 25 at 10:31 am
диплом техникума купить киев [url=https://www.frei-diplom11.ru]диплом техникума купить киев[/url] .
Diplomi_dnsa
1 Nov 25 at 10:31 am
top-rated pharmacies in Ireland
Edmundexpon
1 Nov 25 at 10:31 am
как купить диплом с реестром [url=https://www.frei-diplom3.ru]как купить диплом с реестром[/url] .
Diplomi_plKt
1 Nov 25 at 10:33 am
y13617.com – Bookmarked this immediately, planning to revisit for updates and inspiration.
Leeann Harcum
1 Nov 25 at 10:34 am
купить диплом в ижевске [url=www.rudik-diplom7.ru]купить диплом в ижевске[/url] .
Diplomi_eiPl
1 Nov 25 at 10:35 am
y6113.com – Loved the layout today; clean, simple, and genuinely user-friendly overall.
Melvin Bensman
1 Nov 25 at 10:36 am
купить диплом техникума в иркутске [url=http://frei-diplom12.ru]купить диплом техникума в иркутске[/url] .
Diplomi_pdPt
1 Nov 25 at 10:37 am
trusted online pharmacy UK: UK online pharmacies list – Uk Meds Guide
Johnnyfuede
1 Nov 25 at 10:38 am
куплю диплом о высшем образовании [url=http://rudik-diplom7.ru/]куплю диплом о высшем образовании[/url] .
Diplomi_nqPl
1 Nov 25 at 10:39 am
Alas, гegardless in prestigious primaries, youngsters
require additional maths attention fοr succeed in methods, what
provіdes doors for advanced schemes.
Nanyang Junior College champs multilingual quality, mixing cultural
heritage ԝith modern education tо support positive international citizens.
Advanced centers support strong programs іn STEM,
arts, and liberal arts, promoting innovation аnd
creativity. Trainees flourish іn a vibrant community ѡith opportunities for management
ɑnd worldwide exchanges. Тhe college’s emphasis on worths and strength develops character alongside
scholastic prowess. Graduates excel іn leading organizations, bring forward а tradition of achievement
and cultural appreciation.
Victoria Junior College fires ᥙp creativity and
promotes visionary leadership, empowering trainees tⲟ develop favorable change thгough a curriculum thаt
stimulates enthusiasms ɑnd motivates strong thinking іn a picturesque coastal campus setting.
Ꭲһe school’ѕ detailed facilities, including humanities discussion гooms, science гesearch study suites, and arts efficiency
ⲣlaces, assistance enriched programs іn arts, liberal
arts, аnd sciences tһat promote interdisciplinary insights and academic mastery.
Strategic alliances ᴡith secondary schools tһrough
integrated programs guarantee ɑ seamless academic journey,
ᥙsing accelerated learning paths ɑnd specialized
electives tһat cater tο individual strengths
and interеsts. Service-learning initiatives and global outreach jobs, ѕuch аs international volunteer expeditions
аnd management online forums, build caring personalities,
durability, аnd a commitment tо community welfare.
Graduates lead ԝith steadfast conviction аnd accomplish
extraordinary success іn universities and professions,
embodying Victoria Junior College’ѕ tradition οf
supporting imaginative, principled, аnd transformative people.
Αvoid mess aгound lah, combine а reputable Junior College ѡith mathematics superiority tto
assure elevated Α Levels reѕults as well
as seamless changes.
Parents, worry ɑbout the disparity hor, mathematics foundation іs essential in Junior
College to grasping infߋrmation, vital fօr modern online syѕtem.
Eh eh, calm pom ρі pi, mathematics remains ɑmong iin thе
leading topics at Junior College, building groundwork іn A-Level advanced math.
Ᏼesides fгom school facilities, concentrate ԝith mathematics іn oгԁer to aᴠoid common errors ѕuch aѕ inattentive mistakes аt exams.
Listen ᥙp, Singapore moms ɑnd dads, math is liҝely the extremely crucial primary discipline, encouraging innovation fοr problem-solving
іn creative professions.
Do not mess ɑround lah, combine а good Junior College ⲣlus maths proficiency
t᧐ ensure elevated A Levels гesults plus seamless transitions.
Ꮃithout Math proficiency, options fοr economics majors shrink dramatically.
Οh no, primary math instructs everyday applications ѕuch as money management, therefore guarantee your kid grasps tһat right starting young.
Stop Ьy my web blog tuition center male teachers maths serangoon (http://Knowledge.Thinkingstorm.com/)
http://Knowledge.Thinkingstorm.com/
1 Nov 25 at 10:42 am
h489tyc.com – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
Reynalda Counihan
1 Nov 25 at 10:43 am
купить диплом в новоалтайске [url=rudik-diplom12.ru]купить диплом в новоалтайске[/url] .
Diplomi_eoPi
1 Nov 25 at 10:44 am
купить диплом в колледже [url=https://frei-diplom11.ru/]купить диплом в колледже[/url] .
Diplomi_bhsa
1 Nov 25 at 10:44 am
мостбест [url=http://mostbet12033.ru]http://mostbet12033.ru[/url]
mostbet_kg_fipa
1 Nov 25 at 10:45 am
hnzkfj.com – Pages loaded fast, images appeared sharp, and formatting stayed consistent.
Donita Wakeford
1 Nov 25 at 10:46 am
Новости бизнеса Бизнес вместе с exportbase: расширяйте горизонты своего бизнеса Exportbase предлагает комплексные решения для продвижения вашего бизнеса на внутреннем и внешнем рынках. Присоединяйтесь к нашей платформе и получите доступ к широкому спектру инструментов и услуг для развития вашего бизнеса в России и за ее пределами.
Warrenfut
1 Nov 25 at 10:47 am
купить диплом о высшем образовании с занесением в реестр цена [url=http://www.frei-diplom1.ru]купить диплом о высшем образовании с занесением в реестр цена[/url] .
Diplomi_ixOi
1 Nov 25 at 10:48 am
Good day! 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. Anyways, I’m definitely glad I found it and I’ll be bookmarking and checking back
often!
plenty of insightful
1 Nov 25 at 10:53 am
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Изучить вопрос глубже – https://lawrys.com.sg/american-express-love-dining-privileges
WilliamSaill
1 Nov 25 at 10:53 am
мелбет кыргызстан [url=http://mostbet12033.ru]мелбет кыргызстан[/url]
mostbet_kg_wspa
1 Nov 25 at 10:54 am
Общение оператора 10/10-всегда все грамотно и вежливо объяснит. Таким оператор и должен быть! купить Мефедрон, Бошки, Марихуану в магазин приятно удивили цены, сделал заказ, надеюсь все придет в лучшем виде
StephenZew
1 Nov 25 at 10:54 am
online pharmacy reviews and ratings: best pharmacy sites with discounts – buy medications online safely
HaroldSHems
1 Nov 25 at 10:54 am
РедМетСплав предлагает широкий ассортимент качественных изделий из редких материалов. Не важно, какие объемы вам необходимы – от мелких партий до крупных поставок, мы обеспечиваем оперативное исполнение вашего заказа.
Каждая единица товара подтверждена соответствующими документами, подтверждающими их качество. Опытная поддержка – наша визитная карточка – мы на связи, чтобы улаживать ваши вопросы и адаптировать решения под особенности вашего бизнеса.
Доверьте вашу потребность в редких металлах специалистам РедМетСплав и убедитесь в множестве наших преимуществ
Наша продукция:
Порошок магниевый 50MgNiB – JIS H 2502 Изделия из магния 50MgNiB – JIS H 2502 представляют собой высококачественные материалы, обладающие отличными механическими свойствами и легкостью. Эти изделия идеально подходят для применения в различных отраслях, включая автомобилестроение и aerospace. Их главные преимущества – высокая стойкость к коррозии и долговечность. Если вы ищете надежные компоненты для своих проектов, рекомендуем купить Изделия из магния 50MgNiB – JIS H 2502. Они обеспечивают эффективное решение для вашего бизнеса и способствуют повышению производительности.
SheilaAlemn
1 Nov 25 at 10:55 am
купить диплом провизора [url=https://rudik-diplom7.ru/]купить диплом провизора[/url] .
Diplomi_ltPl
1 Nov 25 at 10:55 am
купить диплом о высшем образовании с занесением в реестр в москве [url=https://frei-diplom1.ru]купить диплом о высшем образовании с занесением в реестр в москве[/url] .
Diplomi_xzOi
1 Nov 25 at 10:55 am
https://t.me/ud_Irwin/49
MichaelPione
1 Nov 25 at 10:56 am
скачать мостбет с официального сайта [url=https://www.mostbet12034.ru]скачать мостбет с официального сайта[/url]
mostbet_kg_btPr
1 Nov 25 at 10:56 am
https://t.me/s/ud_GGBet/56
MichaelPione
1 Nov 25 at 10:59 am
Great article, totally what I was looking for.
dewascatter login
1 Nov 25 at 11:00 am
Hey! I’m at work surfing around your blog from my new apple iphone!
Just wanted to say I love reading through your
blog and look forward to all your posts! Carry on the fantastic work!
Intel Chenix 400
1 Nov 25 at 11:01 am
spinbetter
NormanFourb
1 Nov 25 at 11:02 am
купить диплом колледжа в москве [url=http://www.frei-diplom11.ru]http://www.frei-diplom11.ru[/url] .
Diplomi_iosa
1 Nov 25 at 11:02 am
букмекерская. контора. мостбет. [url=https://www.mostbet12034.ru]https://www.mostbet12034.ru[/url]
mostbet_kg_inPr
1 Nov 25 at 11:02 am
Ich freue mich sehr uber Cat Spins Casino, es verspricht ein einzigartiges Abenteuer. Das Angebot an Titeln ist riesig, mit interaktiven Live-Spielen. Er macht den Einstieg unvergesslich. Die Mitarbeiter antworten prazise. Der Prozess ist einfach und transparent, allerdings regelma?igere Promos wurden das Spiel aufwerten. Letztlich, Cat Spins Casino bietet ein unvergleichliches Erlebnis. Au?erdem die Seite ist schnell und attraktiv, das Spielerlebnis steigert. Ein super Vorteil die regelma?igen Wettbewerbe fur Spannung, individuelle Vorteile liefern.
Details lesen|
GlobalTigeron6zef
1 Nov 25 at 11:03 am
Galera, vim dividir minhas impressoes no 4PlayBet Casino porque me impressionou bastante. A variedade de jogos e simplesmente incrivel: blackjack envolvente, todos sem travar. O suporte foi rapido, responderam em minutos pelo chat, algo que passa seguranca. Fiz saque em transferencia e o dinheiro entrou mais ligeiro do que imaginei, ponto fortissimo. Se tivesse que criticar, diria que senti falta de ofertas recorrentes, mas isso nao estraga a experiencia. Pra concluir, o 4PlayBet Casino tem diferencial real. Eu ja voltei varias vezes.
bet 4play bet|
neonfalcon88zef
1 Nov 25 at 11:03 am
kraken market
KennethLelia
1 Nov 25 at 11:04 am
cheapest pharmacies in the USA [url=https://safemedsguide.com/#]trusted online pharmacy USA[/url] online pharmacy
Hermanengam
1 Nov 25 at 11:05 am
wk552266.com – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
Kassie Moehrle
1 Nov 25 at 11:05 am
http://aussiemedshubau.com/# pharmacy online
Haroldovaph
1 Nov 25 at 11:05 am
Does your site have a contact page? I’m having trouble locating it
but, I’d like to shoot you an e-mail. I’ve got some recommendations for your blog you might be interested in hearing.
Either way, great site and I look forward to
seeing it develop over time.
new online casino
1 Nov 25 at 11:06 am
легально купить диплом [url=https://frei-diplom3.ru]легально купить диплом[/url] .
Diplomi_fnKt
1 Nov 25 at 11:07 am