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://wanderlog.com/view/equsanhxoj/купить-марихуану-гашиш-канабис-анталия/shared
JuliusGlush
21 Aug 25 at 9:48 am
What’s up to all, as I am really keen of reading this blog’s post to be updated on a regular basis.
It contains nice stuff.
https://tt88t3.uk.com
21 Aug 25 at 9:50 am
I think that is among the most significant information for me.
And i’m glad studying your article. But wanna commentary on some basic issues,
The web site taste is wonderful, the articles is actually excellent : D.
Excellent task, cheers
Nổ Hũ TT88
21 Aug 25 at 9:50 am
You actually make it seem so easy with your presentation but I find
this matter to be really something which I think I would never understand.
It seems too complicated and extremely broad for me.
I’m looking forward for your next post, I’ll try to get the hang of it!
Live Draw Taiwan
21 Aug 25 at 9:53 am
1942 Sky Warrior online Pt
WilliamNex
21 Aug 25 at 9:53 am
устройство плоской кровли https://montazh-ploskoj-krovli.ru
montazh-ploskoj-krovli-276
21 Aug 25 at 9:54 am
купить аттестат за 11 класс в киеве [url=www.arus-diplom22.ru]www.arus-diplom22.ru[/url] .
Diplomi_cvsl
21 Aug 25 at 9:57 am
Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
Почему это важно? – https://grandeatomy.com.br/novidade-em-produtos
RodneyCarse
21 Aug 25 at 10:00 am
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Ознакомьтесь с аналитикой – https://kataberita.net/kerjasama-pt-enero-dengan-brin
DavidMon
21 Aug 25 at 10:00 am
В этой информационной статье вы найдете интересное содержание, которое поможет вам расширить свои знания. Мы предлагаем увлекательный подход и уникальные взгляды на обсуждаемые темы, побуждая пользователей к активному мышлению и критическому анализу.
Перейти к статье – https://freguesianews.com.br/2024/05/26/agencia-minas-gerais-vice-governador-participa-da-feira-multissetorial-de-santa-barbara
TerrySnivY
21 Aug 25 at 10:00 am
Создать документы онлайн конструктор трудового договора онлайн: создайте договор, заявление или акт за 5 минут. Простая форма, готовые шаблоны, юридическая точность и возможность скачать в нужном формате.
datadoc-787
21 Aug 25 at 10:01 am
Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
Подробная информация доступна по запросу – https://khalidalmuheirigroup.com/connecting-with-natures-tranquil-essence
Ricardounuse
21 Aug 25 at 10:01 am
https://muckrack.com/person-27490915
Nathanfal
21 Aug 25 at 10:07 am
В этой публикации мы предлагаем подробные объяснения по актуальным вопросам, чтобы помочь читателям глубже понять их. Четкость и структурированность материала сделают его удобным для усвоения и применения в повседневной жизни.
Только факты! – https://fotoreportexalapa.com/el-tranvia-2
HenryNix
21 Aug 25 at 10:08 am
I simply could not depart your website before suggesting that I actually loved the
standard info a person provide for your guests?
Is going to be again frequently in order to inspect new posts
dewa scatter
21 Aug 25 at 10:09 am
cialis over the counter usa [url=https://tadalify.com/#]where to buy liquid cialis[/url] order cialis soft tabs
RobertCat
21 Aug 25 at 10:09 am
This paragraph gives clear idea for the new viewers of blogging, that
actually how to do blogging.
daftar ratuular77
21 Aug 25 at 10:14 am
Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
Более подробно об этом – https://radiantandbrighter.com/2018/07/15/mariarose
JordanAbsox
21 Aug 25 at 10:15 am
купить аттестат о 11 классах [url=www.arus-diplom24.ru]купить аттестат о 11 классах[/url] .
Diplomi_qpKn
21 Aug 25 at 10:18 am
бизнес оценка москва оценочная компания
ocenochnaya-kompaniya-428
21 Aug 25 at 10:21 am
аттестат за 11 класс 2014 купить [url=www.arus-diplom22.ru]аттестат за 11 класс 2014 купить[/url] .
Diplomi_assl
21 Aug 25 at 10:22 am
Всех приветствую! Хотите узнать больше о продвижении? Узнайте больше – https://aidaru.ir/%D8%A2%D9%85%D9%BE%D9%88%D9%84-%D9%87%D8%A7%DB%8C-%D8%AA%D8%B2%D8%B1%DB%8C%D9%82%DB%8C-%D9%84%D8%A7%D8%BA%D8%B1%DB%8C-%D9%88-%D8%AA%D9%81%D8%A7%D9%88%D8%AA-%D8%A2%D9%86%D9%87%D8%A7-%D9%88-%D8%B9%D9%88/
WilliamLig
21 Aug 25 at 10:24 am
https://bio.site/paybuiihai
JuliusGlush
21 Aug 25 at 10:27 am
https://odysee.com/@ekysunandar72
Nathanfal
21 Aug 25 at 10:29 am
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Смотрите также… – https://sale-box.de/2023/04/09/boost-your-online-presence-our-top-digital-marketing
HenryNix
21 Aug 25 at 10:34 am
Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
Получить исчерпывающие сведения – https://compagniedesenergiespropres.fr/ma-prime-renov-2022
Jerrynox
21 Aug 25 at 10:37 am
ставки на хоккей прогнозы [url=http://prognozy-na-khokkej.ru]http://prognozy-na-khokkej.ru[/url] .
prognozi na hokkei_spPr
21 Aug 25 at 10:41 am
Good post. I learn something totally new and challenging on websites I stumbleupon every day.
It’s always useful to read articles from other authors and practice a little
something from their sites.
Live Draw Taiwan Tercepat
21 Aug 25 at 10:41 am
Hi there mates, how is everything, and what you wish for to say on the topic of this article,
in my view its in fact amazing for me.
keo nha cai
21 Aug 25 at 10:45 am
купить аттестат за 11 класс в нижневартовске [url=https://www.arus-diplom22.ru]https://www.arus-diplom22.ru[/url] .
Diplomi_gtsl
21 Aug 25 at 10:48 am
A qualidade e o formato das fotos e imagens baixadas do Instagram podem variar dependendo do arquivo original que foi enviado para a rede social.
link-Motion.com
21 Aug 25 at 10:50 am
https://www.metooo.io/u/68a0f0c14909e3053ade0c14
Nathanfal
21 Aug 25 at 10:50 am
Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
Узнать из первых рук – https://adidas-tt.ru/?paged=32&cat=1
WayneDrist
21 Aug 25 at 10:51 am
I was suggested this blog by my cousin. I’m not certain whether
or not this post is written through him as no one else recognise such
certain about my problem. You are wonderful! Thank you!
호빠
21 Aug 25 at 10:52 am
где можно купить аттестат 11 классов [url=http://www.arus-diplom22.ru]где можно купить аттестат 11 классов[/url] .
Diplomi_resl
21 Aug 25 at 10:55 am
Everyone loves it when individuals come together and share views.
Great website, keep it up!
Elyor Platform
21 Aug 25 at 10:58 am
Каждый гемблер ищет более выгодные условия для игры в казино, чтобы получить бонус, особые привилегии. Вот почему казино выдают бонусы. Их начисляют очень быстро, после авторизации, а потому не придется класть деньги на счет, тратить свои финансы. https://1000topbonus.website/
– на сайте представлено огромное количество проверенных, надежных заведений, которые отличаются наличием лицензии и играют на честных условиях, радуют клиентов безупречной работой, регулярными выплатами, дружелюбной службой поддержки.
verojafeego
21 Aug 25 at 10:59 am
Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
Не упусти важное! – https://all4holidays.ru/?paged=23&cat=1
Ralphmub
21 Aug 25 at 10:59 am
Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
Ознакомьтесь с аналитикой – https://www.hotel-sugano.com/bbs/sugano.cgi/www.tovery.net/datasphere.ru/club/user/12/blog/2477/www.hip-hop.ru/forum/id298234-worksale/www.hip-hop.ru/forum/id298234-worksale/sugano.cgi?page40=val
JordanAbsox
21 Aug 25 at 11:02 am
togel 4d
Info Seru Kompetisi Spin Toto Slot 88 & Tebak Angka Togel 4D Unggulan – TOGELONLINE88
toto slot
21 Aug 25 at 11:02 am
Этот увлекательный информационный материал подарит вам массу новых знаний и ярких эмоций. Мы собрали для вас интересные факты и сведения, которые обогатят ваш опыт. Откройте для себя увлекательный мир информации и насладитесь процессом изучения!
Переходите по ссылке ниже – https://vorticeweb.com/asi-se-podra-afiliar-a-las-trabajadoras-del-hogar-al-imss
JasonSueri
21 Aug 25 at 11:04 am
Мы предлагаем вам подробное руководство, основанное на проверенных источниках и реальных примерах. Каждая часть публикации направлена на то, чтобы помочь вам разобраться в сложных вопросах и применить знания на практике.
Ознакомиться с полной информацией – http://www.vlamcoat.be/2013/03/21/magna-fringilla-quis-condimentum
RickyPrima
21 Aug 25 at 11:05 am
Основные типы бетонных свайных
изделий
свайный фундамент для дома из пеноблоков
21 Aug 25 at 11:06 am
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Узнать напрямую – https://www.brnnetwork.org/gallery/web-american-kestrel-james-poling
RodneyCarse
21 Aug 25 at 11:06 am
https://wanderlog.com/view/qbirorabrn/купить-экстази-кокаин-амфетамин-канарские-острова/shared
JuliusGlush
21 Aug 25 at 11:06 am
can you buy viagra in mexico [url=https://sildenapeak.shop/#]SildenaPeak[/url] best otc female viagra
RobertCat
21 Aug 25 at 11:07 am
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Это стоит прочитать полностью – https://www.iso-studio.it/inail-riduzione-del-premio-ot23-interventi-entro-fine-anno
HenryNix
21 Aug 25 at 11:08 am
Stavki Prognozy [url=stavki-prognozy-two.ru]stavki-prognozy-two.ru[/url] .
stavki prognozi_ipMr
21 Aug 25 at 11:09 am
Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
Углубить понимание вопроса – https://redcrosstrainingcentre.org/2013/10/04/a-look-inside-the-protein-bar
HenryNix
21 Aug 25 at 11:10 am
Wow, incredible blog structure! How long have you been running a blog for?
you made blogging glance easy. The whole glance of your web site is
magnificent, as neatly as the content material!
https://paitomacau.top/
Prediksi Angka Keluaran Macau
21 Aug 25 at 11:11 am