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!
Snagged more $MTAUR; referrals pay. Presale’s value jumps. Minotaur customizable.
minotaurus presale
WilliamPargy
20 Oct 25 at 11:35 am
оформление перепланировки квартиры в москве [url=www.proekt-pereplanirovki-kvartiry11.ru]оформление перепланировки квартиры в москве[/url] .
proekt pereplanirovki kvartiri_lzot
20 Oct 25 at 11:35 am
cd playing clock radio [url=https://alarm-radio-clocks.com]https://alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_gbOa
20 Oct 25 at 11:38 am
купить диплом в россоши [url=www.rudik-diplom10.ru/]купить диплом в россоши[/url] .
Diplomi_ktSa
20 Oct 25 at 11:40 am
1win android yuklab olish [url=http://1win5510.ru/]1win android yuklab olish[/url]
1win_uz_fcsi
20 Oct 25 at 11:40 am
как купить диплом техникума отзывы [url=www.frei-diplom11.ru/]как купить диплом техникума отзывы[/url] .
Diplomi_ijsa
20 Oct 25 at 11:41 am
Дизайнерский ремонт: искусство преображения пространства
Дизайн интерьера играет важную роль в создании комфортной и уютной атмосферы в доме. Сегодня мы поговорим о таком понятии, как дизайнерский ремонт, который позволяет превратить обычное жилье в уникальное пространство, отражающее индивидуальность владельца.
[url=https://designapartment.ru]дизайнерский ремонт квартиры москва[/url]
Что такое дизайнерский ремонт?
Дизайнерский ремонт — это комплекс работ, направленных на создание оригинального дизайна помещения. Это не просто обновление отделки, а полноценный творческий процесс, включающий разработку концепции, подбор материалов и мебели, а также реализацию проекта.
Ключевые особенности дизайнерского ремонта:
[url=https://designapartment.ru]дизайнерский ремонт комнатной квартиры[/url]
– Индивидуальный подход к каждому проекту.
– Использование качественных материалов и современных технологий.
– Создание уникального стиля, соответствующего вкусам заказчика.
– Оптимизация пространства для максимального комфорта и функциональности.
Виды дизайнерских ремонтов
[url=https://designapartment.ru]дизайнерский ремонт однокомнатной квартиры[/url]
Существует несколько видов дизайнерских ремонтов, каждый из которых имеет свои особенности и преимущества.
#1 Дизайнерский ремонт квартиры
Это наиболее распространенный вид ремонта, подходящий для тех, кто хочет обновить интерьер своей городской квартиры. Специалисты разрабатывают проект, учитывая размеры помещений, пожелания клиента и бюджет. Такой ремонт включает перепланировку, замену коммуникаций, отделочные работы и декорирование.
Пример дизайна: светлая гостиная с панорамными окнами, минималистичный дизайн кухни и спальни в стиле лофт.
#2 Дизайнерский ремонт дома
Такой ремонт предполагает полное преобразование жилого дома, начиная от фундамента и заканчивая крышей. Здесь важно учитывать архитектурные особенности здания, климатические условия региона и предпочтения владельцев. Часто используется экодизайн, натуральные материалы и энергосберегающие технологии.
Пример дизайна: просторный холл с камином, стеклянная веранда с видом на сад, спальня в пастельных тонах.
#3 Дизайнерский ремонт виллы
Ремонт вилл требует особого подхода, поскольку такие объекты часто расположены в живописных местах и имеют большую площадь. Важно сохранить гармонию с окружающей средой, используя природные материалы и цвета. Особое внимание уделяется созданию зон отдыха, бассейнов и садов.
Пример дизайна: роскошная вилла с бассейном, открытая терраса с видами на море, спальная зона в тропическом стиле.
#4 Дизайнерский ремонт коттеджа
Коттедж отличается от обычного дома наличием придомового участка и возможностью организации дополнительных функциональных зон. Ремонт коттеджей включает работу над фасадом, ландшафтом и внутренним пространством. Стили могут варьироваться от классики до хай-тека.
Пример дизайна: двухэтажный коттедж с мансардой, гостиная-столовая в скандинавском стиле, детская комната с игровой зоной.
#5 Дизайнерский ремонт пентхауса
Пентхаус — это элитное жилье, расположенное на верхних этажах зданий с панорамными видами. Для такого типа недвижимости характерны высокие потолки, большие окна и эксклюзивные элементы декора. Проектирование пентхауса требует учета особенностей конструкции здания и пожеланий клиентов относительно приватности и удобства.
Пример дизайна: современный пентхаус с открытой планировкой, кабинет с видом на город, зона отдыха с джакузи.
Заключение
Дизайнерский ремонт — это возможность создать идеальное пространство для жизни и отдыха. Независимо от того, хотите ли вы обновить квартиру, дом, виллу, коттедж или пентхаус, профессиональный подход гарантирует вам комфорт и эстетическое удовольствие на долгие годы.
https://designapartment.ru
дизайнерский ремонт коттеджа москва
RobertVex
20 Oct 25 at 11:43 am
sichere sportwetten tipps Heute – https://www.contenero.ro/ – in österreich
Https://www.contenero.ro/
20 Oct 25 at 11:44 am
https://t.me/reiting_top10_casino/7
EdwardAdete
20 Oct 25 at 11:44 am
stereo clock radio alarm [url=www.alarm-radio-clocks.com]www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_tqOa
20 Oct 25 at 11:45 am
диплом купить медицинского техникума [url=http://frei-diplom8.ru/]диплом купить медицинского техникума[/url] .
Diplomi_iusr
20 Oct 25 at 11:45 am
how to get cheap celexa tablets
how can i get cheap celexa for sale
20 Oct 25 at 11:46 am
1win uz bonus [url=http://1win5510.ru/]http://1win5510.ru/[/url]
1win_uz_thsi
20 Oct 25 at 11:48 am
купить диплом геодезиста [url=http://rudik-diplom2.ru/]купить диплом геодезиста[/url] .
Diplomi_ympi
20 Oct 25 at 11:49 am
проект перепланировки для согласования [url=https://proekt-pereplanirovki-kvartiry11.ru/]https://proekt-pereplanirovki-kvartiry11.ru/[/url] .
proekt pereplanirovki kvartiri_skot
20 Oct 25 at 11:51 am
kraken вход
кракен онион
JamesDaync
20 Oct 25 at 11:52 am
купить диплом дорожного техникума [url=https://frei-diplom11.ru/]купить диплом дорожного техникума[/url] .
Diplomi_ggsa
20 Oct 25 at 11:54 am
купить диплом о техническом образовании с занесением в реестр [url=www.frei-diplom6.ru/]www.frei-diplom6.ru/[/url] .
Diplomi_ahOl
20 Oct 25 at 11:54 am
Cialis générique pas cher: pharmacie qui vend du cialis sans ordonnance – acheter Cialis en ligne France
JosephPseus
20 Oct 25 at 11:54 am
драгон мани казино
NormanmuP
20 Oct 25 at 11:55 am
Cialis genérico económico [url=https://tadalafiloexpress.com/#]comprar cialis[/url] Tadalafilo Express
GeorgeHot
20 Oct 25 at 11:57 am
купить диплом в стерлитамаке [url=http://www.rudik-diplom2.ru]купить диплом в стерлитамаке[/url] .
Diplomi_mxpi
20 Oct 25 at 11:58 am
1win ilova skachat [url=https://www.1win5510.ru]1win ilova skachat[/url]
1win_uz_xvsi
20 Oct 25 at 11:58 am
экстренный вывод из запоя
vivod-iz-zapoya-smolensk024.ru
лечение запоя смоленск
vivodzapojsmolenskNeT
20 Oct 25 at 11:58 am
The Minotaurus ICO referral system is paying off big; got extra tokens from invites. $MTAUR’s utility in power-ups makes it more than hype. This project’s got legs.
minotaurus presale
WilliamPargy
20 Oct 25 at 11:59 am
There is certainly a lot to learn about this issue.
I love all the points you made.
mm99
20 Oct 25 at 12:02 pm
купить диплом с занесением в реестр ростов [url=http://frei-diplom6.ru]купить диплом с занесением в реестр ростов[/url] .
Diplomi_orOl
20 Oct 25 at 12:04 pm
проектирование перепланировки в квартире [url=https://proekt-pereplanirovki-kvartiry11.ru]https://proekt-pereplanirovki-kvartiry11.ru[/url] .
proekt pereplanirovki kvartiri_cqot
20 Oct 25 at 12:06 pm
купить диплом в рубцовске [url=http://rudik-diplom14.ru/]http://rudik-diplom14.ru/[/url] .
Diplomi_erea
20 Oct 25 at 12:08 pm
купить диплом агронома [url=http://rudik-diplom10.ru/]купить диплом агронома[/url] .
Diplomi_itSa
20 Oct 25 at 12:08 pm
Выездная бригада действует незаметно: гражданская одежда, быстрый вход без обсуждений на лестничных площадках, краткая коммуникация. На домофон и документы — нейтральные указания, на чеках — общие формулировки. Мы показываем, что конфиденциальность — не обещание, а набор конкретных технологий, встроенных в процесс помощи.
Получить больше информации – https://narkologicheskaya-klinika-murmansk15.ru
PatrickNip
20 Oct 25 at 12:09 pm
купить диплом в сургуте [url=www.rudik-diplom15.ru/]купить диплом в сургуте[/url] .
Diplomi_vrPi
20 Oct 25 at 12:10 pm
купить официальный диплом с занесением в реестр [url=frei-diplom6.ru]frei-diplom6.ru[/url] .
Diplomi_ldOl
20 Oct 25 at 12:10 pm
kraken онлайн
кракен вход
JamesDaync
20 Oct 25 at 12:10 pm
clock radio with remote [url=alarm-radio-clocks.com]alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_qaOa
20 Oct 25 at 12:12 pm
Острый этап разбит на небольшие «окна» с измеримыми целями. Это убирает неопределённость и дисциплинирует процесс: пациент знает, что будет происходить, когда будет проверка и по каким маркерам оценивается успех. Если ответ «плоский», корректируется один параметр, а затем обязательно следует повторная оценка в оговорённое время.
Подробнее можно узнать тут – https://narkologicheskaya-klinika-v-murmanske15.ru/narkologicheskij-dispanser-g-murmansk
Michaelset
20 Oct 25 at 12:13 pm
These are really fantastic ideas in about blogging. You have touched some pleasant
things here. Any way keep up wrinting.
kra39 сс
20 Oct 25 at 12:16 pm
Does your blog have a contact page? I’m having a
tough time locating it but, I’d like to send you an e-mail.
I’ve got some suggestions for your blog you might be interested in hearing.
Either way, great site and I look forward to seeing it develop over time.
pool installation near me
20 Oct 25 at 12:16 pm
Петрозаводск добавляет нюансы: влажные сумерки, ветер от Онежского озера, «звонкие» подъезды старого фонда. Поэтому бригада «СеверКар Медикус» приезжает в гражданской одежде, быстро и без лишних фраз. Координатор заранее уточняет код домофона, парковку, «окна связи» для близких; рекомендует приглушить верхний свет, подготовить воду комнатной температуры и свободный доступ к розетке. Такой «тихий сценарий» снижает сенсорную нагрузку, сглаживает пульсовые «пики» к вечеру и помогает заснуть без избыточной фармакологии.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-petrozavodsk15.ru/]наркологический вывод из запоя[/url]
Richardsor
20 Oct 25 at 12:18 pm
купить диплом электромонтажника [url=https://rudik-diplom10.ru/]купить диплом электромонтажника[/url] .
Diplomi_trSa
20 Oct 25 at 12:18 pm
You really make it seem so easy with your presentation but I find this topic to be really something which I think I would never understand.
It seems too complex and very broad for me.
I’m looking forward for your next post, I’ll
try to get the hang of it!
certified laser courses
20 Oct 25 at 12:19 pm
dragon money
NormanmuP
20 Oct 25 at 12:20 pm
farmacia online italiana Cialis: cialis generico – cialis
RaymondNit
20 Oct 25 at 12:21 pm
https://www.blogger.com/profile/05730397322207586342
Juliohow
20 Oct 25 at 12:21 pm
https://easton1m30hov5.evawiki.com/user
JamesMal
20 Oct 25 at 12:22 pm
купить свидетельство о рождении ссср [url=http://www.rudik-diplom15.ru]купить свидетельство о рождении ссср[/url] .
Diplomi_saPi
20 Oct 25 at 12:23 pm
можно ли купить диплом [url=http://www.rudik-diplom14.ru]можно ли купить диплом[/url] .
Diplomi_lvea
20 Oct 25 at 12:24 pm
cd playing clock radio [url=https://alarm-radio-clocks.com]https://alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_iwOa
20 Oct 25 at 12:24 pm
click here!
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
click here!
20 Oct 25 at 12:24 pm
Awesome! Its actually amazing piece of writing, I
have got much clear idea regarding from this post.
excavation haul-out dirt service
20 Oct 25 at 12:27 pm