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!
What a material of un-ambiguity and preserveness of precious familiarity
on the topic of unpredicted feelings.
esta application
30 Aug 25 at 4:23 pm
Заказать диплом под заказ возможно используя сайт компании. [url=http://ariaqa.com/employer/diploms-goznak/]ariaqa.com/employer/diploms-goznak[/url]
Sazruey
30 Aug 25 at 4:26 pm
bonaslot link resmi mudah diakses [url=http://1wbona.com/#]bonaslot link resmi mudah diakses[/url] bonaslot jackpot harian jutaan rupiah
Aaronreima
30 Aug 25 at 4:30 pm
купить диплом о высшем с занесением в реестр [url=arus-diplom33.ru]купить диплом о высшем с занесением в реестр[/url] .
Diplomi_pgSa
30 Aug 25 at 4:31 pm
купить диплом с занесением в реестр вуза [url=www.arus-diplom34.ru/]купить диплом с занесением в реестр вуза[/url] .
Diplomi_ojer
30 Aug 25 at 4:31 pm
My programmer is trying to convince me to move to .net from PHP.
I have always disliked the idea because of the costs.
But he’s tryiong none the less. I’ve been using WordPress on a variety of websites
for about a year and am concerned about switching
to another platform. I have heard fantastic things about blogengine.net.
Is there a way I can import all my wordpress content into it?
Any help would be really appreciated!
Mevryon Platform
30 Aug 25 at 4:33 pm
Attractive section of content. I simply stumbled upon your web site
and in accession capital to say that I acquire in fact loved account your weblog posts.
Anyway I will be subscribing on your feeds or even I success you get entry
to constantly quickly.
thevaultvalleycity.com lừa đảo công an truy quét cấm người chơi tham gia
30 Aug 25 at 4:34 pm
сколько стоит купить аттестат 11 класса [url=arus-diplom22.ru]сколько стоит купить аттестат 11 класса[/url] .
Diplomi_pesl
30 Aug 25 at 4:37 pm
1wbona: bonaslot jackpot harian jutaan rupiah – bonaslot situs bonus terbesar Indonesia
Miltondep
30 Aug 25 at 4:38 pm
https://yamap.com/users/4790123
DouglasBem
30 Aug 25 at 4:41 pm
I got this website from my pal who shared with me regarding this website and now this time I am browsing this web site
and reading very informative articles or reviews at this time.
ketamine hcl for sale
30 Aug 25 at 4:45 pm
https://1wbona.shop/# bonaslot situs bonus terbesar Indonesia
Alfredrew
30 Aug 25 at 4:46 pm
Bagus sekali artikel ini, saya kagum cara penulis menyampaikan informasinya.
Pembahasan tentang KUBET dan Situs Judi Bola Terlengkap jelas bermanfaat, terutama untuk
orang-orang yang baru ingin mencoba taruhan bola online.
Saya percaya banyak pembaca akan setuju bahwa KUBET dan Situs Judi Bola Terlengkap sudah terbukti dibanding banyak platform lain.
Fitur-fiturnya ramah pengguna, bonusnya cukup besar,
dan layanan pelanggannya responsif.
Menurut saya pribadi, ulasan ini benar-benar membantu.
Mudah-mudahan semakin banyak orang yang mendapatkan manfaat
dari artikel seperti ini tentang KUBET dan Situs Judi
Bola Terlengkap.
Situs Judi Bola Terlengkap
30 Aug 25 at 4:46 pm
Приобрести диплом о высшем образовании!
Мы предлагаемвыгодно купить диплом, который выполняется на бланке ГОЗНАКа и заверен мокрыми печатями, водяными знаками, подписями. Диплом пройдет любые проверки, даже при помощи профессиональных приборов. Достигайте цели быстро и просто с нашими дипломами- [url=http://ledeia.flybb.ru/viewtopic.php?f=2&t=686&sid=0506b5544ec0ffd7fb5477c791cfaf93/]ledeia.flybb.ru/viewtopic.php?f=2&t=686&sid=0506b5544ec0ffd7fb5477c791cfaf93[/url]
Jariorhxf
30 Aug 25 at 4:49 pm
купить легальный диплом [url=www.arus-diplom33.ru/]купить легальный диплом[/url] .
Diplomi_xtSa
30 Aug 25 at 4:52 pm
vevobahis581.com
HowardVof
30 Aug 25 at 4:53 pm
Luxury1288
Luxury1288
30 Aug 25 at 4:53 pm
купить диплом украина харьков [url=https://www.educ-ua2.ru]купить диплом украина харьков[/url] .
Diplomi_pyOt
30 Aug 25 at 4:54 pm
Zombie vs Dao Zhang online KZ
Michaelblels
30 Aug 25 at 4:54 pm
Right away I am going to do my breakfast, later than having
my breakfast coming over again to read additional news.
dewascatter daftar
30 Aug 25 at 4:58 pm
Drug information sheet. Cautions.
can atorvastatin cause indigestion
Best what you want to know about pills. Get information here.
can atorvastatin cause indigestion
30 Aug 25 at 5:01 pm
https://c0bcb1baaab929ee0c051b4c4c.doorkeeper.jp/
DouglasBem
30 Aug 25 at 5:04 pm
купить диплом о среднем техническом образовании [url=www.educ-ua2.ru/]купить диплом о среднем техническом образовании[/url] .
Diplomi_dyOt
30 Aug 25 at 5:06 pm
Когда организм на пределе, важна срочная помощь в Самаре — это команда опытных наркологов, которые помогут быстро и мягко выйти из запоя без вреда для здоровья.
Узнать больше – [url=https://vyvod-iz-zapoya-v-stacionare-samara11.ru/]вывод из запоя вызов[/url]
ThomasKex
30 Aug 25 at 5:07 pm
I needed to thank you for this fantastic read!!
I certainly loved every bit of it. I have got you book marked to check out new stuff you
post…
8day
30 Aug 25 at 5:08 pm
Купить диплом университета!
Наши специалисты предлагаютбыстро и выгодно заказать диплом, который выполняется на бланке ГОЗНАКа и заверен печатями, штампами, подписями должностных лиц. Данный документ способен пройти любые проверки, даже с применением профессионального оборудования. Достигайте цели максимально быстро с нашим сервисом- [url=http://ai.holiday/read-blog/45271_kupit-diplom-v-moskve.html/]ai.holiday/read-blog/45271_kupit-diplom-v-moskve.html[/url]
Jariorvdg
30 Aug 25 at 5:10 pm
I am really enjoying the theme/design of
your website. Do you ever run into any web browser compatibility issues?
A couple of my blog audience have complained about my blog not working correctly in Explorer but looks great in Safari.
Do you have any solutions to help fix this problem?
web page
30 Aug 25 at 5:12 pm
высшее образование купить диплом с занесением в реестр [url=www.arus-diplom34.ru]высшее образование купить диплом с занесением в реестр[/url] .
Diplomi_zder
30 Aug 25 at 5:17 pm
Алкогольный запой, это серьезное состояние, которое появляется при длительном пьянстве. Последствия запоя могут быть серьезными: физическое истощение, повреждение органов, психические расстройства. Быстрый выход из запоя в Туле включает лекарственную терапию и психологическую поддержку. Необходимо знать признаки запойного алкоголизма: регулярные запои, утрата контроля над потреблением спиртного. Методы выхода из запоя разнообразны: от капельниц до консультаций специалистов. Восстановление после запоя требует системного подхода, включая возвращение к здоровью и психологическую помощь. Лечение алкогольной зависимости в Туле предлагает медицинские центры, где доступны программы помощи. экстренный вывод из запоя тула
lechenietulaNeT
30 Aug 25 at 5:19 pm
купить диплом о высшем цена [url=http://educ-ua4.ru/]купить диплом о высшем цена[/url] .
Diplomi_jlPl
30 Aug 25 at 5:20 pm
https://www.betterplace.org/en/organisations/67498
DouglasBem
30 Aug 25 at 5:26 pm
casino online sicuri con Starburst: migliori casino online con Starburst – casino online sicuri con Starburst
LouisJoync
30 Aug 25 at 5:30 pm
Заказать диплом любого ВУЗа!
Наши специалисты предлагаютбыстро заказать диплом, который выполняется на бланке ГОЗНАКа и заверен мокрыми печатями, штампами, подписями должностных лиц. Диплом пройдет лубую проверку, даже с использованием профессиональных приборов. Решите свои задачи быстро и просто с нашими дипломами- [url=http://network.vietagri.online/read-blog/22427_kupit-diplom-v-moskve.html/]network.vietagri.online/read-blog/22427_kupit-diplom-v-moskve.html[/url]
Jariorpey
30 Aug 25 at 5:33 pm
What’s up, just wanted to mention, I enjoyed
this post. It was practical. Keep on posting!
Русское казино с выводом
30 Aug 25 at 5:36 pm
Tulisan ini benar-benar keren!
Saya setuju sekali bahwa situs taruhan bola resmi dan situs resmi taruhan bola adalah pilihan terbaik bagi pemain yang ingin bermain aman dan nyaman.
Saya pribadi sering memakai bola88 agen judi bola resmi dan situs taruhan terpercaya untuk taruhanbola.
Selain itu, saya juga mencoba situs resmi taruhan bola online seperti idnscore, sbobet, sbobet88, hingga sarangsbobet.
Dengan adanya idnscore login dan situs judi bola, saya bisa update score
bola lebih cepat.
Bahkan saya juga suka mencoba slot88, parlay bola, situs bola, dan bola resmi sambil memanfaatkan link sbobet atau idn score.
Situs seperti sbobet88 login, mix parlay, idnscore 808 live, dan parlay88 login membuat pengalaman bola online jadi lebih seru.
Agen bola, situs bola live, taruhan bola, hingga
situs bola terpercaya juga sangat membantu.
Bagi saya, judi bola online, bolaonline, serta situs bola online seperti esbobet dan situs parlay adalah hiburan yang tidak pernah membosankan.
Judi bola terpercaya di situs judi bola terbesar juga semakin populer, apalagi ada link judi bola, judi bola parlay, situs
judi terbesar, parlay 88, agen sbobet, dan linksbobet.
Jangan lupakan juga platform populer seperti kubet, kubet
login, kubet indonesia, kubet link alternatif, dan kubet login alternatif yang jadi pilihan banyak pemain.
Thanks atas sharing ini, sangat membantu bagi siapa pun yang mencari situs judi bola terpercaya dan taruhanbola online.
situs bola online
30 Aug 25 at 5:38 pm
диплом купить с проводкой [url=www.arus-diplom33.ru/]диплом купить с проводкой[/url] .
Diplomi_nhSa
30 Aug 25 at 5:38 pm
I don’t even know how I ended up here, but I assumed this publish was once good.
I don’t understand who you might be but certainly you’re going to a famous blogger when you are not already.
Cheers!
AIDS
30 Aug 25 at 5:40 pm
Hello There. I found your blog using msn. This is a very well written article.
I will be sure to bookmark it and come back to read more of your useful
info. Thanks for the post. I will certainly comeback.
affordable seafront hotel
30 Aug 25 at 5:41 pm
Оказание помощи нарколога на дому организовано по отлаженной схеме, включающей несколько ключевых этапов, которые позволяют оперативно стабилизировать состояние пациента и начать детоксикацию:
Исследовать вопрос подробнее – http://наркология-дома1.рф
SteveFEP
30 Aug 25 at 5:42 pm
купить диплом о среднем образовании в реестр [url=https://www.arus-diplom34.ru]купить диплом о среднем образовании в реестр[/url] .
Diplomi_kier
30 Aug 25 at 5:44 pm
https://bio.site/suugacebobqa
DouglasBem
30 Aug 25 at 5:49 pm
Каждый из наших врачей не только специалист, но и психолог, способный понять переживания пациента, создать атмосферу доверия. Мы применяем индивидуальный подход, позволяя каждому пациенту чувствовать себя комфортно. Наши наркологи проводят тщательную диагностику, разрабатывают планы лечения, основываясь на данных обследования, психологическом состоянии и других факторах. Основное внимание уделяется снижению абстиненции, лечению сопутствующих заболеваний, коррекции психоэмоционального состояния.
Получить дополнительную информацию – https://alko-konsultaciya.ru/vivod-iz-zapoya-anonimno-v-smolenske/
Andrewwerie
30 Aug 25 at 5:49 pm
Excellent blog! Do you have any suggestions for aspiring writers?
I’m hoping to start my own blog soon but I’m a little lost
on everything. Would you advise starting with
a free platform like WordPress or go for a paid option?
There are so many options out there that I’m completely
confused .. Any recommendations? Thank you!
ujangbet
30 Aug 25 at 5:51 pm
Excellent goods from you, man. I’ve understand your stuff previous to and
you are just extremely magnificent. I really like what
you’ve acquired here, certainly like what you are saying and the way in which you say it.
You make it entertaining and you still take care of to keep it sensible.
I can’t wait to read far more from you. This is actually a terrific site.
Louella
30 Aug 25 at 5:51 pm
Купить диплом любого ВУЗа!
Мы предлагаемвыгодно и быстро купить диплом, который выполняется на оригинальной бумаге и заверен мокрыми печатями, штампами, подписями. Диплом способен пройти любые проверки, даже при помощи специфических приборов. Решите свои задачи максимально быстро с нашей компанией- [url=http://ai.holiday/read-blog/45271_kupit-diplom-v-moskve.html/]ai.holiday/read-blog/45271_kupit-diplom-v-moskve.html[/url]
Jariorege
30 Aug 25 at 5:55 pm
OMT’s analysis analyses tailor motivation, helping students
drop іn love ᴡith their distinct mathematics journey tߋward exam success.
Established іn 2013 by Mr. Justin Tan, OMT Math Tuition һas
helped countless students ace tests ⅼike
PSLE, O-Levels, ɑnd Ꭺ-Levels with tested problеm-solving strategies.
Ꮤith trainees in Singapore starting formal math education fгom ɗay one ɑnd dealing wіth һigh-stakes assessments, math tuition սses thе additional edge neeⅾеd tߋ achieve leading performancce іn this іmportant subject.
Tuition stresses heuristic ρroblem-solving methods, іmportant for taкing on PSLE’ѕ difficult ᴡord
pr᧐blems tһat require multiple steps.
Ԍiven the hіgh risks of O Levels fοr secondary school progression іn Singapore,
math tuition tаkes full advantage of opportunities for toρ
qualities аnd preferred placements.
Junior college math tuition іs vital fοr Α Degrees
аs it strengthens understanding ᧐f sophisticated
calculus subjects ⅼike assimilation methods ɑnd differential formulas, ѡhich are central to
the examination curriculum.
OMT sets іtself ɑpart ᴡith an educational program tһat enhances MOE curriculum սsing collaborative online forums fоr discussing
proprietary mathematics obstacles.
OMT’ѕ e-learning reduces math anxiety lor, mɑking you
muϲh moгe positive and rеsulting in highеr test marks.
Bү integrating innovation, online math tuition involves digital-native
Singapore pupils fоr interactive exam modification.
Ηere іs my homepɑge … math tutors
math tutors
30 Aug 25 at 5:59 pm
Приобрести диплом любого университета!
Мы предлагаеммаксимально быстро купить диплом, который выполняется на оригинальной бумаге и заверен печатями, водяными знаками, подписями должностных лиц. Данный документ пройдет любые проверки, даже с использованием специального оборудования. Достигайте цели быстро и просто с нашим сервисом- [url=http://izibiz.pl/companies/aurus-diplomany/]izibiz.pl/companies/aurus-diplomany[/url]
Jariorjzl
30 Aug 25 at 6:01 pm
купить диплом стоит [url=https://educ-ua2.ru]купить диплом стоит[/url] .
Diplomi_gwOt
30 Aug 25 at 6:05 pm
Les couleurs vives et flashy, comme le rose et le jaune, sont typiques de cette
époque.
non gamstop casinos
30 Aug 25 at 6:07 pm
https://wirtube.de/a/brown_michelled58652/video-channels
DavidVef
30 Aug 25 at 6:11 pm