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!
https://saludfrontera.com/# SaludFrontera
JeremyBip
13 Sep 25 at 5:18 am
экстренный вывод из запоя
vivod-iz-zapoya-orenburg009.ru
вывод из запоя круглосуточно оренбург
narkologiyaorenburgNeT
13 Sep 25 at 5:18 am
электрокарнизы [url=http://karnizy-s-elektroprivodom-cena.ru]электрокарнизы[/url] .
karnizi s elektroprivodom cena_bykr
13 Sep 25 at 5:19 am
888starz bet скачать https://culturadom.fr/2025/09/03/888starz-oformlenie-a-eshche-verbovoe-vozmite-dolzhnostnoy-zhurnal-igornyy-dom-888-starz-gde-segodnya-nuzhno-zakachivat-i-tantsevat/
888starzapp
13 Sep 25 at 5:19 am
электрические гардины [url=www.avtomaticheskie-karnizy.ru]www.avtomaticheskie-karnizy.ru[/url] .
avtomaticheskie karnizi_ueSa
13 Sep 25 at 5:19 am
карниз электро [url=www.elektro-karniz77.ru]www.elektro-karniz77.ru[/url] .
elektro karniz_ilSl
13 Sep 25 at 5:19 am
техникум это какое образование украина [url=https://www.educ-ua10.ru]техникум это какое образование украина[/url] .
Diplomi_awKl
13 Sep 25 at 5:20 am
явно не 15-ти минутка, почитайте отзывы в соответвующей теме. Качество товара на высоте у нас всегда .
https://igli.me/kohlsxcbernhard
Оплатил в среду, жду посылочку, посмотрим как что.
Harryunsag
13 Sep 25 at 5:22 am
Мы практикуем минимально достаточную фармакотерапию и предсказуемые алгоритмы. Это означает — никакой полипрагмазии, никаких «универсальных капельниц», никакого «сделаем всё сразу». Сначала — безопасность (дыхание, гемодинамика, сознание), затем — управляемая детоксикация с коррекцией водно-электролитного баланса и седацией только по показаниям, после — «тихий режим» и восстановление сна, и уже на этом фоне — поведенческие навыки, работа с триггерами, переговоры с семьёй о правилах поддержки. Такой порядок убирает хаос, снижает тревогу и делает ремиссию не подвигом, а реальной рутиной.
Изучить вопрос глубже – [url=https://narkologicheskaya-klinika-ryazan14.ru/]наркологические клиники алкоголизм в рязани[/url]
AnthonyRah
13 Sep 25 at 5:22 am
электрокарнизы москва [url=http://www.elektrokarniz-cena.ru]электрокарнизы москва[/url] .
elektrokarniz cena_vnPL
13 Sep 25 at 5:22 am
Мы практикуем минимально достаточную фармакотерапию и предсказуемые алгоритмы. Это означает — никакой полипрагмазии, никаких «универсальных капельниц», никакого «сделаем всё сразу». Сначала — безопасность (дыхание, гемодинамика, сознание), затем — управляемая детоксикация с коррекцией водно-электролитного баланса и седацией только по показаниям, после — «тихий режим» и восстановление сна, и уже на этом фоне — поведенческие навыки, работа с триггерами, переговоры с семьёй о правилах поддержки. Такой порядок убирает хаос, снижает тревогу и делает ремиссию не подвигом, а реальной рутиной.
Подробнее тут – https://narkologicheskaya-klinika-ryazan14.ru/narkolog-ryazan-telefon
AnthonyRah
13 Sep 25 at 5:22 am
http://curabharatusa.com/# medicine online india
CarlosPreom
13 Sep 25 at 5:23 am
карниз для штор электрический [url=https://karnizy-s-elektroprivodom-cena.ru/]карниз для штор электрический[/url] .
karnizi s elektroprivodom cena_hbkr
13 Sep 25 at 5:24 am
карнизы с электроприводом [url=https://elektrokarniz-cena.ru/]карнизы с электроприводом[/url] .
elektrokarniz cena_xoPL
13 Sep 25 at 5:26 am
электрокарниз москва [url=www.avtomaticheskie-karnizy-dlya-shtor.ru/]электрокарниз москва[/url] .
avtomaticheskie karnizi dlya shtor_vaOr
13 Sep 25 at 5:27 am
электрокарниз недорого [url=https://www.elektrokarniz-cena.ru]https://www.elektrokarniz-cena.ru[/url] .
elektrokarniz cena_nwPL
13 Sep 25 at 5:31 am
What’s Going down i’m new to this, I stumbled upon this I have found It absolutely helpful and
it has aided me out loads. I am hoping to contribute
& help different customers like its helped me. Good job.
dewascatter link alternatif
13 Sep 25 at 5:31 am
canadian pharmacy store: TrueNorth Pharm – reliable canadian pharmacy reviews
Teddyroowl
13 Sep 25 at 5:33 am
https://russpain.com/
Roberttow
13 Sep 25 at 5:33 am
электрические гардины [url=https://avtomaticheskie-karnizy-dlya-shtor.ru/]электрические гардины[/url] .
avtomaticheskie karnizi dlya shtor_bdOr
13 Sep 25 at 5:33 am
Wow, math serves as tһe base pillar of primary education, assisting youngsters іn dimensional
analysis in building careers.
Οһ dear, withoսt strong maths at Junior College, regarⅾless leading
school youngsters mіght struggle іn high
school equations, tһerefore cultivate tһat immediɑtely leh.
Catholic Junior College supplies а values-centered education rooted іn compassion аnd
reality, creating ɑ welcoming neighborhood wһere students
flourish academically аnd spiritually. Ꮤith a concentrate on holistic growth, the college offеrs robust programs in humanities аnd sciences, assisted by caring
coaches who influence lоng-lastinglearning. Itѕ vibrant co-curricular scene,
including sports аnd arts, promotes teamwork ɑnd self-discovery іn an encouraging environment.
Opportunities for neighborhood service аnd global exchanges
develop compassion аnd worldwide ⲣoint of views amоngst students.
Alumni typically Ƅecome compassionate leaders, equipped to make
meaningful contributions tօ society.
River Valley Ꮋigh School Junior College perfectly incorporates
multilingual education ԝith a strong dedication tߋ ecological stewardship,
supporting eco-conscious leaders ѡho havе sharp global point of views and a devotion tⲟ sustainable practices іn an increasingly interconnected ᴡorld.
Thе school’s innovative labs, green technology centers, ɑnd environmentally
friendly campus designs support pioneering knowing іn sciences, humanities, ɑnd environmental studies, motivating trainees
tο engage in hands-on experiments and ingenious solutions to real-ѡorld difficulties.
Cuptural immersion programs, ѕuch as language exchanges and heritage journeys,
integrated ᴡith neighborhood service projects
concentrated ᧐n conservation, enhance students’ compassion, cultural
intelligence, аnd uѕeful skills f᧐r fazvorable social еffect.
Ԝithin a unified and helpful community, participation іn sports teams, arts societies, ɑnd leadership workshops
promotes physical ᴡell-bеing, team effort, and strength, creating healthy
individuals ɑll set for future ventures. Graduates fгom River Valley Higһ School Junior College are preferably positioned fօr success in leading universities аnd professions, embodying tһe school’ѕ core values ᧐f fortitude,
cultural acumen, ɑnd a proactive approach tо international sustainability.
Goodness, гegardless іf establishment remains higһ-end, mathematics acts ⅼike the
decisive subject to developing poise іn calculations.
Oһ no, primary mathematics teaches practical applications ⅼike financial
planning, so mɑke ѕure уour child grasps
іt correctly starting young age.
Listen up, composed pom ρi pi, math remains one fгom the leading subjects in Junior
College, establishing base f᧐r A-Level hiɡher calculations.
Вesides to institution amenities, focus սpon math tо
prevent common pitfalls ѕuch as careless blunders іn assessments.
Eh eh, calm pom ⲣi pi, math remaіns part from the hіghest
subjects at Junior College, building base fоr
Α-Level calculus.
Βesides from establishment facilities, emphasize ߋn math to ѕtop frequent errors including careless mistakes ɑt assessments.
Α-level distinctions іn core subjects ⅼike Math set yⲟu apart from the
crowd.
Folks, kiasu style ⲟn lah, sopid primary math results to superior scientific
grasp ρlus construction dreams.
Οh, math serves as tһe base block ᧐f primary schooling, aiding kids ԝith geometric
thinking for building careers.
My web pɑge – Jurong Pioneer Junior College
Jurong Pioneer Junior College
13 Sep 25 at 5:34 am
Вывод из запоя в Рязани является востребованной медицинской услугой, направленной на стабилизацию состояния пациента после длительного употребления алкоголя. Специалисты применяют современные методы детоксикации, позволяющие быстро и безопасно восстановить жизненно важные функции организма, снизить проявления абстинентного синдрома и предотвратить осложнения. Процесс лечения осуществляется в клинических условиях под постоянным наблюдением врачей.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-ryazan14.ru/]вывод из запоя на дому в рязани[/url]
ScottieWah
13 Sep 25 at 5:34 am
автоматический карниз для штор [url=www.karnizy-s-elektroprivodom-cena.ru/]www.karnizy-s-elektroprivodom-cena.ru/[/url] .
karnizi s elektroprivodom cena_bukr
13 Sep 25 at 5:34 am
кракен onion сайт 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
13 Sep 25 at 5:35 am
электрические гардины [url=www.avtomaticheskie-karnizy.ru/]www.avtomaticheskie-karnizy.ru/[/url] .
avtomaticheskie karnizi_rySa
13 Sep 25 at 5:35 am
карниз с приводом для штор [url=http://elektro-karniz77.ru/]http://elektro-karniz77.ru/[/url] .
elektro karniz_zrSl
13 Sep 25 at 5:35 am
Every weekend i used to go to see this web site, for the
reason that i want enjoyment, for the reason that this this web
page conations really good funny data too.
Zevrio Capiture
13 Sep 25 at 5:36 am
«Как отмечает врач-нарколог Павел Викторович Зайцев, «эффективность терапии во многом зависит от своевременного обращения, поэтому откладывать визит в клинику опасно»».
Подробнее можно узнать тут – [url=https://narkologicheskaya-klinika-sankt-peterburg14.ru/]наркологическая клиника наркологический центр в санкт-петербурге[/url]
Romanronse
13 Sep 25 at 5:37 am
Заказать диплом любого ВУЗа!
Мы предлагаемвыгодно заказать диплом, который выполнен на оригинальной бумаге и заверен печатями, водяными знаками, подписями должностных лиц. Документ пройдет лубую проверку, даже при помощи специальных приборов. Решайте свои задачи быстро и просто с нашими дипломами- [url=http://heebig.com/gde-kupit-diplom-v-2025-godu-bez-riska-34/]heebig.com/gde-kupit-diplom-v-2025-godu-bez-riska-34[/url]
Jariorfgj
13 Sep 25 at 5:38 am
карнизы с электроприводом [url=www.avtomaticheskie-karnizy.ru/]карнизы с электроприводом[/url] .
avtomaticheskie karnizi_txSa
13 Sep 25 at 5:39 am
электрокарнизы цена [url=http://elektro-karniz77.ru]http://elektro-karniz77.ru[/url] .
elektro karniz_lfSl
13 Sep 25 at 5:39 am
карниз с электроприводом [url=https://karnizy-s-elektroprivodom-cena.ru/]карниз с электроприводом[/url] .
karnizi s elektroprivodom cena_yakr
13 Sep 25 at 5:40 am
электрические карнизы купить [url=https://elektro-karniz77.ru/]https://elektro-karniz77.ru/[/url] .
elektro karniz_pfSl
13 Sep 25 at 5:42 am
электрокарнизы москва [url=http://avtomaticheskie-karnizy.ru/]http://avtomaticheskie-karnizy.ru/[/url] .
avtomaticheskie karnizi_wtSa
13 Sep 25 at 5:42 am
Does your website have a contact page? I’m having a tough time locating it but, I’d
like to send you an e-mail. I’ve got some creative ideas for your blog you might be interested in hearing.
Either way, great site and I look forward to seeing it improve
over time.
online casino blackjack
13 Sep 25 at 5:42 am
электрокарнизы москва [url=http://avtomaticheskie-karnizy-dlya-shtor.ru]электрокарнизы москва[/url] .
avtomaticheskie karnizi dlya shtor_ipOr
13 Sep 25 at 5:42 am
mostbet for pc [url=https://www.mostbet12008.ru]https://www.mostbet12008.ru[/url]
mostbet_sjer
13 Sep 25 at 5:44 am
Привет всем бандиты? как дела у вас?
https://bio.site/ifeboydyfoof
все ровно мира вам ! и процветания
Harryunsag
13 Sep 25 at 5:45 am
электрические гардины [url=https://karnizy-s-elektroprivodom-cena.ru/]электрические гардины[/url] .
karnizi s elektroprivodom cena_mkkr
13 Sep 25 at 5:45 am
электрокарниз [url=http://elektrokarniz-cena.ru/]электрокарниз[/url] .
elektrokarniz cena_scPL
13 Sep 25 at 5:46 am
электрокарнизы для штор купить [url=https://www.avtomaticheskie-karnizy-dlya-shtor.ru]электрокарнизы для штор купить[/url] .
avtomaticheskie karnizi dlya shtor_xuOr
13 Sep 25 at 5:46 am
натяжные потолки м2 [url=https://natyazhnye-potolki-lipeck-1.ru]натяжные потолки м2[/url] .
natyajnie potolki_mpol
13 Sep 25 at 5:46 am
электрокарнизы для штор купить в москве [url=elektrokarniz-cena.ru]электрокарнизы для штор купить в москве[/url] .
elektrokarniz cena_prPL
13 Sep 25 at 5:49 am
What a data of un-ambiguity and preserveness of precious knowledge about unexpected
feelings.
led signage
13 Sep 25 at 5:50 am
электрические гардины [url=www.karnizy-s-elektroprivodom-cena.ru/]электрические гардины[/url] .
karnizi s elektroprivodom cena_rokr
13 Sep 25 at 5:51 am
Выезд на дом
Узнать больше – [url=https://narkologicheskaya-pomoshch-orekhovo-zuevo7.ru/]центр наркологической помощи[/url]
Donalddoume
13 Sep 25 at 5:51 am
карниз с приводом для штор [url=www.elektrokarniz-cena.ru/]www.elektrokarniz-cena.ru/[/url] .
elektrokarniz cena_ygPL
13 Sep 25 at 5:52 am
https://www.pinterest.com/candetoxblend/
Afrontar un examen de drogas ya no tiene que ser una incertidumbre. Existe una fórmula confiable que actúa rápido.
El secreto está en su fórmula canadiense, que sobrecarga el cuerpo con proteínas, provocando que la orina neutralice los rastros químicos. Esto asegura una muestra limpia en solo 2 horas, con ventana segura para rendir tu test.
Lo mejor: es un plan de emergencia, diseñado para quienes enfrentan pruebas imprevistas.
Miles de clientes confirman su efectividad. Los paquetes llegan sin logos, lo que refuerza la seguridad.
Cuando el examen no admite errores, esta solución es la respuesta que estabas buscando.
JuniorShido
13 Sep 25 at 5:54 am
скачать мостбет кг [url=https://mostbet12006.ru]https://mostbet12006.ru[/url]
mostbet_iaKl
13 Sep 25 at 5:55 am
курсовая работа за деньги курсовые работы в москве
kursovaya-rabota-212
13 Sep 25 at 5:55 am