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!
This paragraph is genuinely a nice one it helps new net viewers, who
are wishing for blogging.
https://google-chrome.ru.com/
20 Oct 25 at 7:06 am
Hey! This post couldn’t be written any better! Reading through this post
reminds me of my previous room mate! He always kept chatting about this.
I will forward this write-up to him. Fairly certain he will have a good read.
Thanks for sharing!
pool installation
20 Oct 25 at 7:08 am
где купить диплом техникума форум [url=https://frei-diplom11.ru/]где купить диплом техникума форум[/url] .
Diplomi_zusa
20 Oct 25 at 7:08 am
доставка алкоголя москва 24/7 [url=http://alcoygoloc.ru]доставка алкоголя москва 24/7[/url] .
dostavka alkogolya_ecki
20 Oct 25 at 7:08 am
прогнозы на спорт точные [url=www.luchshie-prognozy-na-khokkej8.ru/]www.luchshie-prognozy-na-khokkej8.ru/[/url] .
lychshie prognozi na hokkei_bxEi
20 Oct 25 at 7:09 am
levaquin precautions
levaquin 500 mg tablet dosage
20 Oct 25 at 7:10 am
1вин узбекистан [url=www.1win5509.ru]1вин узбекистан[/url]
1win_uz_skKt
20 Oct 25 at 7:10 am
купить диплом в саранске [url=http://rudik-diplom3.ru/]купить диплом в саранске[/url] .
Diplomi_pqei
20 Oct 25 at 7:11 am
купить диплом о среднем образовании в реестр [url=frei-diplom3.ru]купить диплом о среднем образовании в реестр[/url] .
Diplomi_rtKt
20 Oct 25 at 7:11 am
прогнозы на кхл сегодня от профессионалов [url=http://www.prognozy-ot-professionalov4.ru]http://www.prognozy-ot-professionalov4.ru[/url] .
prognozi ot professionalov_yuOr
20 Oct 25 at 7:11 am
1win ro‘yxatdan o‘tish orqali bonus [url=www.1win5509.ru]www.1win5509.ru[/url]
1win_uz_ilKt
20 Oct 25 at 7:11 am
купить диплом о высшем образовании с занесением в реестр [url=http://frei-diplom6.ru/]купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_daOl
20 Oct 25 at 7:12 am
https://www.diigo.com/item/note/90bun/paur?k=6d5f8ea5dc446242c44033af512a6fc0
Juliohow
20 Oct 25 at 7:12 am
купить диплом из колледжа [url=https://www.frei-diplom9.ru]https://www.frei-diplom9.ru[/url] .
Diplomi_efea
20 Oct 25 at 7:12 am
купить диплом математика [url=https://www.rudik-diplom7.ru]купить диплом математика[/url] .
Diplomi_tdPl
20 Oct 25 at 7:13 am
прогноз на хоккей в прогнозе [url=https://luchshie-prognozy-na-khokkej8.ru]https://luchshie-prognozy-na-khokkej8.ru[/url] .
lychshie prognozi na hokkei_bmEi
20 Oct 25 at 7:13 am
https://bookmarkmargin.com/story20458892/best-sportsbook-promos
RandyLoank
20 Oct 25 at 7:13 am
кракен маркет
кракен vk3
JamesDaync
20 Oct 25 at 7:13 am
В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
Наши рекомендации — тут – https://www.neosferaconsulting.com/comunicacion-abierta-y-feedback-constante-claves-para-una-cultura-organizacional-solida
TimothySkype
20 Oct 25 at 7:13 am
krypto wettanbieter
Review my blog post wettquoten vergleich (Alysa)
Alysa
20 Oct 25 at 7:14 am
купить диплом в канске [url=www.rudik-diplom15.ru]купить диплом в канске[/url] .
Diplomi_kaPi
20 Oct 25 at 7:14 am
купить свидетельство о браке [url=https://rudik-diplom2.ru/]купить свидетельство о браке[/url] .
Diplomi_hopi
20 Oct 25 at 7:14 am
https://universocentro.com/NUMERO22/ParrandaSanta.aspx
Coreycip
20 Oct 25 at 7:14 am
1вин рабочее зеркало [url=www.1win5510.ru]1вин рабочее зеркало[/url]
1win_uz_uxsi
20 Oct 25 at 7:16 am
диплом техникума купить с проводкой [url=http://www.frei-diplom11.ru]диплом техникума купить с проводкой[/url] .
Diplomi_ptsa
20 Oct 25 at 7:16 am
Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
Детали по клику – https://getraidnow.com/services/crossfire-triumph
PatrickNab
20 Oct 25 at 7:16 am
лечение запоя краснодар
narkolog-krasnodar016.ru
вывод из запоя круглосуточно краснодар
vivodkrasnodarNeT
20 Oct 25 at 7:17 am
1win uz [url=https://www.1win5509.ru]1win uz[/url]
1win_uz_ibKt
20 Oct 25 at 7:19 am
купить бланк диплома [url=rudik-diplom7.ru]купить бланк диплома[/url] .
Diplomi_hgPl
20 Oct 25 at 7:20 am
как купить диплом техникума отзывы [url=http://frei-diplom9.ru]как купить диплом техникума отзывы[/url] .
Diplomi_mhea
20 Oct 25 at 7:21 am
Раменбет — игровая кухня с фирменной подачей, где каждая ставка
— насыщенный бульон эмоций.
Подача — быстро, горячо и честно — попробуйте сами:
Ramen bet вход на сайт — и почувствуйте вкус побед.
Бонусы миксуются, как идеальные топпинги, а выплаты подаются без ожиданий.
Интерфейс — без лишней соли.
Подарки новичкам без «горечи» условий
Турниры как фестивали вкуса
Крипта и фиат — как разные соусы
Выигрыши, которые подаются горячими.
казино раменбет
20 Oct 25 at 7:22 am
Новини Вінниця https://u-misti.vinnica.ua публікує останні події у Вінниці та області. Політика, крімінал, цікаве..
Lancegailm
20 Oct 25 at 7:22 am
диплом купить с занесением в реестр отзывы [url=https://www.frei-diplom2.ru]https://www.frei-diplom2.ru[/url] .
Diplomi_bpEa
20 Oct 25 at 7:24 am
https://issuu.com/candetoxblend
Superar una prueba de orina puede ser complicado. Por eso, existe una solucion cientifica probada en laboratorios.
Su composicion unica combina carbohidratos, lo que prepara tu organismo y enmascara temporalmente los trazas de alcaloides. El resultado: un analisis equilibrado, lista para entregar tranquilidad.
Lo mas interesante es su accion rapida en menos de 2 horas. A diferencia de detox irreales, no promete milagros, sino una estrategia de emergencia que funciona cuando lo necesitas.
Estos fórmulas están diseñados para facilitar a los consumidores a depurar su cuerpo de sustancias no deseadas, especialmente aquellas relacionadas con el uso de cannabis u otras sustancias.
Uno buen detox para examen de fluido debe ofrecer resultados rápidos y efectivos, en particular cuando el tiempo para prepararse es limitado. En el mercado actual, hay muchas variedades, pero no todas garantizan un proceso seguro o rápido.
De qué funciona un producto detox? En términos claros, estos suplementos actúan acelerando la depuración de metabolitos y residuos a través de la orina, reduciendo su presencia hasta quedar por debajo del límite de detección de algunos tests. Algunos funcionan en cuestión de horas y su impacto puede durar entre 4 a 6 horas.
Parece fundamental combinar estos productos con buena hidratación. Beber al menos dos litros de agua diariamente antes y después del ingesta del detox puede mejorar los beneficios. Además, se aconseja evitar alimentos grasos y bebidas procesadas durante el proceso de desintoxicación.
Los mejores productos de limpieza para orina incluyen ingredientes como extractos de hierbas, vitaminas del grupo B y minerales que respaldan el funcionamiento de los sistemas y la función hepática. Entre las marcas más vendidas, se encuentran aquellas que ofrecen certificaciones sanitarias y estudios de resultado.
Para usuarios frecuentes de marihuana, se recomienda usar detoxes con tiempos de acción largas o iniciar una preparación temprana. Mientras más larga sea la abstinencia, mayor será la efectividad del producto. Por eso, combinar la planificación con el uso correcto del producto es clave.
Un error común es suponer que todos los detox actúan igual. Existen diferencias en dosis, sabor, método de toma y duración del efecto. Algunos vienen en envase líquido, otros en cápsulas, y varios combinan ambos.
Además, hay productos que incluyen fases de preparación o preparación previa al día del examen. Estos programas suelen instruir abstinencia, buena alimentación y descanso adecuado.
Por último, es importante recalcar que ninguno detox garantiza 100% de éxito. Siempre hay variables personales como metabolismo, historial de consumo, y tipo de examen. Por ello, es vital seguir ciertas instrucciones del fabricante y no descuidarse.
Miles de postulantes ya han comprobado su seguridad. Testimonios reales mencionan resultados exitosos en pruebas preocupacionales.
Si quieres proteger tu futuro, esta formula te ofrece confianza.
JuniorShido
20 Oct 25 at 7:25 am
cd player alarm clock radio [url=https://www.alarm-radio-clocks.com]https://www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_bnOa
20 Oct 25 at 7:25 am
купить диплом в выборге [url=https://rudik-diplom7.ru/]https://rudik-diplom7.ru/[/url] .
Diplomi_yqPl
20 Oct 25 at 7:26 am
1вин официальный сайт узбекистан [url=http://1win5509.ru]http://1win5509.ru[/url]
1win_uz_uvKt
20 Oct 25 at 7:26 am
новости олимпиады [url=http://sportivnye-novosti-2.ru/]новости олимпиады[/url] .
sportivnie novosti_muma
20 Oct 25 at 7:27 am
купить диплом в владикавказе [url=https://www.rudik-diplom6.ru]https://www.rudik-diplom6.ru[/url] .
Diplomi_vhKr
20 Oct 25 at 7:27 am
1win o‘zbek tilida sayt [url=www.1win5509.ru]1win o‘zbek tilida sayt[/url]
1win_uz_uvKt
20 Oct 25 at 7:28 am
купить легальный диплом техникума [url=https://www.frei-diplom3.ru]купить легальный диплом техникума[/url] .
Diplomi_fnKt
20 Oct 25 at 7:28 am
купить диплом тренера [url=https://rudik-diplom2.ru]купить диплом тренера[/url] .
Diplomi_eppi
20 Oct 25 at 7:29 am
Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
Ознакомиться с теоретической базой – https://www.bdmab.se/1382124_580619668672891_1084536473_n
Geraldequax
20 Oct 25 at 7:30 am
кракен сайт
кракен 2025
JamesDaync
20 Oct 25 at 7:31 am
купить диплом в иваново [url=www.rudik-diplom5.ru/]купить диплом в иваново[/url] .
Diplomi_wxma
20 Oct 25 at 7:32 am
диплом техникум купить [url=http://frei-diplom9.ru]диплом техникум купить[/url] .
Diplomi_bmea
20 Oct 25 at 7:32 am
Дизайнерский ремонт: искусство преображения пространства
Дизайн интерьера играет важную роль в создании комфортной и уютной атмосферы в доме. Сегодня мы поговорим о таком понятии, как дизайнерский ремонт, который позволяет превратить обычное жилье в уникальное пространство, отражающее индивидуальность владельца.
[url=https://designapartment.ru]дизайнерский ремонт виллы под ключ[/url]
Что такое дизайнерский ремонт?
Дизайнерский ремонт — это комплекс работ, направленных на создание оригинального дизайна помещения. Это не просто обновление отделки, а полноценный творческий процесс, включающий разработку концепции, подбор материалов и мебели, а также реализацию проекта.
Ключевые особенности дизайнерского ремонта:
[url=https://designapartment.ru]дизайнерский ремонт виллы[/url]
– Индивидуальный подход к каждому проекту.
– Использование качественных материалов и современных технологий.
– Создание уникального стиля, соответствующего вкусам заказчика.
– Оптимизация пространства для максимального комфорта и функциональности.
Виды дизайнерских ремонтов
[url=https://designapartment.ru]дизайнерский ремонт виллы[/url]
Существует несколько видов дизайнерских ремонтов, каждый из которых имеет свои особенности и преимущества.
#1 Дизайнерский ремонт квартиры
Это наиболее распространенный вид ремонта, подходящий для тех, кто хочет обновить интерьер своей городской квартиры. Специалисты разрабатывают проект, учитывая размеры помещений, пожелания клиента и бюджет. Такой ремонт включает перепланировку, замену коммуникаций, отделочные работы и декорирование.
Пример дизайна: светлая гостиная с панорамными окнами, минималистичный дизайн кухни и спальни в стиле лофт.
#2 Дизайнерский ремонт дома
Такой ремонт предполагает полное преобразование жилого дома, начиная от фундамента и заканчивая крышей. Здесь важно учитывать архитектурные особенности здания, климатические условия региона и предпочтения владельцев. Часто используется экодизайн, натуральные материалы и энергосберегающие технологии.
Пример дизайна: просторный холл с камином, стеклянная веранда с видом на сад, спальня в пастельных тонах.
#3 Дизайнерский ремонт виллы
Ремонт вилл требует особого подхода, поскольку такие объекты часто расположены в живописных местах и имеют большую площадь. Важно сохранить гармонию с окружающей средой, используя природные материалы и цвета. Особое внимание уделяется созданию зон отдыха, бассейнов и садов.
Пример дизайна: роскошная вилла с бассейном, открытая терраса с видами на море, спальная зона в тропическом стиле.
#4 Дизайнерский ремонт коттеджа
Коттедж отличается от обычного дома наличием придомового участка и возможностью организации дополнительных функциональных зон. Ремонт коттеджей включает работу над фасадом, ландшафтом и внутренним пространством. Стили могут варьироваться от классики до хай-тека.
Пример дизайна: двухэтажный коттедж с мансардой, гостиная-столовая в скандинавском стиле, детская комната с игровой зоной.
#5 Дизайнерский ремонт пентхауса
Пентхаус — это элитное жилье, расположенное на верхних этажах зданий с панорамными видами. Для такого типа недвижимости характерны высокие потолки, большие окна и эксклюзивные элементы декора. Проектирование пентхауса требует учета особенностей конструкции здания и пожеланий клиентов относительно приватности и удобства.
Пример дизайна: современный пентхаус с открытой планировкой, кабинет с видом на город, зона отдыха с джакузи.
Заключение
Дизайнерский ремонт — это возможность создать идеальное пространство для жизни и отдыха. Независимо от того, хотите ли вы обновить квартиру, дом, виллу, коттедж или пентхаус, профессиональный подход гарантирует вам комфорт и эстетическое удовольствие на долгие годы.
https://designapartment.ru
дизайнерский ремонт виллы под ключ
Jacobtib
20 Oct 25 at 7:32 am
What’s up mates, how is the whole thing, and what you
wish for to say about this post, in my view its in fact amazing in support of me.
Wzrost Coinmark
20 Oct 25 at 7:34 am
купить диплом занесением реестр киев [url=https://frei-diplom4.ru/]https://frei-diplom4.ru/[/url] .
Diplomi_uiOl
20 Oct 25 at 7:35 am
1вин теннис ставки [url=http://1win5509.ru]http://1win5509.ru[/url]
1win_uz_rgKt
20 Oct 25 at 7:35 am