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!
Aussie Meds Hub Australia: verified online chemists in Australia – verified online chemists in Australia
HaroldSHems
3 Nov 25 at 1:33 am
Thank you for sharing your info. I truly appreciate
your efforts and I will be waiting for your further post thank you once again.
طراحی سایت صنعتی در تهران
3 Nov 25 at 1:34 am
1 x bet giri? [url=1xbet-giris-5.com]1xbet-giris-5.com[/url] .
1xbet giris_umSa
3 Nov 25 at 1:36 am
потолочкин ру натяжные потолки [url=www.natyazhnye-potolki-nizhniy-novgorod-1.ru]потолочкин ру натяжные потолки[/url] .
natyajnie potolki nijnii novgorod_lxma
3 Nov 25 at 1:36 am
1xbet resmi giri? [url=https://1xbet-giris-6.com/]1xbet-giris-6.com[/url] .
1xbet giris_nqsl
3 Nov 25 at 1:37 am
https://t.me/s/UD_BOoi
AlbertTeery
3 Nov 25 at 1:39 am
https://t.me/s/ud_keNT
AlbertTeery
3 Nov 25 at 1:40 am
1xbet g?ncel adres [url=http://www.1xbet-giris-2.com]http://www.1xbet-giris-2.com[/url] .
1xbet giris_dyPt
3 Nov 25 at 1:41 am
https://safemedsguide.com/# best online pharmacy
Haroldovaph
3 Nov 25 at 1:43 am
1 x bet giri? [url=https://www.1xbet-giris-5.com]https://www.1xbet-giris-5.com[/url] .
1xbet giris_vcSa
3 Nov 25 at 1:44 am
компания потолочкин [url=www.natyazhnye-potolki-nizhniy-novgorod-1.ru]www.natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_xsma
3 Nov 25 at 1:48 am
cheap medicines online Australia [url=http://aussiemedshubau.com/#]compare pharmacy websites[/url] Aussie Meds Hub Australia
Hermanengam
3 Nov 25 at 1:48 am
best UK pharmacy websites: online pharmacy – UkMedsGuide
HaroldSHems
3 Nov 25 at 1:49 am
[url=http://btcoroplast.com/2018/08/24/about-us/]http://btcoroplast.com/2018/08/24/about-us/[/url] Monte Carlo,,,?????????
Jessicafag
3 Nov 25 at 1:49 am
1xbwt giri? [url=http://1xbet-giris-2.com/]http://1xbet-giris-2.com/[/url] .
1xbet giris_qbPt
3 Nov 25 at 1:50 am
рейтинг сео компаний [url=https://reiting-seo-kompanii.ru/]рейтинг сео компаний[/url] .
reiting seo kompanii_kzsn
3 Nov 25 at 1:50 am
bahis sitesi 1xbet [url=1xbet-giris-5.com]bahis sitesi 1xbet[/url] .
1xbet giris_biSa
3 Nov 25 at 1:51 am
best Irish pharmacy websites
Edmundexpon
3 Nov 25 at 1:56 am
потолочкин натяжные потолки нижний новгород отзывы [url=natyazhnye-potolki-nizhniy-novgorod-1.ru]natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_jdma
3 Nov 25 at 1:56 am
https://classix.bizlisting.cloud/code-bonus-1xbet-2026-e130-pour-paris-sportifs/
EdwardLag
3 Nov 25 at 1:56 am
1xbet guncel [url=https://www.1xbet-giris-2.com]https://www.1xbet-giris-2.com[/url] .
1xbet giris_lnPt
3 Nov 25 at 1:58 am
1 x bet [url=www.1xbet-giris-5.com/]www.1xbet-giris-5.com/[/url] .
1xbet giris_hzSa
3 Nov 25 at 1:59 am
유흥알바는 일반적인 서비스 업종과 달리 야간 시간대에 진행되는
특수한 아르바이트 직종입니다. 예를 들어 노래방 도우미, 룸살롱 직원, 바텐더 등 다양한 형태가 있으며
유흥알바
3 Nov 25 at 1:59 am
школы английского языка [url=https://moygorod.online/article/razdel24/moy-gorod-stati_60985.html/]https://moygorod.online/article/razdel24/moy-gorod-stati_60985.html/[/url] .
shkoli angliiskogo yazika_edKi
3 Nov 25 at 2:00 am
1xbet yeni giri? adresi [url=www.1xbet-giris-5.com/]www.1xbet-giris-5.com/[/url] .
1xbet giris_jjSa
3 Nov 25 at 2:04 am
потолочник потолки [url=http://www.natyazhnye-potolki-nizhniy-novgorod-1.ru]http://www.natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_cema
3 Nov 25 at 2:06 am
1xbetgiri? [url=1xbet-giris-6.com]1xbet-giris-6.com[/url] .
1xbet giris_ousl
3 Nov 25 at 2:08 am
1xbet mobi [url=http://1xbet-giris-2.com/]http://1xbet-giris-2.com/[/url] .
1xbet giris_uaPt
3 Nov 25 at 2:10 am
Howdy! Do you know if they make any plugins to safeguard against hackers?
I’m kinda paranoid about losing everything I’ve worked
hard on. Any tips?
Cerita Dewasa co
3 Nov 25 at 2:11 am
рейтинг digital агентств москвы [url=https://www.luchshie-digital-agencstva.ru]рейтинг digital агентств москвы[/url] .
lychshie digital agentstva_fooi
3 Nov 25 at 2:12 am
Listen up, avoid disregard ɑbout math lah, it’s tһe ccore fߋr
primary syllabus, ensuring yoսr youngster avoids lag ⅾuring demanding
Singapore.
In аddition to institution standing, а firm maths foundation develops strength аgainst A Levels demands
annd prospective һigher ed challenges.
Parents, kiasu а tad hor, mathematics proficiency іn Junior College proves vital іn building
analytical thinking ԝhich recruiters аppreciate ѡithin tech
sectors.
Nanyang Junior College champs bilingual excellence, boending cultural heritage ᴡith contemporary
education tօ nurture positive worldwide people.
Advanced centers support strong programs іn STEM, arts, аnd
liberal arts, promoting development аnd creativity.
Students prosper іn ɑ vibrant neighborhood ԝith opportunities fߋr management and global exchanges.Ꭲһe college’ѕ emphasis on worths аnd resilience builds character tоgether
witһ scholastic expertise. Graduates excel іn top institutions,
ƅring forward а tradition оf accomplishment and cultural appreciation.
Millennia Institute stands ɑpart ᴡith its distinctive tһree-yeɑr
pre-university pathway leading tο the GCE A-Level evaluations, supplying flexible аnd thorougһ research study choices іn commerce, arts,
ɑnd sciences tailored tο accommodate а diverse series of
learners and their distinct goals. Ꭺs ɑ centralized institute, іt uses tailored assistance and support systems,
consisting ⲟf dedicated academic consultants аnd
counseling services, tо make sure еvery trainee’s holistic advancement ɑnd academic success іn a inspiring environment.
Tһe institute’s advanced facilities, such as digital learning
hubs, multimedia resource centers, аnd collaborative ᴡork ɑreas, prodice ɑn engaging
platform foг innovative teaching аpproaches аnd
hands-on jobs that bridge theory wiyh սseful
application. Ꭲhrough strong industry partnerships, students access
real-ԝorld experiences ⅼike internships, workshops with specialists, аnd scholarship
chances tһаt boost their employability аnd career preparedness.
Alumni fгom Millennia Institute regularly attain success іn college and professional arenas, showіng
tһe institution’ѕ unwavering commitment tߋ promoting ⅼong-lasting learning, versatility, and personal empowerment.
Parents, fearful ⲟf losing style ᧐n lah, robust primary math leads
fߋr superior STEM comprehension аs ԝell аs tech aspirations.
Wah lao, no matter ᴡhether institution іs atas, maths is the mɑke-or-break subject to cultivates assurance іn figures.
Hey hey, Singapore parents, math гemains perhapѕ the
highly іmportant primary discipline, promoting innovation fоr challenge-tackling tߋ innovative jobs.
Αvoid tak lightly lah, link ɑ excellent Junior College рlus mathematics excellence foг guarantee elevated A Levels scores ρlus effortless ϲhanges.
Withߋut strong Math, competing іn Singapore’ѕ meritocratic ѕystem becomes ɑn uphill battle.
Listen սp, calm pom pi pі, maths proves one of tһe leading subjects іn Junior College, laying foundation іn A-Level
higһer calculations.
Ιn addition beyond institution facilities, concentrate ᥙpon math to stop frequent mistakes
sսch аѕ inattentive blunders dսring assessments.
my blog post – Unity Secondary
Unity Secondary
3 Nov 25 at 2:14 am
Tarz?n?z? 90’lar?n unutulmaz modas?ndan esinlenerek gunumuze tas?mak ister misiniz? Oyleyse bu yaz?m?z tam size gore!
Хочу выделить раздел про Evinizde Estetik ve Fonksiyonu Birlestirin: Ipuclar? ve Trendler.
Ссылка ниже:
[url=https://anadolustil.com]https://anadolustil.com[/url]
90’lar?n buyusunu modern dunyaya tas?mak hic bu kadar kolay olmam?st?. Unutulmayan bu donemin guzellik s?rlar?n? unutmay?n!
Josephassof
3 Nov 25 at 2:15 am
натяжные потолки в нижнем новгороде [url=www.natyazhnye-potolki-nizhniy-novgorod-1.ru/]натяжные потолки в нижнем новгороде[/url] .
natyajnie potolki nijnii novgorod_tsma
3 Nov 25 at 2:18 am
1xbet resmi sitesi [url=https://1xbet-giris-5.com/]https://1xbet-giris-5.com/[/url] .
1xbet giris_tcSa
3 Nov 25 at 2:18 am
1xbet giri?i [url=https://1xbet-giris-2.com/]https://1xbet-giris-2.com/[/url] .
1xbet giris_ahPt
3 Nov 25 at 2:18 am
https://rnmanagers.com/author/linebet-codepromotion/
AnthonyGaw
3 Nov 25 at 2:19 am
discoverpossibility – The overall feel is positive and engaging, good job creating this space.
Palmer Brubeck
3 Nov 25 at 2:19 am
Please let me know if you’re looking for a article writer for your weblog.
You have some really great posts and I feel I would be a good asset.
If you ever want to take some of the load off, I’d love to
write some articles for your blog in exchange
for a link back to mine. Please send me an e-mail
if interested. Kudos!
Check out new Marcello Red music Prophecy tape Volume 2 Tale of Marcus Marcello Clinton Dorleus of favorite music streaming apps new film trimester in theaters nov 21
3 Nov 25 at 2:20 am
Вызов обработка от клопов стоимость на выходные возможен?
травля тараканов
KennethceM
3 Nov 25 at 2:20 am
research by the staff of gooncloud.click
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
research by the staff of gooncloud.click
3 Nov 25 at 2:20 am
Interesantísima guía sobre los juegos de casino online más populares en Pin Up México.
Es impresionante cómo juegos como Gates of Olympus,
Sweet Bonanza y Book of Dead continúan siendo los preferidos.
La explicación de las funciones especiales y versiones demo fue muy clara.
Recomiendo leer el artículo completo si quieres descubrir qué juegos están marcando tendencia en Pin Up Casino.
Se agradece ver una mezcla entre títulos nostálgicos y
nuevas propuestas en el mercado mexicano de apuestas.
No dudes en leer la nota completa y descubrir por qué estos juegos son tendencia en los casinos online de
México.
information
3 Nov 25 at 2:21 am
Link exchange is nothing else however it is only placing the other person’s blog link on your page
at appropriate place and other person will also do
similar in favor of you.
اجاره بای پپ Ventmed مدل DS-8 (ST30)
3 Nov 25 at 2:22 am
buy medicine online legally Ireland: Irish Pharma Finder – top-rated pharmacies in Ireland
Johnnyfuede
3 Nov 25 at 2:23 am
Besіdes beyond institution facilities, emphasize ԝith maths fօr
prevent common mistakes ⅼike sloppy mistakes durіng assessments.
Parents, kiasu approach օn lah, solid primary math leads
t᧐ betteг science grasp as well as construction aspirations.
Victoria Junior College cultivates creativity аnd management, igniting enthusiasms fօr future production. Coastal school facilities support arts, liberal arts, ɑnd sciences.
Integrated prfograms ԝith alliances use seamless, enriched education. Service аnd global efforts construct caring,
resilient individuals. Graduates lead ѡith conviction, attaining impressive success.
National Junior College, holding tһe difference
as Singapore’ѕ veгy firѕt junior college, supplies unparalleled
opportunities fօr intellectual expedition ɑnd management cultivation ѡithin a historic and motivating school tһаt blends tradition with modern-ԁay educational quality.
Ꭲhe unique boarding program promotes ѕеlf-relianceand ɑ sense
of neighborhood, ѡhile modern reseɑrch study facilities and specialized laboratories ɑllow students frоm varied backgrounds to pursue
sophisticated гesearch studies іn arts, sciences, and liberal arts ᴡith optional choices fοr customized learning paths.
Ingenious programs motivate deep scholastic immersion, ѕuch
ɑs project-based гesearch and interdisciplinary workshops tһat sharpen analytical skills and foster creativity ɑmong ambitious scholars.
Тhrough comprehensive international partnerships, consisting of trainee
exchanges, international symposiums, аnd collective initiatiuves ᴡith abroad universities, learners develop broad networks and a nuanced understanding of ɑround the world concerns.
The college’s alumni, wһo frequently presume popular
functions іn federal government, academic community, ɑnd market,
exemplify National Junior College’ѕ enduring contribution tο nation-building and tһе development ⲟf visionary, impactful
leaders.
Wow, math іs the base block іn primary learning, aiding youngsters for
geometric analysis for building routes.
Alas, lacking solid maths ⅾuring Junior College, no matter leading school kids ϲould struggle in һigh school equations, thеrefore develop it promрtly leh.
Listen ᥙp, Singapore parents, math is probabⅼy the
extremely іmportant primary subject, promoting creativity tһrough challenge-tackling in groundbreaking
professions.
Ɗo not mess around lah, pair a reputable Junior College ԝith maths superiority tߋ guarantee
һigh A Levels marks ⲣlus seamless transitions.
Folks, dread tһe difference hor, math base іs critical at Junior College t᧐ grasping figures, crucial ԝithin modern digital ѕystem.
Don’tbe kiasu f᧐r nothing; ace уour A-levels to snag thoѕe scholarships ɑnd avoid the competition later.
Wah lao, еvеn wһether establishment іѕ higһ-end, maths serves аs
the make-or-break topic for cultivates confidence іn figures.
my ρage – Zhenghua Secondary School Singapore
Zhenghua Secondary School Singapore
3 Nov 25 at 2:23 am
купить натяжные потолки в нижнем новгороде недорого [url=natyazhnye-potolki-nizhniy-novgorod-1.ru]natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_zlma
3 Nov 25 at 2:26 am
1xbet ?ye ol [url=https://1xbet-giris-2.com]https://1xbet-giris-2.com[/url] .
1xbet giris_pxPt
3 Nov 25 at 2:26 am
https://t.me/s/UD_gGbET
AlbertTeery
3 Nov 25 at 2:27 am
1xbet giri? adresi [url=http://www.1xbet-giris-2.com]http://www.1xbet-giris-2.com[/url] .
1xbet giris_hfPt
3 Nov 25 at 2:28 am
Thank you for another magnificent article. The place else may just anyone get that kind of info in such
a perfect approach of writing? I’ve a presentation subsequent week, and I
am on the look for such info.
Paito Warna Sydney 6D All Color
3 Nov 25 at 2:28 am
https://t.me/s/uD_LEgzO
AlbertTeery
3 Nov 25 at 2:30 am