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!
how to get generic enalapril price
how to buy generic enalapril without prescription
15 Sep 25 at 3:12 am
mexico drug store online [url=http://saludfrontera.com/#]SaludFrontera[/url] SaludFrontera
Michaelphype
15 Sep 25 at 3:12 am
Вызов нарколога на дом сочетает медицинскую эффективность с удобством. Пациент получает квалифицированную помощь в привычной обстановке, что снижает уровень тревожности и способствует более быстрому восстановлению.
Подробнее можно узнать тут – http://narkolog-na-dom-sankt-peterburg14.ru/
Robertfloum
15 Sep 25 at 3:15 am
как купить диплом о высшем образовании с занесением в реестр отзывы [url=arus-diplom31.ru]как купить диплом о высшем образовании с занесением в реестр отзывы[/url] .
Priobresti diplom ob obrazovanii!_gyOl
15 Sep 25 at 3:16 am
Клиника использует проверенные подходы с понятной логикой применения. Ниже — обзор ключевых методик и их места в маршруте терапии. Важно: выбор всегда индивидуален, а эффекты оцениваются по заранее оговорённым метрикам.
Подробнее – [url=https://narkologicheskaya-klinika-rostov-na-donu14.ru/]наркологическая клиника[/url]
Jackiemoips
15 Sep 25 at 3:18 am
купить аттестаты за 11 вечерней школе отзывы [url=http://www.arus-diplom25.ru]купить аттестаты за 11 вечерней школе отзывы[/url] .
Diplomi_gsot
15 Sep 25 at 3:18 am
Excellent site you have here but I was wondering
if you knew of any community forums that cover the same
topics discussed here? I’d really love to be a part of community where I can get comments
from other experienced individuals that share the same interest.
If you have any recommendations, please let me know. Kudos!
yeezy boost 350 v1 with v2 sole
15 Sep 25 at 3:20 am
Its like you read my mind! You appear to know so much about this,
like you wrote the book in it or something.
I think that you can do with some pics to drive the message home a
bit, but other than that, this is magnificent blog.
A great read. I’ll certainly be back.
homoclimbtastic.com lừa đảo công an truy quét cấm người chơi tham gia
15 Sep 25 at 3:21 am
Good post. I learn something new and challenging on blogs I
stumbleupon on a daily basis. It will always be exciting to read content from
other writers and use something from their web sites.
Click this site
15 Sep 25 at 3:25 am
В условиях медицинского контроля специалисты выполняют последовательные действия, направленные на стабилизацию состояния пациента.
Разобраться лучше – http://vyvod-iz-zapoya-ryazan14.ru/vyvod-iz-zapoya-na-domu-ryazan-czeny/
ScottieWah
15 Sep 25 at 3:25 am
mostbet.com что это [url=mostbet12011.ru]mostbet12011.ru[/url]
mostbet_paOt
15 Sep 25 at 3:26 am
magnificent points altogether, you just gained a logo new reader.
What might you recommend about your publish that
you simply made some days ago? Any certain?
online courses
15 Sep 25 at 3:28 am
Добрый день!
Долго не мог уяснить как поднять сайт и свои проекты и нарастить TF trust flow и узнал от крутых seo,
отличных ребят, именно они разработали недорогой и главное буст прогон Хрумером – https://polarposti.site
Линкбилдинг или стратегии помогают выбрать подход к продвижению. Линкбилдинг линкбилдинг работа экономит время специалистов. Линкбилдинг начать проще с Xrumer. Линкбилдинг стратегия повышает эффективность кампании. Линкбилдинг для англоязычного сайта расширяет охват аудитории.
оптимизация и продвижение сайта цена, инструменты для seo оптимизации сайта, курс линкбилдинг
Xrumer: советы и трюки, показатели сайта seo, редиректы сео
!!Удачи и роста в топах!!
Davidhen
15 Sep 25 at 3:31 am
trusted canadian pharmacy: canada pharmacy – TrueNorth Pharm
Charlesdyelm
15 Sep 25 at 3:33 am
Добрый день!
Долго анализировал как поднять сайт и свои проекты и нарастить DR и узнал от гуру в seo,
отличных ребят, именно они разработали недорогой и главное буст прогон Xrumer – https://short33.site
Xrumer форумный спам – эффективный способ продвижения в поисковиках. Прогон ссылок через форумы улучшает SEO-показатели за короткий срок. Автоматизация линкбилдинга экономит время и силы. Увеличение ссылочной массы приводит к росту DR и Ahrefs. Используйте Xrumer для создания качественных внешних ссылок.
хостинг seo, система создания и продвижения сайта, Автоматический прогон статей
Форумный спам для SEO, дешевое seo продвижение, сайт продвижение книга
!!Удачи и роста в топах!!
Michaelbor
15 Sep 25 at 3:37 am
Такая схема позволяет комплексно воздействовать на организм и уменьшить риски осложнений.
Ознакомиться с деталями – [url=https://narkolog-na-dom-v-krasnodare14.ru/]нарколог на дом срочно[/url]
Robertosaids
15 Sep 25 at 3:38 am
купить аттестат за 11 класс цена москва [url=arus-diplom25.ru]купить аттестат за 11 класс цена москва[/url] .
Diplomi_cnot
15 Sep 25 at 3:39 am
where buy cipro without prescription
can i purchase cheap cipro price
15 Sep 25 at 3:42 am
It’s enormous that youu are getting thoughts from this post as well as
from our discussion made at this place.
casino
15 Sep 25 at 3:46 am
Медикаментозное пролонгированное
Ознакомиться с деталями – http://kodirovanie-ot-alkogolizma-vidnoe7.ru/kodirovka-ot-alkogolya-v-vidnom/https://kodirovanie-ot-alkogolizma-vidnoe7.ru
JeremyTEF
15 Sep 25 at 3:46 am
Its like you read my mind! You seem to know so much about this, like you wrote the book in it
or something. I think that you can do with some pics to drive the message home
a little bit, but instead of that, this is fantastic blog.
A fantastic read. I will definitely be back.
j88slot
15 Sep 25 at 3:47 am
Come posso acquistare atarax economico senza ricetta
Come ottenere atarax generico
15 Sep 25 at 3:49 am
1win букмекерская [url=https://1win12007.ru]https://1win12007.ru[/url]
1win_sopn
15 Sep 25 at 3:49 am
где можно купить диплом [url=www.educ-ua17.ru/]где можно купить диплом[/url] .
Diplomi_crSl
15 Sep 25 at 3:50 am
Rainbet Australia
GeraldMug
15 Sep 25 at 3:56 am
Формат лечения
Исследовать вопрос подробнее – http://narkologicheskaya-klinika-sankt-peterburg14.ru
Romanronse
15 Sep 25 at 3:59 am
Даже если кажется, что «пройдёт само», при запойных состояниях осложнения нарастают быстро. Перед списком отметим логику: показания к инфузионной терапии определяет врач по совокупности симптомов, хронических заболеваний и текущих показателей. Ниже — типичные ситуации, при которых капельница даёт предсказуемый клинический эффект и снижает риски.
Получить дополнительные сведения – [url=https://kapelnica-ot-zapoya-vidnoe7.ru/]капельница от запоя цена видное[/url]
EugeneSoype
15 Sep 25 at 4:00 am
купить аттестат за 11 класс lr 63 [url=https://www.arus-diplom25.ru]купить аттестат за 11 класс lr 63[/url] .
Diplomi_bgot
15 Sep 25 at 4:02 am
Hi there! I understand this is sort of off-topic but I had
to ask. Does operating a well-established blog like yours take a massive amount work?
I’m brand new to writing a blog but I do write in my diary daily.
I’d like to start a blog so I can easily share my experience and feelings online.
Please let me know if you have any suggestions or tips for new
aspiring blog owners. Thankyou!
Ziyaret Et
15 Sep 25 at 4:08 am
*Седативные препараты применяются строго по показаниям и под мониторингом дыхания.
Подробнее тут – [url=https://vivod-iz-zapoya-rostov14.ru/]нарколог на дом вывод из запоя ростов-на-дону[/url]
BrianBlogy
15 Sep 25 at 4:11 am
Greate article. Keep posting such kind of info on your page.
Im really impressed by your site.
Hey there, You have performed a fantastic job. I’ll definitely digg it and individually suggest to
my friends. I’m confident they’ll be benefited from this web site.
relevant {material
15 Sep 25 at 4:11 am
купить дипломы техникума старого образца [url=educ-ua17.ru]купить дипломы техникума старого образца[/url] .
Diplomi_gbSl
15 Sep 25 at 4:11 am
1win вывод средств сколько ждать [url=https://1win12012.ru/]https://1win12012.ru/[/url]
1win_mzmr
15 Sep 25 at 4:14 am
как потратить бонусы казино 1вин [url=https://1win12010.ru]https://1win12010.ru[/url]
1win_gqEl
15 Sep 25 at 4:17 am
как потратить бонусы казино в 1вин [url=https://1win12013.ru/]https://1win12013.ru/[/url]
1win_uoPa
15 Sep 25 at 4:20 am
Современные методы лечения алкоголизма в Красноярске Алкоголизм — серьезная проблема, требующая профессионального подхода. В Красноярске доступны наркологические услуги, включая вызов нарколога на дом для анонимного лечения. Современные технологии лечения включают медикаментозную терапию и детоксикацию организма. Психотерапия при алкоголизме помогает разобраться с психологическими аспектами зависимости. Реабилитация зависимых проходит в специализированных центрах, где важна поддержка семьи. Программа восстановления включает профилактику алкогольной зависимости и лечение запойного состояния, что позволяет добиться устойчивых результатов. заказать нарколога на дом
vivodkrasnoyarskNeT
15 Sep 25 at 4:20 am
Мы изготавливаем дипломы психологов, юристов, экономистов и любых других профессий по приятным тарифам. Покупка диплома, который подтверждает окончание института, – это выгодное решение. Приобрести диплом университета: [url=http://apimi.com/agents/andrastrangway/]apimi.com/agents/andrastrangway[/url]
Mazrvdb
15 Sep 25 at 4:22 am
Howdy great website! Does running a blog similar to this require a large amount of work?
I have very little expertise in computer programming but I was hoping to start
my own blog in the near future. Anyway, should you have any recommendations or
techniques for new blog owners please share. I understand
this is off topic nevertheless I simply wanted to ask.
Many thanks!
commercial image generation
15 Sep 25 at 4:22 am
купить аттестат за 11 класс в тюмени [url=http://arus-diplom25.ru]купить аттестат за 11 класс в тюмени[/url] .
Diplomi_weot
15 Sep 25 at 4:24 am
как зарегистрироваться в мостбет [url=mostbet12013.ru]mostbet12013.ru[/url]
mostbet_qqka
15 Sep 25 at 4:24 am
Привет всем!
Долго обмозговывал как поднять сайт и свои проекты и нарастить CF cituation flow и узнал от гуру в seo,
отличных ребят, именно они разработали недорогой и главное продуктивный прогон Хрумером – https://polarposti.site
SEO-прогон для новичков ускоряет понимание работы с линкбилдингом. Программы типа Xrumer автоматизируют размещение ссылок. Массовый прогон повышает DR. Автоматизация упрощает продвижение сайтов. SEO-прогон для новичков – первый шаг к эффективному линкбилдингу.
2 продвижение сайтов, базовый курс seo курсы, линкбилдинг под бурж
Техники увеличения ссылочной массы, seo и smm специалистов, seo wiki
!!Удачи и роста в топах!!
Davidhen
15 Sep 25 at 4:24 am
Alas, primary mathematics educates everyday applications ѕuch as financial planning, therefοre guarantee yoսr kid grasps that properly starting
еarly.
Hey hey, calm pom ρi pi, maths іs one in tһе hiɡhest topics in Junior College, laying base fⲟr A-Level
һigher calculations.
Anglo-Chinese Junior College stands аs a beacon ߋf well balanced education, mixing rigorous academics
ԝith a supporting Christian principles that influences ethical integrity and personal development.
Ƭһe college’ѕ modern centers and experienced faculty support impressive performance іn botһ arts and sciences, ѡith students often attaining
leading accolades. Τhrough its focus оn sports and performing arts,
trainees establish discipline, sociability, аnd an enthusiasm for excellence ƅeyond the class.
International partnerships ɑnd exchange opportunities enhance tһe finding oսt
experience, fostering international awareness ɑnd cultural gratitude.
Alumni flourish іn diverse fields, testimony to tһe college’ѕ
function in forming principled leaders ɑll set to contribute
positively tߋ society.
Tampines Meridian Junior College, born fгom the lively merger of Tampines Junior College ɑnd Meridian Junior
College, delivers ɑn innovative ɑnd culturally rich education highlighted ƅy specialized electives іn drama and Malay language,
supporting meaningful ɑnd multilingual talents іn a forward-thinking neighborhood.
Ꭲhe college’ѕ innovative centers, encompassing theater
ɑreas, commerce simulation labs, ɑnd sciuence innovation hubs,
assistance diverse scholastic streams tһat encourage interdisciplinary exploration аnd practical skill-building throughout arts, sciences, аnd business.
Skill advancement programs, coupled ᴡith overseas immersion trips and cultural festivals, foster sgrong management qualities,
cultural awareness, аnd flexibility tⲟ international characteristics.
Ꮤithin a caring and understanding campus culture, students tɑke
pɑrt in wellness efforts, peer support ɡroups, ɑnd co-curricular clubs thаt promote
durability, psychological intelligence, аnd collaborative spirit.
Αs a result, Tampines Meridian Junior College’s trainees achieve holistic development аnd are well-prepared tо tackle worldwide obstacles,
emerging аѕ positive, flexible people prepared fⲟr university success
ɑnd beyond.
Don’t play play lah, combine а reputable
Junior College ρlus mathematics excellence fοr ensure superior A Levels results as
wеll as effortless changes.
Folks, dread tһe difference hor, maths foundation іs essential іn Junior College tо grasping figures, vital
iin modern tech-driven ѕystem.
Goodness, гegardless іf institution гemains fancy, mathematics
acts ⅼike the critical subject tߋ building confidence гegarding numƅers.
Listen uр, Singapore moms and dads, math remains prօbably the
extremely іmportant primary topic, fostering creativity fߋr issue-resolving to
creative careers.
Kiasu study apps fⲟr Math makе A-level prep efficient.
Aiyo, mіnus solid maths Ԁuring Junior College, еven prestigious
institution children could falter with secondary algebra,
theгefore develop it promptlʏ leh.
Check out mу web-site – math tuition singapore
math tuition singapore
15 Sep 25 at 4:25 am
It is in point of fact a great and helpful piece of information. I am glad that you simply shared this
useful information with us. Please keep us up to date like this.
Thanks for sharing.
jelas777
15 Sep 25 at 4:25 am
I have read so many posts regarding the blogger lovers but this
piece of writing is in fact a nice paragraph, keep it up.
Vortex Bitriver
15 Sep 25 at 4:26 am
Thanks a bunch for sharing this with all people you actually know what
you’re speaking approximately! Bookmarked. Please additionally seek advice from my
site =). We will have a hyperlink trade arrangement between us
https://fromkorea.kr
15 Sep 25 at 4:28 am
купить аттестаты за 11 классов в краснодаре [url=https://arus-diplom25.ru]купить аттестаты за 11 классов в краснодаре[/url] .
Diplomi_fqot
15 Sep 25 at 4:29 am
как купить диплом о высшем образовании с занесением в реестр [url=https://educ-ua11.ru/]как купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_ntPi
15 Sep 25 at 4:31 am
купить диплом о среднем специальном образовании цена [url=http://educ-ua17.ru]купить диплом о среднем специальном образовании цена[/url] .
Diplomi_zsSl
15 Sep 25 at 4:31 am
стоит купить диплом о высшем образовании [url=http://educ-ua17.ru/]стоит купить диплом о высшем образовании[/url] .
Diplomi_mmSl
15 Sep 25 at 4:38 am
Для максимальной эффективности мы предлагаем несколько сценариев — от разового экстренного вмешательства до длительного сопровождения ремиссии. Выбор формата определяется состоянием, анамнезом и целями пациента. Возможен гибридный маршрут: старт на дому, затем — дневной стационар или госпитализация, а после стабилизации — амбулаторное сопровождение.
Выяснить больше – [url=https://narkologicheskaya-pomoshch-ramenskoe7.ru/]оказание наркологической помощи[/url]
LarryMub
15 Sep 25 at 4:40 am