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!
من همیشه فکر میکردم نخ فقط نخ
دیگه! ولی الان متوجه شدم نخ چای کیسهای
با نخ سرکیسهدوزی کلی فرق داره.
یکی روی سلامت و دمآوری تاثیر میذاره، اون یکی روی استحکام بستهبندی.
واقعا هر دوشون مهمن و نباید
دست کم گرفته بشن.
80e education loan limit
21 Oct 25 at 10:07 am
лучшие сервисы виртуальных номеров
Jaredvaf
21 Oct 25 at 10:09 am
купить диплом в северске [url=rudik-diplom4.ru]rudik-diplom4.ru[/url] .
Diplomi_txOr
21 Oct 25 at 10:09 am
https://groups.google.com/g/candetoxblend/c/nYWf8CoaQqE
Pasar una prueba de orina puede ser un momento critico. Por eso, existe un suplemento innovador creada con altos estandares.
Su receta unica combina minerales, lo que estimula tu organismo y neutraliza temporalmente los trazas de alcaloides. El resultado: una prueba sin riesgos, lista para ser presentada.
Lo mas valioso es su ventana de efectividad de 4 a 5 horas. A diferencia de otros productos, no promete milagros, sino una herramienta puntual que funciona cuando lo necesitas.
Estos fórmulas están diseñados para colaborar a los consumidores a depurar su cuerpo de componentes no deseadas, especialmente aquellas relacionadas con el consumo de cannabis u otras sustancias ilícitas.
Un buen detox para examen de pipí debe ofrecer resultados rápidos y efectivos, en gran cuando el tiempo para limpiarse es limitado. En el mercado actual, hay muchas opciones, pero no todas prometen un proceso seguro o fiable.
Qué funciona un producto detox? En términos simples, estos suplementos funcionan acelerando la eliminación de metabolitos y toxinas a través de la orina, reduciendo su nivel hasta quedar por debajo del límite de detección de ciertos tests. Algunos funcionan en cuestión de horas y su acción puede durar entre 4 a 6 horas.
Resulta fundamental combinar estos productos con adecuada hidratación. Beber al menos par litros de agua por jornada antes y después del uso del detox puede mejorar los beneficios. Además, se aconseja evitar alimentos pesados y bebidas azucaradas durante el proceso de uso.
Los mejores productos de purga para orina incluyen ingredientes como extractos de naturales, vitaminas del complejo B y minerales que favorecen el funcionamiento de los sistemas y la función hepática. Entre las marcas más populares, se encuentran aquellas que tienen certificaciones sanitarias y estudios de resultado.
Para usuarios frecuentes de cannabis, se recomienda usar detoxes con tiempos de acción largas o iniciar una preparación previa. Mientras más prolongada sea la abstinencia, mayor será la efectividad del producto. Por eso, combinar la organización con el uso correcto del producto es clave.
Un error común es pensar que todos los detox actúan igual. Existen diferencias en dosis, sabor, método de uso y duración del impacto. Algunos vienen en formato líquido, otros en cápsulas, y varios combinan ambos.
Además, hay productos que incluyen fases de preparación o purga previa al día del examen. Estos programas suelen sugerir abstinencia, buena alimentación y descanso recomendado.
Por último, es importante recalcar que todo detox garantiza 100% de éxito. Siempre hay variables biológicas como metabolismo, frecuencia de consumo, y tipo de examen. Por ello, es vital seguir las instrucciones del fabricante y no descuidarse.
Miles de postulantes ya han comprobado su efectividad. Testimonios reales mencionan envios en menos de 24 horas.
Si necesitas asegurar tu resultado, esta alternativa te ofrece tranquilidad.
JuniorShido
21 Oct 25 at 10:10 am
купить диплом техникума новосибирск [url=http://frei-diplom12.ru]купить диплом техникума новосибирск[/url] .
Diplomi_iuPt
21 Oct 25 at 10:11 am
fantastic post, very informative. I wonder why the opposite specialists of this sector don’t realize this.
You should proceed your writing. I am confident, you have
a huge readers’ base already!
extra boost
21 Oct 25 at 10:12 am
Write more, thats all I have to say. Literally,
it seems as though you relied on the video to make your point.
You obviously know what youre talking about, why throw away
your intelligence on just posting videos to your site when you
could be giving us something enlightening to read?
slot gacor
21 Oct 25 at 10:12 am
виртуальный номер для соцсетей
Antoniooscig
21 Oct 25 at 10:13 am
рейтинг компаний по продвижению сайтов [url=http://www.luchshie-digital-agencstva.ru]рейтинг компаний по продвижению сайтов[/url] .
lychshie digital agentstva_xqoi
21 Oct 25 at 10:14 am
kraken зеркало
кракен vk2
JamesDaync
21 Oct 25 at 10:14 am
В наше время проблема зависимости становится все более актуальной. Зачастую люди нуждаются в срочной помощи, и именно в таких случаях нарколог на дом предоставит необходимую помощь. Выездной нарколог предоставляет медицинскую помощь для людей с зависимостями, включая очистку организма у пациента на дому. Сайт vivod-iz-zapoya-vladimir027.ru предлагает услуги профессионалов, которые могут выехать к вам в любое время. Консультация нарколога поможет оценить состояние пациента и определить необходимое лечение зависимости. Анонимное лечение и восстановление для зависимых — ключевые моменты, которые обеспечивают комфорт и безопасность. Прием врача на дому уменьшает стрессовую нагрузку на пациента, что имеет решающее значение для успешного выздоровления.
vivodzapojvladimirNeT
21 Oct 25 at 10:14 am
пин ап загрузка на андроид [url=http://pinup5007.ru]пин ап загрузка на андроид[/url]
pin_up_uz_nusr
21 Oct 25 at 10:15 am
продвижение сайта топ поиска [url=http://reiting-runeta-seo.ru/]http://reiting-runeta-seo.ru/[/url] .
reiting ryneta seo_kima
21 Oct 25 at 10:16 am
оптимизация и seo продвижение сайтов москва [url=https://www.seo-prodvizhenie-reiting-kompanij.ru]https://www.seo-prodvizhenie-reiting-kompanij.ru[/url] .
seo prodvijenie reiting kompanii_lkst
21 Oct 25 at 10:16 am
виртуальный номер для Facebook
Timothydrart
21 Oct 25 at 10:18 am
продвижение сайтов в топ 10 москва [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]продвижение сайтов в топ 10 москва[/url] .
agentstvo poiskovogo prodvijeniya_tdKt
21 Oct 25 at 10:19 am
Этот информативный материал предлагает содержательную информацию по множеству задач и вопросов. Мы призываем вас исследовать различные идеи и факты, обобщая их для более глубокого понимания. Наша цель — сделать обучение доступным и увлекательным.
Подробнее – https://fands-llc.biz/index.php/2024/01/03/hello-world
WilliambEw
21 Oct 25 at 10:19 am
прием СМС для регистрации
Antoniomerty
21 Oct 25 at 10:19 am
купить диплом швеи [url=https://rudik-diplom4.ru]купить диплом швеи[/url] .
Diplomi_zkOr
21 Oct 25 at 10:20 am
купить аттестат за 11 класс [url=https://rudik-diplom10.ru]купить аттестат за 11 класс[/url] .
Diplomi_vwSa
21 Oct 25 at 10:20 am
как купить проведенный диплом отзывы [url=http://frei-diplom4.ru]http://frei-diplom4.ru[/url] .
Diplomi_opOl
21 Oct 25 at 10:20 am
виртуальный номер для Telegram
Timothydrart
21 Oct 25 at 10:20 am
лучшие сервисы виртуальных номеров
Antoniomerty
21 Oct 25 at 10:21 am
Чем отличаются промокоды букмекерской конторы 1xBet особенными? Какие нюансы стоит понимать о кодах, чтобы извлечь максимальную выгоду от их активации? И, наконец, какие еще интересные моменты в акционной политике этой конторы, на которые стоит заметить, если вы планируете ставить с бонусами. Промокод на 1xBet (актуален в 2026 году, бонус 100%) можно найти по этой ссылке: как получить промокод 1xbet.
Jasonbrado
21 Oct 25 at 10:21 am
В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
Ознакомиться с полной информацией – https://mbn-nadstaga.pl/witaj-swiecie
Georgejet
21 Oct 25 at 10:22 am
топ сео компаний [url=https://reiting-seo-kompaniy.ru/]топ сео компаний[/url] .
reiting seo kompanii_uuon
21 Oct 25 at 10:22 am
кракен
kraken vpn
JamesDaync
21 Oct 25 at 10:24 am
виртуальный номер для WhatsApp
Jaredvaf
21 Oct 25 at 10:27 am
купить диплом автомеханика [url=rudik-diplom3.ru]купить диплом автомеханика[/url] .
Diplomi_hfei
21 Oct 25 at 10:27 am
виртуальный номер для Instagram
Jaredvaf
21 Oct 25 at 10:28 am
Wah, math acts like tһe foundation pillar օf primary education, assisting children іn geometric analysis tߋ architecture routes.
Oh dear, lacking robust maths аt Junior College, no matter tοp school youngsters may struggle ᴡith һigh school calculations, so
build tһis now leh.
St. Joseph’s Institution Junior College embodies Lasallian traditions, stressing faith,
service, ɑnd intellectual pursuit. Integrated programs ᥙsе seamless development ѡith concentrate
οn bilingualism аnd development. Facilities like performing
arts centers improve innovative expression. Global immersions аnd research
opportunities widen perspectives. Graduates ɑгe compassionjate achievers,
standing օut in universities and professions.
Anglo-Chinese School (Independent) Junior College delivers аn enriching education deeply rooted іn faith, wherе intellectual exploration is harmoniously balanced ԝith core ethical concepts,
guiding students tοward ending up Ƅeing empathetic аnd
rеsponsible international people geared up to attend to complex social challenges.
Ꭲhе school’s distinguished International
Baccalaureate Diploma Programme promotes advanced critical thinking, гesearch study skills,
and interdisciplinary knowing, reinforced Ƅy extraordinary resources ⅼike devoted
innovation hubs and professional faculty ԝho mentor trainees іn attaining academic difference.
Α broad spectrum ᧐f co-curricular offerings, fгom
innovative robotics cⅼubs that encourage technological creativity tօ chamber orchestra that refine musical skills, enables
trainees tߋ find and fine-tune tһeir special abilities in а
supportive and revitalizing environment. Вy incorporating
service learning initiatives, sսch as community outreach projects ɑnd volunteer programs Ƅoth locally aand globally, tһе college cultivates ɑ strong sense of social responsibility, compassion,ɑnd active citizenship amongst itѕ trainee
body. Graduates ᧐f Anglo-Chinese School (Independent) Junior
College ɑre incredibly ᴡell-prepared fⲟr entry intο elite universities worldwide, Ьring with them a distinguished
legacy оf scholastic excellence, personal stability, аnd a commitment to
lⲟng-lasting knowing and contribution.
Mums and Dads, fearful ߋf losing mode engaged lah, solid primary maths leads f᧐r improved science understanding аnd tech goals.
Avoid mess аrоund lah, pair а gooԀ Junior College with mathematics
proficiency fоr guarantee higһ A Levels resᥙlts and seamless
shifts.
Folks, worry ɑbout the gap hor, math groundwork іѕ critical in Junior College in understanding
figures, essential іn current online economy.
Goodness, no matter ԝhether school remains atas, maths is
tһe critical subject to building confidence ԝith
calculations.
In Singapore’s kiasu culture, excelling іn JC Ꭺ-levels mеаns you’rе ahead in thе rat
race for gooԁ jobs.
Oh no, primary math educates real-ԝorld uѕeѕ likе money management, tһerefore guarantee уour youngster masters tһis properly beginning уoung age.
Hey hey, steady pom рі pi, mathematics proves ɑmong іn the tօр subjects at Junior
College, buildiing groundwork іn A-Level calculus.
Als᧐ visit my website :: Kaizenare math tuition
Kaizenare math tuition
21 Oct 25 at 10:29 am
Artikel ini sangat informatif dan menjelaskan dengan detail mengenai KUBET
serta Situs Judi Bola Terlengkap. Saya suka bagaimana penulis menguraikan topik
Situs Parlay Resmi dan Situs Parlay Gacor secara jelas
dan berimbang. Penjelasan tentang Situs Mix Parlay juga menambah wawasan saya tentang tren hiburan online
yang terus berkembang. Tambahan informasi seperti situs parlay,
kubet login, dan toto macau benar-benar membuat artikel ini semakin bernilai.
kubet login
21 Oct 25 at 10:30 am
pin up kripto orqali yechish [url=https://pinup5007.ru]https://pinup5007.ru[/url]
pin_up_uz_kasr
21 Oct 25 at 10:30 am
kraken vk3
кракен маркетплейс
JamesDaync
21 Oct 25 at 10:30 am
В этой публикации мы сосредоточимся на интересных аспектах одной из самых актуальных тем современности. Совмещая факты и мнения экспертов, мы создадим полное представление о предмете, которое будет полезно как новичкам, так и тем, кто глубоко изучает вопрос.
Исследовать вопрос подробнее – https://patioscenes.com/preparing-gazebo-summer/preparing-gazebo-summer-2
Harryhutty
21 Oct 25 at 10:31 am
Wow, that’s what I was seeking for, what a material! existing here at this weblog, thanks admin of this site.
Find Out More
21 Oct 25 at 10:31 am
аренда виртуального номера
Antoniooscig
21 Oct 25 at 10:31 am
купить диплом техника [url=http://rudik-diplom11.ru/]купить диплом техника[/url] .
Diplomi_yoMi
21 Oct 25 at 10:31 am
купить диплом с занесением в реестр барнаул [url=http://frei-diplom5.ru]купить диплом с занесением в реестр барнаул[/url] .
Diplomi_iuPa
21 Oct 25 at 10:31 am
прием СМС для регистрации
Antoniooscig
21 Oct 25 at 10:32 am
В этой статье-обзоре мы соберем актуальную информацию и интересные факты, которые освещают важные темы. Читатели смогут ознакомиться с различными мнениями и подходами, что позволит им расширить кругозор и глубже понять обсуждаемые вопросы.
Посмотреть подробности – https://edx.amamedia.org/product/campground-reservation-4
Ernierop
21 Oct 25 at 10:34 am
Awesome post! I was currently browsing for ways to receive free credits on AdultWork.
I came across this method that really works. You can test it on this website.
It’s completely working and no verification is needed.
Thanks for sharing such a useful article!
AdultWork Free Credits
21 Oct 25 at 10:34 am
seo продвижение в интернете москва [url=reiting-seo-agentstv-moskvy.ru]seo продвижение в интернете москва[/url] .
reiting seo agentstv moskvi_uiMl
21 Oct 25 at 10:35 am
рейтинг seo [url=www.reiting-seo-agentstv.ru]www.reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_ersa
21 Oct 25 at 10:36 am
seo agency ranking [url=https://reiting-seo-kompaniy.ru]https://reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_jqon
21 Oct 25 at 10:37 am
Купить виртуальный номер
Jaredvaf
21 Oct 25 at 10:37 am
купить диплом в орске [url=www.rudik-diplom10.ru]купить диплом в орске[/url] .
Diplomi_guSa
21 Oct 25 at 10:37 am
kraken РФ
kraken вход
JamesDaync
21 Oct 25 at 10:37 am
по позициям продвижение сайтов сео [url=http://reiting-runeta-seo.ru/]http://reiting-runeta-seo.ru/[/url] .
reiting ryneta seo_lqma
21 Oct 25 at 10:38 am
сео продвижение сайтов топ [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/[/url] .
agentstvo poiskovogo prodvijeniya_qnKt
21 Oct 25 at 10:38 am