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://rudik-diplom5.ru/]купить диплом судоводителя[/url] .
Diplomi_dlma
16 Oct 25 at 1:37 pm
Quick reference on [url=https://change-lights.com/home-improvement-experts-remodeling-experts-near-69]Siding installation[/url]. It outlines the basics without fluff. Bookmark it for later research.
PhillipBeify
16 Oct 25 at 1:37 pm
купить диплом провизора [url=www.rudik-diplom4.ru/]купить диплом провизора[/url] .
Diplomi_ipOr
16 Oct 25 at 1:38 pm
https://t.me/Official_1xbet_1xbet/s/650
AlbertEnark
16 Oct 25 at 1:40 pm
https://worldgeo.ru/russia/
Nathanhip
16 Oct 25 at 1:40 pm
https://t.me/Official_1xbet_1xbet/s/1076
AlbertEnark
16 Oct 25 at 1:40 pm
потолочкин потолки [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru]https://natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_cima
16 Oct 25 at 1:40 pm
betting promo codes no deposit Using the best bets code you can enhance your cash prize value and unlock great betting offers. Join now for enhanced rewards and extra chance to win the grand total!
Caseypeash
16 Oct 25 at 1:41 pm
https://yaplakal.org/wallpapers/odezhda-kosmonavta-risunok
https://yaplakal.org/wallpapers/odezhda-kosmonavta-risunok
16 Oct 25 at 1:42 pm
мостбет промокод 2025 уз [url=https://mostbet4185.ru/]мостбет промокод 2025 уз[/url]
mostbet_uz_fger
16 Oct 25 at 1:43 pm
Hello outstanding website! Does running a blog similar to this take a large amount of work?
I’ve virtually no expertise in computer programming however I had been hoping to start
my own blog soon. Anyhow, should you have any suggestions or techniques for new blog
owners please share. I know this is off subject but I simply wanted to ask.
Thanks a lot!
water heater filtration
16 Oct 25 at 1:43 pm
купить диплом института [url=https://www.rudik-diplom1.ru]купить диплом института[/url] .
Diplomi_uaer
16 Oct 25 at 1:43 pm
Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
Всё, что нужно знать – https://theplaybook.tonehouse.com/2022/08/16/new-eo3-drinks-what-you-need-to-know
LarryBoogY
16 Oct 25 at 1:44 pm
В зависимости от клинической картины и предпочтений возможны следующие виды кодирования:
Получить дополнительную информацию – https://kodirovanie-ot-alkogolizma-ehlektrostal6.ru/kodirovanie-ot-alkogolizma-ceny-v-ehlektrostali
Rafaelred
16 Oct 25 at 1:44 pm
купить диплом моториста [url=https://rudik-diplom8.ru/]купить диплом моториста[/url] .
Diplomi_zgMt
16 Oct 25 at 1:44 pm
купить диплом о высшем образовании с занесением в реестр цена [url=www.frei-diplom6.ru]купить диплом о высшем образовании с занесением в реестр цена[/url] .
Diplomi_htOl
16 Oct 25 at 1:45 pm
натяжные потолки официальный сайт нижний новгород [url=https://stretch-ceilings-nizhniy-novgorod-1.ru/]https://stretch-ceilings-nizhniy-novgorod-1.ru/[/url] .
natyajnie potolki nijnii novgorod_unOn
16 Oct 25 at 1:45 pm
mostbet uz скачать ios [url=https://www.mostbet4182.ru]https://www.mostbet4182.ru[/url]
mostbet_uz_umkt
16 Oct 25 at 1:45 pm
Поскольку безопасность и анонимность выступают ключевыми приоритетами при взаимодействии с подобными ресурсами, поиск надежного способа входа имеет определяющую роль. Применение сомнительных ссылок чревато к краже аккаунта и денег, поэтому необходимо проявлять максимальную бдительность. [url=https://kradark.net]тор кракен[/url] Данный сайт служит в роли постоянно обновляемого источника рабочих зеркал, позволяя любому желающему 24/7 найти действующий адрес на площадку Кракен. Запомнив эту страницу, вы навсегда избавите себя от необходимости выискивать зеркала на посторонних ресурсах, подвергая риску своей безопасностью.
Othex
16 Oct 25 at 1:46 pm
купить диплом диспетчера [url=http://rudik-diplom11.ru]купить диплом диспетчера[/url] .
Diplomi_ixMi
16 Oct 25 at 1:47 pm
купить проведенный диплом о высшем образовании [url=https://frei-diplom5.ru]купить проведенный диплом о высшем образовании[/url] .
Diplomi_itPa
16 Oct 25 at 1:48 pm
I’m really enjoying the theme/design of your blog. Do you ever run into any internet browser compatibility problems?
A number of my blog audience have complained about my blog not operating correctly in Explorer but looks great in Chrome.
Do you have any ideas to help fix this problem?
knowledge
16 Oct 25 at 1:49 pm
потолочкин натяжные потолки нижний новгород отзывы клиентов [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru/]natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_lqma
16 Oct 25 at 1:51 pm
Чтобы войти на официальный сайт 1xBet,
бетторам из России необходимо обойти блокировку.
1xbet рабочее зеркало
16 Oct 25 at 1:52 pm
потолочкин потолки [url=https://stretch-ceilings-nizhniy-novgorod-1.ru/]stretch-ceilings-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_pyOn
16 Oct 25 at 1:52 pm
где купить диплом [url=www.rudik-diplom8.ru]где купить диплом[/url] .
Diplomi_vyMt
16 Oct 25 at 1:53 pm
купить диплом с занесением в реестр отзывы [url=www.frei-diplom6.ru]купить диплом с занесением в реестр отзывы[/url] .
Diplomi_wfOl
16 Oct 25 at 1:53 pm
купить диплом в кызыле [url=www.rudik-diplom11.ru/]купить диплом в кызыле[/url] .
Diplomi_fdMi
16 Oct 25 at 1:57 pm
mostbet skachat app [url=https://www.mostbet4185.ru]https://www.mostbet4185.ru[/url]
mostbet_uz_ther
16 Oct 25 at 1:58 pm
https://t.me/Official_1xbet_1xbet/s/610
AlbertEnark
16 Oct 25 at 1:59 pm
https://t.me/Official_1xbet_1xbet/s/882
AlbertEnark
16 Oct 25 at 2:00 pm
just click the up coming article
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
just click the up coming article
16 Oct 25 at 2:01 pm
купить диплом психолога [url=www.rudik-diplom11.ru/]купить диплом психолога[/url] .
Diplomi_xcMi
16 Oct 25 at 2:04 pm
The caring environment at OMT urges curiosity іn mathematics, transforming Singapore students
гight intо enthusiastic learners inspired tⲟ accomplish top test results.
Register tⲟdɑү in OMT’s standalone e-learning programs and view your grades soar thгough limitless access t᧐ premium,
syllabus-aligned material.
Given thɑt mathematics plays аn essential function in Singapore’ѕ economic development аnd progress, purchasing specialized math tuition equips students ԝith the analytical skills required tߋ thrive in a
competitive landscape.
primaryschool math tuition builds test endurance tһrough timed drills,
simulating tһe PSLE’ѕ tᴡo-paper format ɑnd helping students manage
tіme efficiently.
Ԝith tһe O Level math curriculum ѕometimes advancing, tuition қeeps trainees updated ߋn modifications,
guaranteeing tһey are well-prepared foг present layouts.
Junior college math tuition promotes vital assuming skills required tօ
fiх non-routine troubles that typically appear in A Level mathematics assessments.
Ultimately, OMT’ѕ distinct proprietary syllabus matches tһe Singapore MOE educational
program by promoting independent thinkers furnished f᧐r
lifelong mathematical success.
Multi-device compatibility leh, ѕo switch over from laptop computеr to phone and ҝeep
increasing thoѕe grades.
In a fаst-paced Singapore classroom, math tuition ɡives
the slower, thorough explanations neеded to build confidence fօr examinations.
Feel free tо visit my web-site: а level maths
tuition (http://www.dumascoop.com)
www.dumascoop.com
16 Oct 25 at 2:04 pm
купить диплом в сарапуле [url=https://rudik-diplom8.ru]купить диплом в сарапуле[/url] .
Diplomi_nkMt
16 Oct 25 at 2:05 pm
https://t.me/Official_1xbet_1xbet/s/1118
AlbertEnark
16 Oct 25 at 2:05 pm
как купить легальный диплом о среднем образовании [url=www.frei-diplom6.ru/]www.frei-diplom6.ru/[/url] .
Diplomi_lwOl
16 Oct 25 at 2:05 pm
https://t.me/Official_1xbet_1xbet/s/320
AlbertEnark
16 Oct 25 at 2:05 pm
webrevive.click – Good job on the layout, looks polished and built with care.
Rodney Kewal
16 Oct 25 at 2:08 pm
just click the next web page
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
just click the next web page
16 Oct 25 at 2:08 pm
Цікавитесь кулінарією? Завітайте на кулінарний блог MeatPortal – https://meatportal.com.ua Знайдіть нові рецепти, корисні поради починаючим і досвідченим кулінарам. Збирайте нові рецепти до своєї колекції, щоб смачно і корисно годувати сім’ю
saxupGot
16 Oct 25 at 2:09 pm
натяжные потолки нижний новгород отзывы [url=www.natyazhnye-potolki-nizhniy-novgorod-1.ru/]натяжные потолки нижний новгород отзывы[/url] .
natyajnie potolki nijnii novgorod_htma
16 Oct 25 at 2:09 pm
потолочкин потолки натяжные [url=https://stretch-ceilings-nizhniy-novgorod-1.ru/]https://stretch-ceilings-nizhniy-novgorod-1.ru/[/url] .
natyajnie potolki nijnii novgorod_xbOn
16 Oct 25 at 2:10 pm
mostbet app skachat [url=http://mostbet4182.ru]mostbet app skachat[/url]
mostbet_uz_nckt
16 Oct 25 at 2:10 pm
Дизайнерский ремонт: искусство преображения пространства
Дизайн интерьера играет важную роль в создании комфортной и уютной атмосферы в доме. Сегодня мы поговорим о таком понятии, как дизайнерский ремонт, который позволяет превратить обычное жилье в уникальное пространство, отражающее индивидуальность владельца.
[url=https://designapartment.ru ]дизайнерский ремонт квартиры под ключ[/url]
Что такое дизайнерский ремонт?
Дизайнерский ремонт — это комплекс работ, направленных на создание оригинального дизайна помещения. Это не просто обновление отделки, а полноценный творческий процесс, включающий разработку концепции, подбор материалов и мебели, а также реализацию проекта.
Ключевые особенности дизайнерского ремонта:
[url=https://designapartment.ru ]дизайнерский ремонт квартиры под ключ[/url]
– Индивидуальный подход к каждому проекту.
– Использование качественных материалов и современных технологий.
– Создание уникального стиля, соответствующего вкусам заказчика.
– Оптимизация пространства для максимального комфорта и функциональности.
Виды дизайнерских ремонтов
[url=https://designapartment.ru]дизайнерский ремонт комнатной квартиры москва[/url]
Существует несколько видов дизайнерских ремонтов, каждый из которых имеет свои особенности и преимущества.
#1 Дизайнерский ремонт квартиры
Это наиболее распространенный вид ремонта, подходящий для тех, кто хочет обновить интерьер своей городской квартиры. Специалисты разрабатывают проект, учитывая размеры помещений, пожелания клиента и бюджет. Такой ремонт включает перепланировку, замену коммуникаций, отделочные работы и декорирование.
Пример дизайна: светлая гостиная с панорамными окнами, минималистичный дизайн кухни и спальни в стиле лофт.
#2 Дизайнерский ремонт дома
Такой ремонт предполагает полное преобразование жилого дома, начиная от фундамента и заканчивая крышей. Здесь важно учитывать архитектурные особенности здания, климатические условия региона и предпочтения владельцев. Часто используется экодизайн, натуральные материалы и энергосберегающие технологии.
Пример дизайна: просторный холл с камином, стеклянная веранда с видом на сад, спальня в пастельных тонах.
#3 Дизайнерский ремонт виллы
Ремонт вилл требует особого подхода, поскольку такие объекты часто расположены в живописных местах и имеют большую площадь. Важно сохранить гармонию с окружающей средой, используя природные материалы и цвета. Особое внимание уделяется созданию зон отдыха, бассейнов и садов.
Пример дизайна: роскошная вилла с бассейном, открытая терраса с видами на море, спальная зона в тропическом стиле.
#4 Дизайнерский ремонт коттеджа
Коттедж отличается от обычного дома наличием придомового участка и возможностью организации дополнительных функциональных зон. Ремонт коттеджей включает работу над фасадом, ландшафтом и внутренним пространством. Стили могут варьироваться от классики до хай-тека.
Пример дизайна: двухэтажный коттедж с мансардой, гостиная-столовая в скандинавском стиле, детская комната с игровой зоной.
#5 Дизайнерский ремонт пентхауса
Пентхаус — это элитное жилье, расположенное на верхних этажах зданий с панорамными видами. Для такого типа недвижимости характерны высокие потолки, большие окна и эксклюзивные элементы декора. Проектирование пентхауса требует учета особенностей конструкции здания и пожеланий клиентов относительно приватности и удобства.
Пример дизайна: современный пентхаус с открытой планировкой, кабинет с видом на город, зона отдыха с джакузи.
Заключение
Дизайнерский ремонт — это возможность создать идеальное пространство для жизни и отдыха. Независимо от того, хотите ли вы обновить квартиру, дом, виллу, коттедж или пентхаус, профессиональный подход гарантирует вам комфорт и эстетическое удовольствие на долгие годы.
дизайнерский ремонт
https://designapartment.ru
AaronRiz
16 Oct 25 at 2:10 pm
hi!,I love your writing very much! proportion we keep in touch more approximately your post on AOL?
I need an expert in this space to solve my problem.
Maybe that’s you! Having a look forward to peer you.
rent wedding car
16 Oct 25 at 2:13 pm
boostengine.click – Site loads fast on mobile too, which is always a plus for me.
Karen Sunniga
16 Oct 25 at 2:15 pm
mostbet сайт [url=http://mostbet4185.ru]http://mostbet4185.ru[/url]
mostbet_uz_kber
16 Oct 25 at 2:15 pm
В статье представлены ключевые моменты по актуальной теме, дополненные советами экспертов и ссылками на дополнительные ресурсы. Цель материала — дать читателю инструменты для самостоятельного развития и принятия осознанных решений.
Это ещё не всё… – https://seointellect.com/2023/04/09/digital-marketing-made-easy-let-our-team-handle
Haroldjop
16 Oct 25 at 2:15 pm
Приобрести диплом о высшем образовании мы поможем. Купить диплом электроэнергетика – [url=http://diplomybox.com/diplom-elektroenergetika/]diplomybox.com/diplom-elektroenergetika[/url]
Cazrfvl
16 Oct 25 at 2:16 pm