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=www.frei-diplom5.ru]купить диплом с занесением в реестр новосибирск[/url] .
Diplomi_rnPa
21 Oct 25 at 6:55 am
купить диплом в архангельске [url=http://rudik-diplom11.ru/]купить диплом в архангельске[/url] .
Diplomi_xgMi
21 Oct 25 at 6:55 am
купить диплом в петропавловске-камчатском [url=http://www.rudik-diplom1.ru]купить диплом в петропавловске-камчатском[/url] .
Diplomi_gwer
21 Oct 25 at 6:57 am
купить диплом с проводкой меня [url=http://www.frei-diplom4.ru]купить диплом с проводкой меня[/url] .
Diplomi_hyOl
21 Oct 25 at 6:58 am
купить диплом в юрге [url=https://rudik-diplom10.ru/]купить диплом в юрге[/url] .
Diplomi_faSa
21 Oct 25 at 7:00 am
купить диплом в кемерово [url=http://rudik-diplom4.ru/]купить диплом в кемерово[/url] .
Diplomi_ufOr
21 Oct 25 at 7:01 am
купить легальный диплом [url=http://frei-diplom5.ru]купить легальный диплом[/url] .
Diplomi_shPa
21 Oct 25 at 7:03 am
купить дипломы о высшем образовании цена [url=https://www.rudik-diplom11.ru]купить дипломы о высшем образовании цена[/url] .
Diplomi_naMi
21 Oct 25 at 7:03 am
купить диплом моряка [url=rudik-diplom8.ru]купить диплом моряка[/url] .
Diplomi_cqMt
21 Oct 25 at 7:04 am
Как купить Лирика в Красногорскии?Смотрите, что нашел – сайт https://radio-rock.ru
. Цены нормальные, доставку обещают. Может, кто-то тестил у них? Насколько чистый товар?
Stevenref
21 Oct 25 at 7:05 am
migliori farmacie online 2024 [url=https://pilloleverdi.shop/#]farmacia online italiana Cialis[/url] compresse per disfunzione erettile
GeorgeHot
21 Oct 25 at 7:05 am
firma seo [url=https://www.seo-prodvizhenie-reiting.ru]firma seo[/url] .
seo prodvijenie reiting_reEa
21 Oct 25 at 7:06 am
рейтинг seo агентств [url=https://reiting-seo-agentstv.ru/]рейтинг seo агентств[/url] .
reiting seo agentstv_wmsa
21 Oct 25 at 7:06 am
купить диплом техникума в тамбове [url=www.frei-diplom12.ru/]купить диплом техникума в тамбове[/url] .
Diplomi_vuPt
21 Oct 25 at 7:06 am
Dived into Minotaurus presale; the 60B total supply with 60% allocated smartly. $MTAUR’s vesting prevents dumps. Loving the endless runner mechanics.
minotaurus presale
WilliamPargy
21 Oct 25 at 7:07 am
Дизайнерский ремонт: искусство преображения пространства
Дизайн интерьера играет важную роль в создании комфортной и уютной атмосферы в доме. Сегодня мы поговорим о таком понятии, как дизайнерский ремонт, который позволяет превратить обычное жилье в уникальное пространство, отражающее индивидуальность владельца.
[url=https://designapartment.ru]дизайнерский ремонт коттеджа под ключ[/url]
Что такое дизайнерский ремонт?
Дизайнерский ремонт — это комплекс работ, направленных на создание оригинального дизайна помещения. Это не просто обновление отделки, а полноценный творческий процесс, включающий разработку концепции, подбор материалов и мебели, а также реализацию проекта.
Ключевые особенности дизайнерского ремонта:
[url=https://designapartment.ru]дизайнерский ремонт квартиры москва[/url]
– Индивидуальный подход к каждому проекту.
– Использование качественных материалов и современных технологий.
– Создание уникального стиля, соответствующего вкусам заказчика.
– Оптимизация пространства для максимального комфорта и функциональности.
Виды дизайнерских ремонтов
[url=https://designapartment.ru]дизайнерский ремонт под ключ цена[/url]
Существует несколько видов дизайнерских ремонтов, каждый из которых имеет свои особенности и преимущества.
#1 Дизайнерский ремонт квартиры
Это наиболее распространенный вид ремонта, подходящий для тех, кто хочет обновить интерьер своей городской квартиры. Специалисты разрабатывают проект, учитывая размеры помещений, пожелания клиента и бюджет. Такой ремонт включает перепланировку, замену коммуникаций, отделочные работы и декорирование.
Пример дизайна: светлая гостиная с панорамными окнами, минималистичный дизайн кухни и спальни в стиле лофт.
#2 Дизайнерский ремонт дома
Такой ремонт предполагает полное преобразование жилого дома, начиная от фундамента и заканчивая крышей. Здесь важно учитывать архитектурные особенности здания, климатические условия региона и предпочтения владельцев. Часто используется экодизайн, натуральные материалы и энергосберегающие технологии.
Пример дизайна: просторный холл с камином, стеклянная веранда с видом на сад, спальня в пастельных тонах.
#3 Дизайнерский ремонт виллы
Ремонт вилл требует особого подхода, поскольку такие объекты часто расположены в живописных местах и имеют большую площадь. Важно сохранить гармонию с окружающей средой, используя природные материалы и цвета. Особое внимание уделяется созданию зон отдыха, бассейнов и садов.
Пример дизайна: роскошная вилла с бассейном, открытая терраса с видами на море, спальная зона в тропическом стиле.
#4 Дизайнерский ремонт коттеджа
Коттедж отличается от обычного дома наличием придомового участка и возможностью организации дополнительных функциональных зон. Ремонт коттеджей включает работу над фасадом, ландшафтом и внутренним пространством. Стили могут варьироваться от классики до хай-тека.
Пример дизайна: двухэтажный коттедж с мансардой, гостиная-столовая в скандинавском стиле, детская комната с игровой зоной.
#5 Дизайнерский ремонт пентхауса
Пентхаус — это элитное жилье, расположенное на верхних этажах зданий с панорамными видами. Для такого типа недвижимости характерны высокие потолки, большие окна и эксклюзивные элементы декора. Проектирование пентхауса требует учета особенностей конструкции здания и пожеланий клиентов относительно приватности и удобства.
Пример дизайна: современный пентхаус с открытой планировкой, кабинет с видом на город, зона отдыха с джакузи.
Заключение
Дизайнерский ремонт — это возможность создать идеальное пространство для жизни и отдыха. Независимо от того, хотите ли вы обновить квартиру, дом, виллу, коттедж или пентхаус, профессиональный подход гарантирует вам комфорт и эстетическое удовольствие на долгие годы.
https://designapartment.ru
дизайнерский ремонт цена
Kennethwep
21 Oct 25 at 7:08 am
В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
Эксклюзивная информация – https://centresocialauterive.fr/le-foyer
AnthonyTic
21 Oct 25 at 7:08 am
Wonderful beat ! I wish to apprentice while you amend your web site, how could i subscribe for a
blog web site? The account helped me a acceptable deal.
I had been a little bit acquainted of this your broadcast offered bright clear idea
roof repair services
21 Oct 25 at 7:09 am
компания seo [url=reiting-seo-kompanii.ru]компания seo[/url] .
reiting seo kompanii_lcsn
21 Oct 25 at 7:09 am
где купить диплом техникума в уфе [url=http://www.frei-diplom10.ru]где купить диплом техникума в уфе[/url] .
Diplomi_bmEa
21 Oct 25 at 7:09 am
сео продвижение заказать москва [url=reiting-seo-agentstv-moskvy.ru]reiting-seo-agentstv-moskvy.ru[/url] .
reiting seo agentstv moskvi_sqMl
21 Oct 25 at 7:09 am
Great weblog here! Also your website rather a lot up fast!
What web host are you using? Can I am getting your associate
link on your host? I wish my site loaded up as quickly as yours lol
littleton roof repairs
21 Oct 25 at 7:09 am
купить диплом в находке [url=http://www.rudik-diplom10.ru]купить диплом в находке[/url] .
Diplomi_aoSa
21 Oct 25 at 7:09 am
топ digital агентств [url=luchshie-digital-agencstva.ru]топ digital агентств[/url] .
lychshie digital agentstva_bxoi
21 Oct 25 at 7:14 am
professionalgrowthhub.bond – I found a few interesting articles, will dive deeper into the learning resources soon.
Dannie Bejger
21 Oct 25 at 7:15 am
купить проведенный диплом весь [url=http://www.frei-diplom5.ru]купить проведенный диплом весь[/url] .
Diplomi_bfPa
21 Oct 25 at 7:17 am
купить диплом в уфе [url=http://rudik-diplom11.ru/]купить диплом в уфе[/url] .
Diplomi_saMi
21 Oct 25 at 7:18 am
cialis generico [url=https://tadalafiloexpress.shop/#]Cialis genérico económico[/url] comprar cialis
GeorgeHot
21 Oct 25 at 7:18 am
купить диплом в ревде [url=https://www.rudik-diplom4.ru]купить диплом в ревде[/url] .
Diplomi_hvOr
21 Oct 25 at 7:20 am
купить диплом техникума в красноярске [url=http://frei-diplom12.ru/]купить диплом техникума в красноярске[/url] .
Diplomi_vzPt
21 Oct 25 at 7:21 am
Купить диплом техникума в Запорожье [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_rsea
21 Oct 25 at 7:21 am
кто нибудь работает медсестрой по купленному диплому [url=https://frei-diplom13.ru/]https://frei-diplom13.ru/[/url] .
Diplomi_kbkt
21 Oct 25 at 7:21 am
купить диплом в северодвинске [url=http://www.rudik-diplom10.ru]купить диплом в северодвинске[/url] .
Diplomi_ewSa
21 Oct 25 at 7:23 am
Its not my first time to visit this website, i am browsing this web page dailly and obtain good information from here
everyday.
situs slot
21 Oct 25 at 7:25 am
купить диплом стоматолога [url=rudik-diplom3.ru]купить диплом стоматолога[/url] .
Diplomi_bcei
21 Oct 25 at 7:26 am
кракен Россия
кракен актуальная ссылка
JamesDaync
21 Oct 25 at 7:26 am
где купить диплом о техникуме [url=https://frei-diplom10.ru]где купить диплом о техникуме[/url] .
Diplomi_taEa
21 Oct 25 at 7:27 am
modernlifestylezone.shop – Would like to see more customer reviews and detailed shipping info though.
Bob Durward
21 Oct 25 at 7:27 am
купить проведенный диплом всеми [url=https://frei-diplom6.ru/]купить проведенный диплом всеми[/url] .
Diplomi_qiOl
21 Oct 25 at 7:28 am
acquistare Cialis online Italia: tadalafil senza ricetta – compresse per disfunzione erettile
RaymondNit
21 Oct 25 at 7:28 am
купить диплом с реестром спб [url=http://frei-diplom4.ru]купить диплом с реестром спб[/url] .
Diplomi_sxOl
21 Oct 25 at 7:30 am
пин ап получить бонус через промо [url=http://pinup5007.ru]пин ап получить бонус через промо[/url]
pin_up_uz_dksr
21 Oct 25 at 7:30 am
Someone essentially lend a hand to make critically articles I’d state.
This is the very first time I frequented your web page and up to now?
I surprised with the research you made to make this particular submit incredible.
Great job!
buôn bán nội tạng
21 Oct 25 at 7:31 am
Great site you have got here.. It’s hard to find high-quality writing like yours nowadays.
I honestly appreciate people like you! Take care!!
buôn bán nội tạng
21 Oct 25 at 7:31 am
топ диджитал агентств россии [url=https://www.luchshie-digital-agencstva.ru]топ диджитал агентств россии[/url] .
lychshie digital agentstva_djoi
21 Oct 25 at 7:34 am
You really make it appear really easy together with your presentation however I to find this matter to be really something
that I feel I’d never understand. It seems too complex and very vast
for me. I am taking a look forward to your next put up,
I will attempt to get the grasp of it!
buôn bán nội tạng
21 Oct 25 at 7:35 am
купить диплом в салавате [url=http://rudik-diplom3.ru]купить диплом в салавате[/url] .
Diplomi_owei
21 Oct 25 at 7:35 am
seo оптимизация сайта москва [url=http://reiting-seo-agentstv-moskvy.ru]http://reiting-seo-agentstv-moskvy.ru[/url] .
reiting seo agentstv moskvi_bxMl
21 Oct 25 at 7:35 am
В данной обзорной статье представлены интригующие факты, которые не оставят вас равнодушными. Мы критикуем и анализируем события, которые изменили наше восприятие мира. Узнайте, что стоит за новыми открытиями и как они могут изменить ваше восприятие реальности.
Детальнее – https://trelewelectronica.com.ar/video/the-bug-bad-ft-flowdan-official-video
CarltonOvert
21 Oct 25 at 7:37 am
купить диплом в сочи [url=https://rudik-diplom4.ru/]купить диплом в сочи[/url] .
Diplomi_snOr
21 Oct 25 at 7:37 am