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!
перепланировка офиса [url=http://soglasovanie-pereplanirovki-kvartiry17.ru/]перепланировка офиса[/url] .
soglasovanie pereplanirovki kvartiri _cfol
12 Sep 25 at 11:08 am
https://bluepilluk.com/# sildenafil tablets online order UK
Carrollalery
12 Sep 25 at 11:09 am
I know this if off topic but I’m looking into starting my own weblog and was curious
what all is needed to get set up? I’m assuming having a blog
like yours would cost a pretty penny? I’m not very internet savvy so
I’m not 100% positive. Any recommendations or advice would be greatly appreciated.
Kudos
Feel free to surf to my blog; sports injury urgent care Clermont
sports injury urgent care Clermont
12 Sep 25 at 11:11 am
I love looking through a post that will make people think.
Also, thanks for allowing for me to comment!
Free local listing
12 Sep 25 at 11:12 am
Казино Leonbets слот Book of Goddess
Josephhet
12 Sep 25 at 11:13 am
Folks, competitive approach օn lah, solid primary maths results in Ьetter science understanding аnd construction goals.
Wow, maths acts ⅼike the base block іn primary education, helping youngsters ԝith dimensional
thinking tօ architecture routes.
Tampines Meridian Junior College, fгom a vibrant merger, provіԀes innovative education іn drama and Malay language electives.
Innovative centers support diverse streams, including commerce.
Talent development ɑnd abroad programs foster leadership ɑnd cultural awareness.
Α caring community encourages compassion ɑnd resilience.
Trainees ɑre successful in holistic advancement, ցotten ready for global difficulties.
Jurong Pioneer Junior College, established tһrough the thoughtful merger of Jurong Junior College аnd Pioneer
Junior College, pгovides a proghressive and future-orientededucation tһat places a unique focus оn China preparedness,
worldwide company acumen, and cross-cultural engagement tο prepare trainees foг growing in Asia’ѕ dynamic financial landscape.
Тhе college’ѕ dual campuses aге equipped with modern, versatile facilities including specialized commerce simulation spaces, science
development laboratories, ɑnd arts ateliers, ɑll designed to promote practical skills, creativity,
аnd interdisciplinary knowing. Enhancing academic programs arе complemented Ьy worldwide partnerships,
ѕuch as joint jobs ԝith Chinese universities аnd cultural immersion trips, ᴡhich boost students’ linguistic efficiency ɑnd
worldwide outlook. A encouraging ɑnd inclusive
neighborhood environment encourages strength ɑnd management
development tһrough а vast array of co-curricular activities, from
entrepreneurship clubs to sports teams that promote team effort ɑnd determination. Graduates
оf Jurong Pioneer Junior College are extremely ԝell-prepared
for competitive careers, embodying tһe worths
ⲟf care, continuous improvement, ɑnd development that ѕpecify tһe institution’s forward-lօoking values.
Hey hey, composed pom pi pi, maths proves ɑmong in the highest disciplines іn Junior
College, building groundwork to A-Level advanced math.
Аpart from school resources, concentrate ѡith math іn orɗeг to stop
common pitfalls including sloppy errors ɗuring
tests.
Oh, math іs the base pillar of primary education,
helping children fоr spatial thinking tо architecture paths.
Aiyo, mіnus robust math іn Junior College, no matter prestigious establishment youngsters mіght
struggle in next-level algebra, tһerefore develop іt now leh.
Kiasu tuition centers specialize in Math tߋ bost Ꭺ-level scores.
Dо not take lightly lah, link a excellent Junior College plus
maths excellence іn ordeг to ensure elevated Α Levels marks аѕ well as seamless сhanges.
Mums ɑnd Dads, wory аbout the gap hor, math base iѕ vital іn Junior
College fօr grasping data, crucial ᴡithin today’s digital economy.
Ꮪtop by mү web site: kiasu parents secondary
math tuition (Youths.Kcckp.Go.ke)
Youths.Kcckp.Go.ke
12 Sep 25 at 11:13 am
Современный женский https://happywoman.kyiv.ua онлайн-журнал: новости стиля, секреты красоты, идеи для дома, кулинарные рецепты и советы по отношениям. Пространство для вдохновения и развития.
JosephRox
12 Sep 25 at 11:15 am
Мы предлагаем вам подробное руководство, основанное на проверенных источниках и реальных примерах. Каждая часть публикации направлена на то, чтобы помочь вам разобраться в сложных вопросах и применить знания на практике.
Подробнее – https://beacon-india.com/introduction-to-fluid-dynamics-engineer-role-fmk
Mauronom
12 Sep 25 at 11:16 am
заказать перепланировку [url=www.soglasovanie-pereplanirovki-kvartiry17.ru]www.soglasovanie-pereplanirovki-kvartiry17.ru[/url] .
soglasovanie pereplanirovki kvartiri _xfol
12 Sep 25 at 11:17 am
Современный женский https://happywoman.kyiv.ua онлайн-журнал: новости стиля, секреты красоты, идеи для дома, кулинарные рецепты и советы по отношениям. Пространство для вдохновения и развития.
JosephRox
12 Sep 25 at 11:17 am
Современный женский https://happywoman.kyiv.ua онлайн-журнал: новости стиля, секреты красоты, идеи для дома, кулинарные рецепты и советы по отношениям. Пространство для вдохновения и развития.
JosephRox
12 Sep 25 at 11:18 am
Hmm is anyone else encountering problems with the pictures on this blog
loading? I’m trying to figure out if its a problem on my end or if it’s the blog.
Any responses would be greatly appreciated.
casino online
12 Sep 25 at 11:20 am
https://www.dhakaonlineschool.com/page/42
LeonardMed
12 Sep 25 at 11:20 am
сайт 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
12 Sep 25 at 11:20 am
My partner and I absolutely love your blog and find almost all
of your post’s to be precisely what I’m looking
for. Does one offer guest writers to write content for yourself?
I wouldn’t mind composing a post or elaborating on most
of the subjects you write about here. Again, awesome web log!
turkey visa for australian
12 Sep 25 at 11:21 am
magnificent issues altogether, you just received a brand new reader.
What could you suggest about your submit that you simply made
some days in the past? Any sure?
webwinkelkeur
12 Sep 25 at 11:23 am
1win промокод на деньги при пополнении [url=https://www.1win12008.ru]https://www.1win12008.ru[/url]
1win_ufsn
12 Sep 25 at 11:25 am
соглосование [url=www.soglasovanie-pereplanirovki-kvartiry17.ru/]www.soglasovanie-pereplanirovki-kvartiry17.ru/[/url] .
soglasovanie pereplanirovki kvartiri _bpol
12 Sep 25 at 11:26 am
мостбет казино скачать [url=mostbet12006.ru]mostbet12006.ru[/url]
mostbet_ceKl
12 Sep 25 at 11:26 am
Проб НЕТ!
https://www.brownbook.net/business/54231997/лирика-капсулы-где-купить-без-рецепта/
Может еще вернемся.
Miguellag
12 Sep 25 at 11:26 am
https://bluepilluk.shop/# order viagra online safely UK
Carrollalery
12 Sep 25 at 11:28 am
перепланировка и согласование [url=http://www.soglasovanie-pereplanirovki-kvartiry17.ru]http://www.soglasovanie-pereplanirovki-kvartiry17.ru[/url] .
soglasovanie pereplanirovki kvartiri _alol
12 Sep 25 at 11:29 am
https://businesssuitehub.com/
RobertMiz
12 Sep 25 at 11:30 am
Analizador Vibraciones Equilibrado Dinamico
Balanset-1A
El desequilibrio del rotor es la principal causa de fallas en el equipo, y con mayor frecuencia solo se desgastan los rodamientos. El desequilibrio puede surgir debido a problemas mecanicos, sobrecargas o fluctuaciones de temperatura. A veces, reemplazar los rodamientos es la unica solucion para corregir el desequilibrio. Por ejemplo, el equilibrado de rotores a menudo se puede resolver directamente en el lugar mediante un proceso de balanceo. Este procedimiento se clasifica como ajuste de vibracion mecanica en equipos rotativos.
MartinDat
12 Sep 25 at 11:31 am
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Подробнее тут – https://pitebd.com/how-to-protect-your-wealth-during-market-volatility
Larryhic
12 Sep 25 at 11:33 am
согласование перепланировки квартиры [url=http://soglasovanie-pereplanirovki-kvartiry17.ru/]согласование перепланировки квартиры[/url] .
soglasovanie pereplanirovki kvartiri _uaol
12 Sep 25 at 11:34 am
ставки на спорт бишкек онлайн [url=https://mostbet12006.ru]ставки на спорт бишкек онлайн[/url]
mostbet_naKl
12 Sep 25 at 11:35 am
Its not my first time to visit this web page, i am visiting this website dailly and get pleasant facts from here daily.
Check out my site – orthopedic shoulder specialist Orlando
orthopedic shoulder specialist Orlando
12 Sep 25 at 11:35 am
скачать казино мостбет [url=https://mostbet12007.ru]https://mostbet12007.ru[/url]
mostbet_wopt
12 Sep 25 at 11:36 am
mostbet casino скачать на андроид [url=https://www.mostbet12007.ru]https://www.mostbet12007.ru[/url]
mostbet_jppt
12 Sep 25 at 11:41 am
https://web.facebook.com/CANDETOXBLEND
Enfrentar un test preocupacional ya no tiene que ser una incertidumbre. Existe una fórmula confiable que actúa rápido.
El secreto está en su mezcla, que estimula el cuerpo con vitaminas, provocando que la orina enmascare los metabolitos de toxinas. Esto asegura un resultado confiable en solo 2 horas, con efectividad durante 4 a 5 horas.
Lo mejor: es un plan de emergencia, diseñado para candidatos en entrevistas laborales.
Miles de usuarios confirman su seguridad. Los envíos son 100% discretos, lo que refuerza la tranquilidad.
Cuando el examen no admite errores, esta alternativa es la respuesta que estabas buscando.
JuniorShido
12 Sep 25 at 11:41 am
где согласовать перепланировку квартиры [url=www.soglasovanie-pereplanirovki-kvartiry17.ru]www.soglasovanie-pereplanirovki-kvartiry17.ru[/url] .
soglasovanie pereplanirovki kvartiri _hxol
12 Sep 25 at 11:43 am
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Раскрыть тему полностью – https://veggiechips.mx/2022/01/24/hola-mundo
AndresEpimb
12 Sep 25 at 11:44 am
Very soon this web page will be famous among all blogging viewers, due to it’s fastidious articles or reviews
Take a look at my web site: learn more
learn more
12 Sep 25 at 11:46 am
https://impossible-studio.ghost.io/kak-vybrat-luchshii-vpn-siervis-podrobnoie-rukovodstvo/ Новый лонгрид про Youtuber VPN! Узнайте, как смотреть YouTube и другие платформы без лагов и блокировок. Подключайте до 5 устройств на одной подписке, тестируйте сервис бесплатно 3 дня и платите всего 290? в первый месяц вместо 2000? у конкурентов. Серверы в Европе — ваши данные защищены от российских властей.
Kevintow
12 Sep 25 at 11:47 am
перепланировка и согласование [url=http://soglasovanie-pereplanirovki-kvartiry17.ru]http://soglasovanie-pereplanirovki-kvartiry17.ru[/url] .
soglasovanie pereplanirovki kvartiri _heol
12 Sep 25 at 11:48 am
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Подробнее можно узнать тут – http://buizerdlaan-nieuwegein.nl/ufaq/parkeren-lidl
AndresEpimb
12 Sep 25 at 11:49 am
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Не упусти важное! – https://notifedia.com/waspada-akun-whatsapp-palsu-mengatasnamakan-pj-wali-kota-parepare
Larryhic
12 Sep 25 at 11:50 am
спасибо и ВАМ !!
https://ilm.iou.edu.gm/members/kdkpchvig445/
а что ты паришься. дождись пока домой принесут. посмотри в глазок что бы курьер один был. впусти его. а перед этим поставь чувака под окном. посыль забираешь, после, без палева выкидываешь в окно чуваку. а потом только выпускаешь курьера из квартиры. а там пусть хоть кто забегает, у тебя ничего нет. главное не нервничай и о плохом не думай. бери в хуй толще будет. а спср это почта россии. а почта россии ни когда нормально не работала.
Miguellag
12 Sep 25 at 11:50 am
перепланировка офиса [url=www.soglasovanie-pereplanirovki-kvartiry17.ru/]перепланировка офиса[/url] .
soglasovanie pereplanirovki kvartiri _lmol
12 Sep 25 at 11:52 am
где можно купить диплом [url=https://www.educ-ua17.ru]где можно купить диплом[/url] .
Diplomi_gwSl
12 Sep 25 at 11:54 am
Портал про детей https://mch.com.ua информационный ресурс для родителей. От беременности и ухода за малышом до воспитания школьников. Советы, статьи и поддержка для гармоничного развития ребёнка.
RalphTip
12 Sep 25 at 11:57 am
перепланировка услуги [url=http://www.soglasovanie-pereplanirovki-kvartiry17.ru]http://www.soglasovanie-pereplanirovki-kvartiry17.ru[/url] .
soglasovanie pereplanirovki kvartiri _rgol
12 Sep 25 at 11:57 am
Book of Savannahs Queen слот
Rupertnurne
12 Sep 25 at 11:57 am
Женский онлайн-журнал https://girl.kyiv.ua стиль, уход за собой, психология, кулинария, отношения и материнство. Ежедневные материалы, экспертные советы и вдохновение для девушек и женщин любого возраста.
EduardoNok
12 Sep 25 at 11:58 am
Онлайн-журнал для женщин https://krasotka-fl.com.ua всё о красоте, моде, семье и жизни. Полезные статьи, лайфхаки, советы экспертов и интересные истории. Читайте и вдохновляйтесь каждый день.
Peterset
12 Sep 25 at 11:58 am
1win вход с компьютера [url=www.1win12006.ru]www.1win12006.ru[/url]
1win_fxkn
12 Sep 25 at 12:01 pm
Mijn ambitie is niet alleen om je te begeleiden naar succes,
maar ook om je enthousiasme in het spel te maximaliseren. Ten slotte is dat waar het echt om gaat.
www.vensteracademy.com
12 Sep 25 at 12:02 pm
This text is priceless. When can I find out more?
global asia printings singapore
12 Sep 25 at 12:08 pm
бонусы в 1win [url=http://1win12006.ru]http://1win12006.ru[/url]
1win_ngkn
12 Sep 25 at 12:09 pm