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!
Je suis transporte par Donbet Casino, c’est une deflagration de fun absolu. Il y a une avalanche de jeux captivants, offrant des sessions live qui electrisent. Le service client est d’une efficacite foudroyante, garantissant un support d’une puissance rare. Les gains arrivent a une vitesse supersonique, de temps a autre des tours gratuits en plus feraient vibrer. Dans l’ensemble, Donbet Casino est une plateforme qui fait trembler les sens pour les joueurs en quete d’intensite ! A noter l’interface est fluide comme un torrent, amplifie l’immersion dans un tourbillon de fun.
donbet code promo|
BlitzEchoR6zef
21 Oct 25 at 4:05 am
купить диплом вуза с проводкой [url=frei-diplom4.ru]frei-diplom4.ru[/url] .
Diplomi_xzOl
21 Oct 25 at 4:06 am
топ агентств seo продвижения [url=http://www.reiting-seo-kompaniy.ru]http://www.reiting-seo-kompaniy.ru[/url] .
reiting seo kompanii_kfon
21 Oct 25 at 4:07 am
продвижение сайта топ 1 [url=seo-prodvizhenie-reiting.ru]продвижение сайта топ 1[/url] .
seo prodvijenie reiting_plEa
21 Oct 25 at 4:07 am
купить диплом в твери [url=www.rudik-diplom8.ru]купить диплом в твери[/url] .
Diplomi_ufMt
21 Oct 25 at 4:07 am
купить диплом с занесением реестра [url=http://frei-diplom5.ru]купить диплом с занесением реестра[/url] .
Diplomi_dmPa
21 Oct 25 at 4:08 am
купить диплом института [url=rudik-diplom11.ru]купить диплом института[/url] .
Diplomi_nkMi
21 Oct 25 at 4:08 am
кракен онлайн
kraken зеркало
JamesDaync
21 Oct 25 at 4:09 am
купить диплом в буденновске [url=www.rudik-diplom4.ru]www.rudik-diplom4.ru[/url] .
Diplomi_mxOr
21 Oct 25 at 4:09 am
купить диплом повара-кондитера [url=www.rudik-diplom1.ru/]купить диплом повара-кондитера[/url] .
Diplomi_eaer
21 Oct 25 at 4:10 am
Дизайнерский ремонт: искусство преображения пространства
Дизайн интерьера играет важную роль в создании комфортной и уютной атмосферы в доме. Сегодня мы поговорим о таком понятии, как дизайнерский ремонт, который позволяет превратить обычное жилье в уникальное пространство, отражающее индивидуальность владельца.
[url=https://designapartment.ru ]дизайнерский ремонт однокомнатной квартиры москва[/url]
Что такое дизайнерский ремонт?
Дизайнерский ремонт — это комплекс работ, направленных на создание оригинального дизайна помещения. Это не просто обновление отделки, а полноценный творческий процесс, включающий разработку концепции, подбор материалов и мебели, а также реализацию проекта.
Ключевые особенности дизайнерского ремонта:
– Индивидуальный подход к каждому проекту.
– Использование качественных материалов и современных технологий.
– Создание уникального стиля, соответствующего вкусам заказчика.
– Оптимизация пространства для максимального комфорта и функциональности.
Виды дизайнерских ремонтов
[url=https://designapartment.ru ]дизайнерский ремонт квартиры под ключ[/url]
Существует несколько видов дизайнерских ремонтов, каждый из которых имеет свои особенности и преимущества.
#1 Дизайнерский ремонт квартиры
Это наиболее распространенный вид ремонта, подходящий для тех, кто хочет обновить интерьер своей городской квартиры. Специалисты разрабатывают проект, учитывая размеры помещений, пожелания клиента и бюджет. Такой ремонт включает перепланировку, замену коммуникаций, отделочные работы и декорирование.
Пример дизайна: светлая гостиная с панорамными окнами, минималистичный дизайн кухни и спальни в стиле лофт.
#2 Дизайнерский ремонт дома
Такой ремонт предполагает полное преобразование жилого дома, начиная от фундамента и заканчивая крышей. Здесь важно учитывать архитектурные особенности здания, климатические условия региона и предпочтения владельцев. Часто используется экодизайн, натуральные материалы и энергосберегающие технологии.
Пример дизайна: просторный холл с камином, стеклянная веранда с видом на сад, спальня в пастельных тонах.
[url=https://designapartment.ru]дизайнерский ремонт цена[/url]
#3 Дизайнерский ремонт виллы
Ремонт вилл требует особого подхода, поскольку такие объекты часто расположены в живописных местах и имеют большую площадь. Важно сохранить гармонию с окружающей средой, используя природные материалы и цвета. Особое внимание уделяется созданию зон отдыха, бассейнов и садов.
Пример дизайна: роскошная вилла с бассейном, открытая терраса с видами на море, спальная зона в тропическом стиле.
#4 Дизайнерский ремонт коттеджа
Коттедж отличается от обычного дома наличием придомового участка и возможностью организации дополнительных функциональных зон. Ремонт коттеджей включает работу над фасадом, ландшафтом и внутренним пространством. Стили могут варьироваться от классики до хай-тека.
Пример дизайна: двухэтажный коттедж с мансардой, гостиная-столовая в скандинавском стиле, детская комната с игровой зоной.
#5 Дизайнерский ремонт пентхауса
Пентхаус — это элитное жилье, расположенное на верхних этажах зданий с панорамными видами. Для такого типа недвижимости характерны высокие потолки, большие окна и эксклюзивные элементы декора. Проектирование пентхауса требует учета особенностей конструкции здания и пожеланий клиентов относительно приватности и удобства.
Пример дизайна: современный пентхаус с открытой планировкой, кабинет с видом на город, зона отдыха с джакузи.
Заключение
Дизайнерский ремонт — это возможность создать идеальное пространство для жизни и отдыха. Независимо от того, хотите ли вы обновить квартиру, дом, виллу, коттедж или пентхаус, профессиональный подход гарантирует вам комфорт и эстетическое удовольствие на долгие годы.
https://designapartment.ru
дизайнерский ремонт однокомнатной квартиры
GeraldZek
21 Oct 25 at 4:11 am
купить диплом в михайловске [url=www.rudik-diplom10.ru]www.rudik-diplom10.ru[/url] .
Diplomi_xsSa
21 Oct 25 at 4:12 am
купить мухоморы На сайте muhomorus вы можете оформить заказ на мухоморы с доставкой по всей территории РФ. У нас выгодные предложения на экологически чистые продукты, которые помогут вам справиться с тревожностью, стрессом, депрессией, хронической усталостью и облегчат симптомы различных заболеваний. Необходимо отметить, что сушеные мухоморы не относятся к лекарственным средствам, их классифицируют как парафармацевтику, которая является альтернативным средством, используемым по личному усмотрению в качестве вспомогательной терапии. Все этапы – сбор, сушка, продажа и покупка – осуществляются абсолютно законно. Мы предлагаем вам приобрести микродозинг на законных основаниях.
GradyBus
21 Oct 25 at 4:14 am
купить медицинский диплом с занесением в реестр [url=https://frei-diplom5.ru/]купить медицинский диплом с занесением в реестр[/url] .
Diplomi_gtPa
21 Oct 25 at 4:14 am
Красивые девушки с профессиональными руками делают массаж настоящим наслаждением. Каждое прикосновение наполнено вниманием и заботой, чувствуешь гармонию тела и души. Атмосфера салона полностью погружает в релакс. Рекомендую, эро массаж заказать Новосиб – https://sibirka.com/. Очень понравилась девушка, красивая и милая.
Bobbyham
21 Oct 25 at 4:14 am
купить диплом в якутске [url=www.rudik-diplom11.ru/]купить диплом в якутске[/url] .
Diplomi_nmMi
21 Oct 25 at 4:15 am
купить проведенный диплом весь [url=http://www.frei-diplom3.ru]купить проведенный диплом весь[/url] .
Diplomi_tsKt
21 Oct 25 at 4:15 am
купить диплом о среднем специальном образовании с занесением в реестр [url=https://frei-diplom1.ru/]купить диплом о среднем специальном образовании с занесением в реестр[/url] .
Diplomi_tiOi
21 Oct 25 at 4:15 am
can you buy cheap dapsone without rx
cost dapsone tablets
21 Oct 25 at 4:15 am
загадки про музичні інструменти
Jamesstalm
21 Oct 25 at 4:16 am
pin up ijobiy sharhlar [url=http://pinup5008.ru/]http://pinup5008.ru/[/url]
pin_up_uz_xuSt
21 Oct 25 at 4:16 am
Формат лечения
Получить дополнительную информацию – [url=https://narkologicheskaya-klinika-sankt-peterburg14.ru/]запой наркологическая клиника санкт-петербург[/url]
Isaacunofs
21 Oct 25 at 4:16 am
top seo [url=https://reiting-seo-agentstv.ru]top seo[/url] .
reiting seo agentstv_bgsa
21 Oct 25 at 4:17 am
сео продвижение москва [url=www.reiting-seo-agentstv-moskvy.ru/]сео продвижение москва[/url] .
reiting seo agentstv moskvi_ikMl
21 Oct 25 at 4:19 am
кракен vk2
kraken android
JamesDaync
21 Oct 25 at 4:20 am
E28BET বাংলাদেশে স্বাগতম – আপনার জয়, সম্পূর্ণরূপে পরিশোধিত। আকর্ষণীয় বোনাস উপভোগ করুন, উত্তেজনাপূর্ণ গেম খেলুন এবং একটি ন্যায্য
ও আরামদায়ক অনলাইন বাজির অভিজ্ঞতা লাভ করুন। এখনই নিবন্ধন করুন!
সম্পূর্ণরূপে পরিশোধিত
21 Oct 25 at 4:20 am
купить диплом колледжа [url=http://rudik-diplom8.ru/]купить диплом колледжа[/url] .
Diplomi_waMt
21 Oct 25 at 4:21 am
купить диплом в феодосии [url=https://www.rudik-diplom10.ru]https://www.rudik-diplom10.ru[/url] .
Diplomi_xbSa
21 Oct 25 at 4:21 am
купить диплом в абакане [url=https://rudik-diplom15.ru]купить диплом в абакане[/url] .
Diplomi_ovPi
21 Oct 25 at 4:22 am
купить диплом занесением в реестр [url=www.frei-diplom6.ru]купить диплом занесением в реестр[/url] .
Diplomi_pjOl
21 Oct 25 at 4:23 am
купить диплом в симферополе [url=http://www.rudik-diplom1.ru]http://www.rudik-diplom1.ru[/url] .
Diplomi_cyer
21 Oct 25 at 4:23 am
Why viewers still use to read news papers when in this technological globe everything is available on web?
megaweb 5
21 Oct 25 at 4:23 am
Pretty section of content. I simply stumbled upon your
website and in accession capital to claim that I get actually
loved account your blog posts. Anyway I’ll be subscribing for your augment and even I success you get admission to consistently fast.
Adam & Eve Remote Toy
21 Oct 25 at 4:23 am
pin up kripto orqali yechish [url=https://pinup5007.ru]https://pinup5007.ru[/url]
pin_up_uz_misr
21 Oct 25 at 4:24 am
легальный диплом купить [url=https://frei-diplom3.ru/]легальный диплом купить[/url] .
Diplomi_bvKt
21 Oct 25 at 4:25 am
диплом внесенный в реестр купить [url=http://www.frei-diplom1.ru]диплом внесенный в реестр купить[/url] .
Diplomi_lzOi
21 Oct 25 at 4:25 am
Купить диплом колледжа в Харьков [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_emea
21 Oct 25 at 4:26 am
Cabinet IQ Austin
8305 Ⴝtate Hwy 71 #110, Austin,
TX 78735, Unitwd Ѕtates
+12542755536
Designerkitchen
Designerkitchen
21 Oct 25 at 4:27 am
диплом кулинарного техникума купить [url=http://frei-diplom10.ru]диплом кулинарного техникума купить[/url] .
Diplomi_obEa
21 Oct 25 at 4:29 am
Первый раз вижу такое с МН. От других селлеров все было норм с растворимостью. Растворяющийся полностью пер чуть посильнее…
Магазин 24/7 – купить закладку MEF GASH SHIHSKI
забьется, такое бывает у них.
ArturoIcedy
21 Oct 25 at 4:29 am
respectable,ラブドール 女性 用and permanent engagemen as a character actor,
ラブドール
21 Oct 25 at 4:29 am
купить диплом в казани [url=rudik-diplom3.ru]купить диплом в казани[/url] .
Diplomi_lwei
21 Oct 25 at 4:30 am
кракен ссылка
кракен vk3
JamesDaync
21 Oct 25 at 4:30 am
The $MTAUR token presale is a steal at current rates. Audited contracts and vesting smart. Minotaur adventures await. minotaurus token
WilliamPargy
21 Oct 25 at 4:32 am
Profitez d’une offre 1xBet : utilisez-le une fois lors de l’inscription et obtenez un bonus de 100% pour l’inscription jusqu’a 130€. Renforcez votre solde facilement en placant des paris avec un multiplicateur de cinq fois. Le code bonus est valide tout au long de l’annee 2026. Pour activer ce code, rechargez votre compte a partir de 1€. Vous pouvez trouver le code promo 1xbet sur ce lien — Code Promo 1xbet Burundi. Le code promo 1xBet aujourd’hui est disponible pour les joueurs du Cameroun, du Senegal et de la Cote d’Ivoire. Avec le 1xBet code promo bonus, obtenez jusqu’a 130€ de bonus promotionnel du code 1xBet. Ne manquez pas le dernier code promo 1xBet 2026 pour les paris sportifs et les jeux de casino.
Marvinspaft
21 Oct 25 at 4:32 am
Hi there! This article could not be written any better!
Reading through this article reminds me of my previous roommate!
He constantly kept talking about this. I will forward this post to
him. Fairly certain he’s going to have a great read. I appreciate you for sharing!
تأجير الإضاءة الرياض
21 Oct 25 at 4:32 am
купить диплом о высшем образовании проведенный [url=https://www.frei-diplom6.ru]купить диплом о высшем образовании проведенный[/url] .
Diplomi_hnOl
21 Oct 25 at 4:32 am
купить диплом в новоалтайске [url=https://rudik-diplom4.ru]купить диплом в новоалтайске[/url] .
Diplomi_hlOr
21 Oct 25 at 4:32 am
and discerning the carcase of a man,せっくす どー るfrom she thought,
ラブドール
21 Oct 25 at 4:34 am
pin up aviator qanday o‘ynash [url=https://pinup5008.ru]pin up aviator qanday o‘ynash[/url]
pin_up_uz_unSt
21 Oct 25 at 4:34 am