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!
Сегодня обменник скинов — это не просто часть игрового процесса, а своего рода мини-индустрия, где важны внимательность, понимание цен и умение выстраивать доверие с другими игроками. В этой статье мы разберём, как безопасно и эффективно пользоваться системой трейдов в CS2, какие платформы наиболее удобны и на что стоит обратить внимание, чтобы не нарваться на мошенников.
ShawnNab
18 Sep 25 at 12:15 pm
обрезка деревьев цены
обрезка деревьев цены
18 Sep 25 at 12:17 pm
купить диплом об образовании киев [url=http://educ-ua19.ru]http://educ-ua19.ru[/url] .
Diplomi_ndml
18 Sep 25 at 12:19 pm
I love your blog.. very nice colors & theme.
Did you make this website yourself or did you hire someone
to do it for you? Plz answer back as I’m looking to design my
own blog and would like to find out where u got this from.
thanks
dewascatter
18 Sep 25 at 12:20 pm
https://pixelfed.tokyo/zfmomuhmzi856
RobertSnova
18 Sep 25 at 12:21 pm
Your way of describing everything in this article is truly nice, all be able to
without difficulty be aware of it, Thanks a lot.
Zeno Flow Engine
18 Sep 25 at 12:26 pm
услуги по выравниванию земельного участка
услуги по выравниванию земельного участка
18 Sep 25 at 12:26 pm
Мы можем предложить документы университетов, которые расположены в любом регионе РФ. Купить диплом ВУЗа:
[url=http://alertesjob.com/employer/diplomiki/]аттестат за 11 класс 2006 купить[/url]
Diplomi_cpPn
18 Sep 25 at 12:27 pm
Oһ man, even wһether establishment proves atas, mathematics
іs the decisive discipline іn building confidence гegarding figures.
Aiyah, primary mathematics instructs practical applications ⅼike money management,
so make ѕure your youngster grasps tһat correctly starting еarly.
River Valley High School Junior College integrates bilingualism
ɑnd environmental stewardship, developing eco-conscious leaders ԝith worldwide perspectives.
Modern laboratories аnd green nitiatives support cutting-edge knowing in sciences ɑnd humanities.
Students engage іn cultural immersions аnd service jobs,
enhancing empathy ɑnd skills. Thе school’s unified community promotes strength ɑnd
teamwork throᥙgh sports and arts. Graduates are prepared for
success іn universities аnd beуond, embodying perseverance and cultural acumen.
Tampines Meridian Junior College,born fгom tһe lively
merger οf Tampines Junior College аnd Meridian Junior College, providеs ɑn innovative and culturally abundant education highlighted Ьy specialized electives іn drama and Malay language, nurturing meaningful ɑnd multilingual talents іn a forward-thinking neighborhood.
Ꭲhe college’s advanced facilities, including theater spaces, commerce
simulation laboratories, ɑnd science innovation hubs, support diverse scholastic
streams tһat encourage interdisciplinary expedition аnd practical skill-building aсross arts, sciences, аnd organization. Talent
advancement programs, combined ԝith overseas immersion
journeys ɑnd cultural festivals, foster strong leadership qualities, cultural
awareness, аnd flexibility to global dynamics. Ꮃithin a caring аnd empathetic school culture,
trainees participate іn wellness initiatives, peer support ѕystem, and cο-curricular сlubs tһat promote resilience, psychological
intelligence, annd collaborative spirit. Ꭺs a result, Tampines Meridian Junior
College’ѕ students achieve holistic development ɑnd агe well-prepared tߋ tackle global challenges,
emerging аs positive, versatile individuals prepared fօr university success ɑnd beyond.
Oh man, eᴠen though institution іs hiɡh-end, mathematics serves аѕ thе critical topic tⲟ cultivates assurance ԝith
calculations.
Oһ no, primary math educates real-ѡorld implementations
like financial planning, therefore ensure yоur
youngster ցets tһat correctly ƅeginning eɑrly.
Folks, fear the gap hor, math groundwork proves critical ԁuring Junior College f᧐r understanding
infоrmation, crucial in modern digital ѕystem.
Do not take lightly lah, link а reputable Junior College рlus maths proficiency іn orԁeг tо ensure һigh A Levels resuⅼts as well as effortless shifts.
Parents, dread tһe disparity hor, mathematics groundwork
гemains essential ɑt Junior College tօ comprehending data, crucial іn today’s digital market.
Ꭺ-level success inspires siblings іn tһe family.
Eh eh, calm pom ρi pі, mathematics proves among in tһe leading disciplines
at Junior College, building foundation іn A-Level hіgher calculations.
junior college
18 Sep 25 at 12:28 pm
Excellent post. I will be experiencing some of these issues as well..
online slots real money
18 Sep 25 at 12:29 pm
купить диплом института образования [url=https://www.educ-ua19.ru]купить диплом института образования[/url] .
Diplomi_hfml
18 Sep 25 at 12:29 pm
Visit hye
youtubewdg
18 Sep 25 at 12:30 pm
Thank you for the auspicious writeup. It in fact was
a amusement account it. Look advanced to more added agreeable from you!
By the way, how could we communicate?
ثبت نام ماکسیم راننده
18 Sep 25 at 12:32 pm
Carnevale di Venezia сравнение с другими онлайн слотами
Eddiefen
18 Sep 25 at 12:39 pm
Через него можно входить на платформу даже без использования
браузера.
7k
18 Sep 25 at 12:42 pm
[url=http://clearmedshub.com/#][/url]
Michealstilm
18 Sep 25 at 12:43 pm
Internet Marketing – Competitive Research Tips submit (Mireya)
Mireya
18 Sep 25 at 12:45 pm
http://www.pageorama.com/?p=sycryaedy
RobertSnova
18 Sep 25 at 12:45 pm
https://word66036.ampblogs.com/la-guГa-definitiva-para-capacitacion-de-liderazgo-online-74006121
Participar en una escuela de liderazgo virtual ya no es un lujo, sino una necesidad para cualquier negocio que aspira a competir en el contexto moderno.
Un buen curso de liderazgo empresarial no solo ensena teoria, sino que transforma la practica del liderazgo de mandos medios que tienen equipos a cargo.
Que tiene de especial una formacion en liderazgo online?
Autonomia para progresar sin frenar el trabajo diario.
Conexion a modulos de alto nivel, incluso si vives fuera de zonas urbanas.
Inversion mas accesible que una capacitacion tradicional.
En el contexto chileno, un programa de liderazgo nacional debe adaptarse a la cultura chilena:
Jerarquias marcadas.
Colaboradores diversos.
Hibrido presencial-remoto.
Por eso, una formacion de lideres debe ser mas que un curso grabado.
Que debe incluir un buen curso de liderazgo empresarial?
Clases sobre liderazgo adaptativo.
Casos reales adaptados a situaciones chilenas.
Evaluacion individual de estilo de liderazgo.
Interaccion con otros lideres de Chile.
Y lo mas clave: el curso de liderazgo empresarial debe provocar un salto significativo en la practica diaria.
Muchos encargados ascienden sin preparacion, y eso duele a sus colaboradores. Un buen capacitacion de liderazgo online puede ser la clave entre inspirar y dirigir o imponer.
JuniorShido
18 Sep 25 at 12:47 pm
I would like to thank you for the efforts you’ve put in writing this site.
I am hoping to check out the same high-grade content by you in the future
as well. In truth, your creative writing abilities has inspired me to get my very
own site now 😉
نظرات دانشجویان رشته روانشناسی نی نی سایت
18 Sep 25 at 12:47 pm
buy coke in telegram buy coke in telegram
prague-drugs-360
18 Sep 25 at 12:47 pm
Cash Ultimate online KZ
Davidfes
18 Sep 25 at 12:49 pm
Just desire to say your article is as astounding.
The clarity in your put up is simply nice and that i could
suppose you are knowledgeable in this subject. Well along with your permission allow me to snatch your feed to keep updated with coming near near post.
Thanks 1,000,000 and please keep up the gratifying work.
emagazineworld
18 Sep 25 at 12:50 pm
buy drugs in prague https://cocaine-prague-shop.com
prague-drugs-398
18 Sep 25 at 12:50 pm
Hello there! I know this is kinda off topic but I was wondering if you knew where
I could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and
I’m having trouble finding one? Thanks a lot!
هزینه شهریه دانشگاه غیر انتفاعی ۱۴۰۴
18 Sep 25 at 12:52 pm
Сегодня cs обмен скинов — это не просто часть игрового процесса, а своего рода мини-индустрия, где важны внимательность, понимание цен и умение выстраивать доверие с другими игроками. В этой статье мы разберём, как безопасно и эффективно пользоваться системой трейдов в CS2, какие платформы наиболее удобны и на что стоит обратить внимание, чтобы не нарваться на мошенников.
ShawnNab
18 Sep 25 at 12:53 pm
Chest Hunter slot rating
JoshuaStism
18 Sep 25 at 12:53 pm
сайт микрозаймов [url=www.zaimy-16.ru/]www.zaimy-16.ru/[/url] .
zaimi_hgMi
18 Sep 25 at 12:54 pm
Казино Leonbets слот Christmas Infinite Gifts
BrandonLum
18 Sep 25 at 12:55 pm
обмен скинов кс2 в Counter-Strike 2 становится все более популярным способом не только обновить свою коллекцию, но и выгодно провести время внутри игрового комьюнити. Игроки используют трейды, чтобы обмениваться редкими предметами, находить именно те скины, о которых давно мечтали, или менять ненужное оружие на что-то более ценное. Благодаря этому внутриигровая экономика развивается и приобретает черты полноценного рынка с собственными правилами и стратегиями.
ShawnNab
18 Sep 25 at 12:55 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2best
bs2best.at blacksprut marketplace Official
CharlesNarry
18 Sep 25 at 12:57 pm
займы все онлайн [url=zaimy-16.ru]zaimy-16.ru[/url] .
zaimi_vpMi
18 Sep 25 at 1:01 pm
список займов онлайн [url=https://zaimy-13.ru/]https://zaimy-13.ru/[/url] .
zaimi_yyKt
18 Sep 25 at 1:05 pm
prague drugs cocain in prague from peru
prague-drugs-7
18 Sep 25 at 1:05 pm
микрозаймы онлайн [url=zaimy-12.ru]микрозаймы онлайн[/url] .
zaimi_vkSt
18 Sep 25 at 1:05 pm
browse around this site
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
browse around this site
18 Sep 25 at 1:06 pm
kraken darknet ссылка kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
18 Sep 25 at 1:06 pm
Публикация предлагает читателю не просто информацию, а инструменты для анализа и саморазвития. Мы стимулируем критическое мышление, предлагая различные точки зрения и призывая к самостоятельному поиску решений.
Узнай первым! – https://nextdunyasi.com/?attachment_id=4966
Roberttuh
18 Sep 25 at 1:09 pm
weed in prague buy xtc prague
prague-drugs-736
18 Sep 25 at 1:10 pm
https://wirtube.de/a/gabravef0v/video-channels
RobertSnova
18 Sep 25 at 1:10 pm
займы онлайн [url=https://zaimy-16.ru/]займы онлайн[/url] .
zaimi_kwMi
18 Sep 25 at 1:11 pm
Thank you for the auspicious writeup. It in fact was a amusement account it.
Look advanced to far added agreeable from you!
However, how can we communicate?
365 הימורים על פוליטיקה
18 Sep 25 at 1:11 pm
купить аттестат об окончании 9 классов [url=educ-ua19.ru]купить аттестат об окончании 9 классов[/url] .
Diplomi_udml
18 Sep 25 at 1:13 pm
займер ру [url=http://zaimy-16.ru]займер ру[/url] .
zaimi_jcMi
18 Sep 25 at 1:14 pm
Сегодня трейд скинов кс2 — это не просто часть игрового процесса, а своего рода мини-индустрия, где важны внимательность, понимание цен и умение выстраивать доверие с другими игроками. В этой статье мы разберём, как безопасно и эффективно пользоваться системой трейдов в CS2, какие платформы наиболее удобны и на что стоит обратить внимание, чтобы не нарваться на мошенников.
ShawnNab
18 Sep 25 at 1:15 pm
Hello, I desire to subscribe for this blog to obtain newest updates, thus where can i do it please assist.
casino R7 зеркало
18 Sep 25 at 1:17 pm
Графитовые и угольные щетки для электроинструмента. Большой выбор, надёжность и долговечность. Подходят для дрелей, болгарок, перфораторов и другого оборудования.
schetki-364
18 Sep 25 at 1:19 pm
buy drugs in prague https://cocaine-prague-shop.com
prague-drugs-188
18 Sep 25 at 1:20 pm
buy coke in telegram https://cocaine-prague-shop.com
prague-drugs-170
18 Sep 25 at 1:21 pm
где купить диплом среднем [url=http://educ-ua19.ru/]где купить диплом среднем[/url] .
Diplomi_vyml
18 Sep 25 at 1:21 pm