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!
Приобрести MEF GASH SHIHSKI ALFA – ОТЗЫВЫ, ГАРАНТРР, КАЧЕСТВО
Stacymug
2 Oct 25 at 10:19 pm
iphone 10 цена спб [url=http://iphone-kupit-1.ru/]iphone 10 цена спб[/url] .
aifon kypit_unsn
2 Oct 25 at 10:20 pm
Admiring the dedication you put into your blog and detailed information you provide.
It’s nice to come across a blog every once in a while that isn’t the same out of date rehashed material.
Great read! I’ve saved your site and I’m adding your RSS feeds to my Google account.
Very good
2 Oct 25 at 10:20 pm
аренда экскаватора в москве цена [url=arenda-ekskavatora-pogruzchika-cena.ru]аренда экскаватора в москве цена[/url] .
arenda ekskavatora pogryzchika cena_szSr
2 Oct 25 at 10:21 pm
Please let me know if you’re looking for a article writer for your site.
You have some really great posts and I feel I would be a
good asset. If you ever want to take some of the load off, I’d really
like to write some material for your blog in exchange for a link back to
mine. Please send me an email if interested. Kudos!
13win
2 Oct 25 at 10:22 pm
The $MTAUR token presale is seamless—swapped USDT easily. Hidden treasures in mazes reward skillful play. This could be huge for play-to-earn fans.
mtaur coin
WilliamPargy
2 Oct 25 at 10:23 pm
OMT’ѕ self-paced e-learning platform enables pupils
tο check out mathematics ɑt their ߋwn rhythm, transforming irritation іnto attraction and motivating outstanding examination performance.
Dive іnto self-paced math mastery ѡith OMT’ѕ 12-mⲟnth e-learning courses, ⅽomplete with practice worksheets аnd taped sessions f᧐r thorougһ modification.
Singapore’ѕ emphasis ߋn vital analyzing mathematics highlights tһe valᥙe of math tuition,
wһiⅽh helps students establish tһe analytical skills demanded Ƅy the country’ѕ forward-thinking curriculum.
primary tuition іs essential f᧐r PSLE as it uѕеs restorative assistance fօr topics like
whole numberѕ and measurements, ensuring no foundational weak рoints continue.
Comprehensive insurance coverage οf the ԝhole O
Level curriculum іn tuition ensures no subjects, from collections tօ vectors,are overlooked іn ɑ student’s alteration.
Math tuition at the junior college degree highlights theoretical quality оver rote memorization, essential fоr taking on application-based A Level
concerns.
OMT’ѕ custom-designed educational program distinctively improves tһe MOE structure Ƅy supplying
thematic systems tһat link mathematics topics аcross primary tօ JC degrees.
Unrestricted retries ߋn tests ѕia, ideal foг understanding subjects ɑnd attaining tһose A grades іn math.
Singapore’s global position іn math cօmeѕ from supplementary tuition tһɑt develops skills for global criteria like PISA
and TIMSS.
my site :: maths home Tuition іn faridabad – wiki.Tgt.eu.Com –
wiki.Tgt.eu.Com
2 Oct 25 at 10:23 pm
спортивные новости [url=https://novosti-sporta-16.ru/]https://novosti-sporta-16.ru/[/url] .
novosti sporta_whsi
2 Oct 25 at 10:23 pm
Hi my friend! I want to say that this article is awesome,
great written and include approximately all important infos.
I would like to see more posts like this .
소액결제 현금화
2 Oct 25 at 10:23 pm
бесплатные точные прогнозы на спорт [url=www.prognozy-na-sport-12.ru]www.prognozy-na-sport-12.ru[/url] .
prognozi na sport_aaMn
2 Oct 25 at 10:25 pm
мобильные телефоны iphone [url=https://iphone-kupit-1.ru]мобильные телефоны iphone[/url] .
aifon kypit_dasn
2 Oct 25 at 10:27 pm
Сломалась машина? техпомощь выездная мы создали профессиональную службу автопомощи, которая неустанно следит за безопасностью автомобилистов в Санкт-Петербурге и Ленинградской области. Наши специалисты всегда на страже вашего спокойствия. В случае любой нештатной ситуации — от банальной разрядки аккумулятора до серьёзных технических неисправностей — мы незамедлительно выезжаем на место.
avto-help-240
2 Oct 25 at 10:27 pm
аренда экскаватора стоимость [url=arenda-ekskavatora-pogruzchika-cena.ru]arenda-ekskavatora-pogruzchika-cena.ru[/url] .
arenda ekskavatora pogryzchika cena_xaSr
2 Oct 25 at 10:31 pm
ставки прогнозы [url=https://novosti-sporta-17.ru]https://novosti-sporta-17.ru[/url] .
novosti sporta_cwOi
2 Oct 25 at 10:31 pm
Сломалась машина? техпомощь выездная мы создали профессиональную службу автопомощи, которая неустанно следит за безопасностью автомобилистов в Санкт-Петербурге и Ленинградской области. Наши специалисты всегда на страже вашего спокойствия. В случае любой нештатной ситуации — от банальной разрядки аккумулятора до серьёзных технических неисправностей — мы незамедлительно выезжаем на место.
avto-help-143
2 Oct 25 at 10:34 pm
Таблица: Основные признаки надёжного центра лечения наркомании
Узнать больше – [url=https://lechenie-narkomanii-murmansk0.ru/]принудительное лечение наркомании в мурманске[/url]
BarrySem
2 Oct 25 at 10:35 pm
аренда экскаватора стоимость [url=http://www.arenda-ekskavatora-pogruzchika-cena.ru]http://www.arenda-ekskavatora-pogruzchika-cena.ru[/url] .
arenda ekskavatora pogryzchika cena_ulSr
2 Oct 25 at 10:35 pm
tatumsounds – I really enjoyed the visuals and sound vibe, feels creative and smooth.
Sha Dornon
2 Oct 25 at 10:36 pm
Hello I am so happy I found your website, I really found
you by accident, while I was researching on Google for something else, Regardless I am here now and would just like
to say kudos for a fantastic post and a all round entertaining blog (I
also love the theme/design), I don’t have time to read it all at the moment but I
have book-marked it and also included your RSS feeds, so when I have time I will
be back to read a lot more, Please do keep up the excellent job.
@SEO_LINKK - SEO BLACKHAT
2 Oct 25 at 10:36 pm
новости спорта [url=http://novosti-sporta-15.ru/]http://novosti-sporta-15.ru/[/url] .
novosti sporta_btma
2 Oct 25 at 10:36 pm
Сломалась машина? помощь на дороге круглосуточно мы создали профессиональную службу автопомощи, которая неустанно следит за безопасностью автомобилистов в Санкт-Петербурге и Ленинградской области. Наши специалисты всегда на страже вашего спокойствия. В случае любой нештатной ситуации — от банальной разрядки аккумулятора до серьёзных технических неисправностей — мы незамедлительно выезжаем на место.
avto-help-257
2 Oct 25 at 10:37 pm
Проблемы зависимости требуют оперативного вмешательства. Чем раньше начато лечение, тем выше вероятность полного восстановления. Наркологическая помощь в Архангельске представлена как государственными, так и частными клиниками, каждая из которых предлагает свой уровень сервиса и спектр услуг. Однако для получения эффективной и безопасной помощи важно понимать, какие критерии определяют качество наркологической поддержки.
Углубиться в тему – http://narkologicheskaya-pomoshh-arkhangelsk0.ru
MichaelImino
2 Oct 25 at 10:39 pm
Современные реалии требуют от медицинских учреждений гибкости, скорости и чуткости. Наркологическая помощь — одна из сфер, где промедление может стоить человеку здоровья или жизни. В наркологической клинике «ТверьМед» разработаны оперативные механизмы реагирования: выезд врача по адресу в течение 30 минут, круглосуточная поддержка и возможность получения онлайн-консультации, не покидая дом. Такой подход позволяет вовремя оказать помощь, даже если пациент отказывается ехать в стационар или не осознаёт всю серьёзность своего состояния.
Исследовать вопрос подробнее – [url=https://narkologicheskaya-pomoshh-tver0.ru/]оказание наркологической помощи[/url]
Lucashapof
2 Oct 25 at 10:40 pm
аренда экскаватора погрузчика московская область [url=arenda-ekskavatora-pogruzchika-cena.ru]аренда экскаватора погрузчика московская область[/url] .
arenda ekskavatora pogryzchika cena_tvSr
2 Oct 25 at 10:41 pm
Приобрести MEF GASH SHIHSKI ALFA – ОТЗЫВЫ, ГАРАНТРР, КАЧЕСТВО
Stacymug
2 Oct 25 at 10:45 pm
https://www.wildberries.ru/catalog/249860602/detail.aspx
Kevinsaush
2 Oct 25 at 10:46 pm
https://tex-stile.ru/novosti/6607-v-chem-osobennosti-oficialnogo-importa-iz-kitaya.html
GeraldObedo
2 Oct 25 at 10:48 pm
аренда экскаватора погрузчика terex [url=https://arenda-ekskavatora-pogruzchika-cena.ru]https://arenda-ekskavatora-pogruzchika-cena.ru[/url] .
arenda ekskavatora pogryzchika cena_bjSr
2 Oct 25 at 10:50 pm
https://yerkramas.org/article/198234/professionalnye-B2B-platformy-dlya-effektivnyx-zakupok-tovarov-iz-kitaya
GeraldObedo
2 Oct 25 at 10:50 pm
Оперативный выезд специалиста позволяет начать терапию без задержек, что особенно важно при тяжелой алкогольной интоксикации. Благодаря помощи на дому, пациент избегает длительного ожидания в очередях и стрессовых поездок в стационар, что способствует сохранению психологического комфорта и анонимности.
Детальнее – [url=https://vyvod-iz-zapoya-tula000.ru/]наркологический вывод из запоя[/url]
BrittLonge
2 Oct 25 at 10:51 pm
Клиники владимира предлагают разнообразные пакеты услуг, включая инъекции для снятия запойного состояния, которые могут включать витамины и лекарства для облегчения состояния. Анализ медицинских учреждений позволяет определить лучший выбор с учетом ценовой политики и уровня сервиса. Большинство учреждений предоставляет круглосуточную помощь в большинстве учреждений.При определении медицинского учреждения стоит учитывать отзывы пациентов и опыт врачей. Консультации нарколога помогут составить эффективный план терапии алкоголизма. Конфиденциальное лечение также является важным аспектом, так как многие пациенты предпочитают скрыть свою проблему.После завершения запойного состояния требует комплексного подхода, включая реабилитационные программы для зависимых и дальнейшее наблюдение за состоянием пациента. Таким образом, работа специалистов-наркологов, такие как вывод из запоя и капельницы от запоя, играют ключевую роль в процессе выздоровления. вывод из запоя круглосуточно владимир
lechenievladimirNeT
2 Oct 25 at 10:52 pm
There is certainly a great deal to find out
about this topic. I like all of the points you have made.
Medikamentebestellen.space
2 Oct 25 at 10:55 pm
legit mexican pharmacy without prescription [url=https://medicexpressmx.com/#]mexican pharmacy[/url] buy viagra from mexican pharmacy
TimothyArrar
2 Oct 25 at 10:56 pm
стоимость услуг экскаватора [url=http://arenda-ekskavatora-pogruzchika-cena.ru]стоимость услуг экскаватора[/url] .
arenda ekskavatora pogryzchika cena_uqSr
2 Oct 25 at 10:56 pm
Bullish on $MTAUR coin for its referral and vesting perks. ICO phase’s low entry beats later prices. Whimsical gameplay hooks you instantly.
mtaur coin
WilliamPargy
2 Oct 25 at 10:57 pm
экскаватор. цена. час. [url=https://arenda-ekskavatora-pogruzchika-cena.ru/]https://arenda-ekskavatora-pogruzchika-cena.ru/[/url] .
arenda ekskavatora pogryzchika cena_rmSr
2 Oct 25 at 11:00 pm
Как поясняет врач-нарколог НМИЦ психиатрии и наркологии, «наличие оборудованного стационара с возможностью контроля осложнений — обязательное условие безопасного лечения наркомании».
Выяснить больше – [url=https://lechenie-narkomanii-yaroslavl0.ru/]лечение наркомании ярославль.[/url]
StevenTweve
2 Oct 25 at 11:01 pm
tatumsounds – I really enjoyed the visuals and sound vibe, feels creative and smooth.
Forrest Kuza
2 Oct 25 at 11:03 pm
Appreciate this post. Will try it out.
Thank you
2 Oct 25 at 11:04 pm
сервис аренды спецтехники [url=arenda-ekskavatora-pogruzchika-cena.ru]arenda-ekskavatora-pogruzchika-cena.ru[/url] .
arenda ekskavatora pogryzchika cena_jaSr
2 Oct 25 at 11:05 pm
If you want to grow your familiarity jujst keep visiting this web site and be
updated with thhe most recent information polsted
here.
Feel free to surf to my page … um curso em milagres
um curso em milagres
2 Oct 25 at 11:06 pm
Generic Cialis without a doctor prescription: tadalafil online united states – Generic tadalafil 20mg price
BruceMaivy
2 Oct 25 at 11:06 pm
https://www.imdb.com/list/ls4150156394/
Jamesaberi
2 Oct 25 at 11:08 pm
Приобрести MEF GASH SHIHSKI ALFA – ОТЗЫВЫ, ГАРАНТРР, КАЧЕСТВО
Jeromeliz
2 Oct 25 at 11:11 pm
https://www.wildberries.ru/catalog/514992745/detail.aspx
Kevinsaush
2 Oct 25 at 11:12 pm
By incorporating Singaporean contexts іnto lessons,
OMT mаkes math pertinent, promoting affection аnd inspiration for high-stakes exams.
Transform math difficulties іnto triumphs ᴡith OMT Math Tuition’s blend of online ɑnd on-site choices, baсked by a
performance history оf student quality.
In Singapore’ѕ rigorous education ѕystem, wheгe
mathematics is required аnd takеѕ in around 1600 hourѕ of curriculum time in primary ɑnd secondary schools, math tuition ƅecomes vital tօ
assist trainees build а strong structure fοr lifelong success.
Ϝοr PSLE achievers, tuition proviԀes mock tests ɑnd feedback, helping improve responses fοr maximum marks іn both
multiple-choice ɑnd օpen-ended areaѕ.
Dеtermining and rectifying certain weak pоints, lіke
іn probability or coordinate geometry, mɑkes secondary tuition indispensable
fοr O Level excellence.
Tһrough regular mock exams аnd thoгough responses, tuition assists junior college students determine
аnd correct weaknesses Ƅefore tһe actual A Levels.
OMT’s personalized mathematics curriculum stands оut by bridging MOE material ѡith sophisticated theoretical web ⅼinks, assisting students connect
ideas аcross various math topics.
OMT’s online syѕtеm complements MOE syllabus ⲟne, assisting yοu take on PSLE math
effortlessly аnd better scores.
Ӏn Singapore, ԝһere mathematics proficiency opens doors to STEM jobs, tuition іs
important for solid test structures.
Feel free t᧐ surf tօ my hօmepage good math tuition centre for primary
good math tuition centre for primary
2 Oct 25 at 11:16 pm
прогнозы на сегодня спорт [url=https://prognozy-na-sport-12.ru/]прогнозы на сегодня спорт[/url] .
prognozi na sport_izMn
2 Oct 25 at 11:18 pm
https://tadalmedspharmacy.shop/# india pharmacy online tadalafil
Williamjib
2 Oct 25 at 11:18 pm
Первый шаг в лечении — это тщательный осмотр специалиста. Наряду с измерением жизненно важных показателей (пульс, артериальное давление, температура) врач проводит сбор анамнеза, выясняя длительность запоя, тип употребляемого алкоголя и наличие сопутствующих заболеваний. Эти данные помогают оценить степень интоксикации и подобрать индивидуальный план терапии, что является ключевым для дальнейшей эффективной детоксикации.
Детальнее – [url=https://vyvod-iz-zapoya-yaroslavl0.ru/]срочный вывод из запоя[/url]
PatrickSig
2 Oct 25 at 11:19 pm
купить диплом в каспийске [url=www.rudik-diplom6.ru/]www.rudik-diplom6.ru/[/url] .
Diplomi_nhKr
2 Oct 25 at 11:20 pm