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://karniz-s-elektroprivodom-kupit.ru]http://karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_lfEr
15 Sep 25 at 10:21 pm
Алгоритм одинаково прозрачен в обоих форматах. Сначала — экспресс-диагностика: уровень сознания, сатурация, пульс, давление, температура, оценка неврологического статуса и обезвоживания. Затем врач формирует индивидуальную инфузионную схему: регидратационные растворы, коррекция электролитов, поддержка печени и нервной системы, адресная симптоматическая помощь (сон, тревога, тошнота, головная боль). Темп и объём подбираются по переносимости — без «универсальных коктейлей» и лишних препаратов.
Подробнее – https://vyvod-iz-zapoya-pushkino7.ru/
LeslieSoG
15 Sep 25 at 10:21 pm
Мы предлагаем дипломы любой профессии по приятным тарифам. Покупка диплома, который подтверждает обучение в университете, – это грамотное решение. Заказать диплом ВУЗа: [url=http://gulfstatesliving.com/author/murieldonahoe/]gulfstatesliving.com/author/murieldonahoe[/url]
Mazrbbm
15 Sep 25 at 10:22 pm
рулонные шторы с направляющими на пластиковые окна [url=https://www.elektricheskie-rulonnye-shtory15.ru]https://www.elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_xuEi
15 Sep 25 at 10:22 pm
рулонные шторы автоматические [url=http://avtomaticheskie-rulonnye-shtory5.ru]http://avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_tosr
15 Sep 25 at 10:23 pm
электрокарниз недорого [url=www.karniz-s-elektroprivodom-kupit.ru]www.karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_sqEr
15 Sep 25 at 10:23 pm
I really like your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you?
Plz reply as I’m looking to design my own blog and would
like to know where u got this from. cheers
new online casinos
15 Sep 25 at 10:23 pm
Have you ever thought about creating an ebook or guest authoring on other blogs?
I have a blog centered on the same information you discuss and would
really like to have you share some stories/information. I know my audience would
value your work. If you are even remotely interested, feel free to shoot me an e mail.
canada pharmacies
15 Sep 25 at 10:24 pm
пластиковые окна рулонные шторы с электроприводом [url=www.elektricheskie-rulonnye-shtory15.ru]www.elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_loEi
15 Sep 25 at 10:26 pm
электрокарнизы цена [url=http://www.karnizy-s-elektroprivodom-cena.ru]электрокарнизы цена[/url] .
karnizi s elektroprivodom cena_mbkr
15 Sep 25 at 10:26 pm
шторы в оконный проем [url=http://avtomaticheskie-rulonnye-shtory5.ru]http://avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_dksr
15 Sep 25 at 10:27 pm
купить рулонные шторы в москве [url=https://elektricheskie-rulonnye-shtory15.ru/]https://elektricheskie-rulonnye-shtory15.ru/[/url] .
elektricheskie rylonnie shtori_viEi
15 Sep 25 at 10:28 pm
купить аттестаты за 11 класс пермь [url=www.arus-diplom25.ru/]купить аттестаты за 11 класс пермь[/url] .
Diplomi_ueot
15 Sep 25 at 10:28 pm
заказать рулонные шторы цена [url=https://avtomaticheskie-rulonnye-shtory5.ru/]заказать рулонные шторы цена[/url] .
avtomaticheskie rylonnie shtori_hfsr
15 Sep 25 at 10:29 pm
Thanks for your marvelous posting! I really enjoyed reading it,
you may be a great author.I will always bookmark
your blog and will come back very soon. I want to encourage you to continue
your great work, have a nice evening!
jelas777
15 Sep 25 at 10:29 pm
электрокарнизы для штор цена [url=https://karnizy-s-elektroprivodom-cena.ru/]электрокарнизы для штор цена[/url] .
karnizi s elektroprivodom cena_gpkr
15 Sep 25 at 10:30 pm
Thanks very interesting blog!
Belqorix
15 Sep 25 at 10:31 pm
карнизы для штор с электроприводом [url=http://karniz-s-elektroprivodom-kupit.ru/]http://karniz-s-elektroprivodom-kupit.ru/[/url] .
karniz s elektroprivodom kypit_qbEr
15 Sep 25 at 10:32 pm
Мега ссылка Мега даркнет Мега сайт Мега онион Мега ссылка Mega даркнет Mega сайт Mega онион Mega ссылка Mega darknet Mega onion
RichardPep
15 Sep 25 at 10:32 pm
Mega darknet Мега даркнет Мега сайт Мега онион Мега ссылка Mega даркнет Mega сайт Mega онион Mega ссылка Mega darknet Mega onion
RichardPep
15 Sep 25 at 10:34 pm
карниз для штор с электроприводом [url=karnizy-s-elektroprivodom-cena.ru]карниз для штор с электроприводом[/url] .
karnizi s elektroprivodom cena_ackr
15 Sep 25 at 10:35 pm
рольшторы заказать [url=http://www.elektricheskie-rulonnye-shtory15.ru]http://www.elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_nbEi
15 Sep 25 at 10:37 pm
установить рулонные шторы цена [url=http://avtomaticheskie-rulonnye-shtory5.ru]http://avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_lqsr
15 Sep 25 at 10:39 pm
https://logistikstroy24.ru/ru-ru/
DanielSoOni
15 Sep 25 at 10:41 pm
карнизы с электроприводом [url=http://www.karniz-s-elektroprivodom-kupit.ru]http://www.karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_isEr
15 Sep 25 at 10:41 pm
карниз с электроприводом [url=https://www.karniz-s-elektroprivodom-kupit.ru]https://www.karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_pdEr
15 Sep 25 at 10:45 pm
карниз электро [url=https://karnizy-s-elektroprivodom-cena.ru]https://karnizy-s-elektroprivodom-cena.ru[/url] .
karnizi s elektroprivodom cena_vfkr
15 Sep 25 at 10:46 pm
рулонная штора автоматическая [url=www.elektricheskie-rulonnye-shtory15.ru/]www.elektricheskie-rulonnye-shtory15.ru/[/url] .
elektricheskie rylonnie shtori_voEi
15 Sep 25 at 10:47 pm
Прогнозы экономики Финансы – это обширная область, охватывающая управление денежными средствами, инвестициями и другими активами. Она включает в себя планирование, организацию, контроль и анализ финансовых ресурсов для достижения экономических целей. От личных бюджетов до глобальных рынков, финансы играют ключевую роль в экономическом благополучии individuals, organizations and nations. Управление рисками, финансовое планирование, инвестиционные стратегии и понимание финансовых рынков – все это важные аспекты успешного финансового управления.
JamesHophy
15 Sep 25 at 10:48 pm
электро жалюзи на окна [url=https://avtomaticheskie-rulonnye-shtory5.ru/]https://avtomaticheskie-rulonnye-shtory5.ru/[/url] .
avtomaticheskie rylonnie shtori_casr
15 Sep 25 at 10:49 pm
cost of cheap nootropil online
get generic nootropil tablets
15 Sep 25 at 10:49 pm
экстренный вывод из запоя
vivod-iz-zapoya-smolensk016.ru
лечение запоя
izzapoyasmolenskNeT
15 Sep 25 at 10:51 pm
рулонные шторы с электроприводом купить в москве [url=https://elektricheskie-rulonnye-shtory15.ru/]elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_otEi
15 Sep 25 at 10:51 pm
карниз для штор с электроприводом [url=karniz-s-elektroprivodom-kupit.ru]karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_saEr
15 Sep 25 at 10:51 pm
Мега сайт Мега даркнет Мега сайт Мега онион Мега ссылка Mega даркнет Mega сайт Mega онион Mega ссылка Mega darknet Mega onion
RichardPep
15 Sep 25 at 10:51 pm
It’s no secret how President Donald Trump feels about sports teams turning away from Native American mascots. He’s repeatedly called for the return of the Washington Redskins and Cleveland Indians, claiming their recent rebrands were part of a “woke” agenda designed to erase history.
[url=https://kra-38cc.org]kra39 at [/url]
But one surprising team has really gotten the president’s attention: the Massapequa Chiefs.
The Long Island school district has refused to change its logo and name under a mandate from New York state banning schools from using team mascots appropriating Indigenous culture. Schools were given two years to rebrand, but Massapequa is the lone holdout, having missed the June 30 deadline to debut a new logo.
[url=https://kra-40cc.net]kra40[/url]
The district lost an initial lawsuit it filed against the state but now has the federal government on its side. In May, Trump’s Department of Education intervened on the district’s behalf, claiming the state’s mascot ban is itself discriminatory.
Massapequa’s Chiefs logo — an American Indian wearing a yellow feathered headdress — is expected to still be prominently displayed when the fall sports season kicks off soon, putting the quiet Long Island hamlet at the center of a political firestorm.
[url=https://kra—40at.ru]kra39 сс[/url]
The district is now a key “battleground,” said Oliver Roberts, a Massapequa alum and the lawyer representing the school board in its fresh lawsuit against New York claiming that the ban is unconstitutional and discriminatory.
The Trump administration claims New York’s mascot ban violates Title VI of the Civil Rights Act of 1964, which prohibits recipients of federal funds from engaging in discriminatory behavior based on race, color or national origin — teeing up a potentially precedent-setting fight.
The intervention on behalf of Massapequa follows a pattern for a White House that has aggressively applied civil rights protections to police “reverse discrimination” and coerced schools and universities into policy concessions by withholding federal funds.
“Our goal is to assist nationally,” Roberts said. “It’s us putting forward our time and effort to try and assist with this national movement and push back against the woke bureaucrats trying to cancel our country’s history and tradition.”
kra40 at
kra38 cc
ScottZib
15 Sep 25 at 10:52 pm
карниз с приводом [url=karnizy-s-elektroprivodom-cena.ru]karnizy-s-elektroprivodom-cena.ru[/url] .
karnizi s elektroprivodom cena_vbkr
15 Sep 25 at 10:53 pm
шторы на окна купить [url=http://avtomaticheskie-rulonnye-shtory5.ru/]http://avtomaticheskie-rulonnye-shtory5.ru/[/url] .
avtomaticheskie rylonnie shtori_issr
15 Sep 25 at 10:53 pm
https://brookspqxq424.trexgame.net/los-errores-mas-comunes-antes-de-un-examen-antidoping
Gestionar un test antidoping puede ser un desafio. Por eso, se desarrollo un suplemento innovador creada con altos estandares.
Su composicion unica combina vitaminas, lo que sobrecarga tu organismo y neutraliza temporalmente los trazas de THC. El resultado: una orina con parametros normales, lista para ser presentada.
Lo mas interesante es su ventana de efectividad de 4 a 5 horas. A diferencia de metodos caseros, no promete milagros, sino una estrategia de emergencia que te respalda en situaciones criticas.
Miles de estudiantes ya han comprobado su seguridad. Testimonios reales mencionan envios en menos de 24 horas.
Si necesitas asegurar tu resultado, esta solucion te ofrece seguridad.
JuniorShido
15 Sep 25 at 10:54 pm
повесить рулонные шторы цена за работу [url=www.elektricheskie-rulonnye-shtory15.ru/]www.elektricheskie-rulonnye-shtory15.ru/[/url] .
elektricheskie rylonnie shtori_jgEi
15 Sep 25 at 10:56 pm
order clomid for sale
cost of clomid for sale
15 Sep 25 at 10:57 pm
электрические гардины [url=https://karnizy-s-elektroprivodom-cena.ru/]электрические гардины[/url] .
karnizi s elektroprivodom cena_ynkr
15 Sep 25 at 10:57 pm
согласование проекта перепланировки квартиры [url=https://fanfiction.borda.ru/?1-0-0-00030334-000-0-0]согласование проекта перепланировки квартиры [/url] .
soglasovanie pereplanirovki kvartiri moskva _gzka
15 Sep 25 at 10:57 pm
рулонные шторы на окна на заказ [url=http://avtomaticheskie-rulonnye-shtory5.ru]http://avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_vhsr
15 Sep 25 at 10:58 pm
автоматические карнизы для штор [url=https://karniz-s-elektroprivodom-kupit.ru]https://karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_iaEr
15 Sep 25 at 10:59 pm
Каждый день запоя увеличивает риск для жизни. Не рискуйте — специалисты в Краснодаре приедут на дом и окажут экстренную помощь. Без боли, стресса и ожидания.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-krasnodar11.ru/]нарколог на дом цена в краснодаре[/url]
HaroldGaw
15 Sep 25 at 11:02 pm
электрические гардины [url=http://www.karnizy-s-elektroprivodom-cena.ru]электрические гардины[/url] .
karnizi s elektroprivodom cena_yzkr
15 Sep 25 at 11:02 pm
квартира на сутки Лида https://grupascout.pl/2025/09/10/kvartira-premium-klassa-na-sutki-chasy-v-lide/
https://grupascout.pl/2025/09/10/kvartira-premium-klassa-na-sutki-chasy-v-lide/
15 Sep 25 at 11:02 pm
ritzo 20 freispiele Spinbara Casino
RonaldDuh
15 Sep 25 at 11:03 pm
Мы можем предложить дипломы любой профессии по доступным ценам. Приобретение диплома, который подтверждает обучение в ВУЗе, – это грамотное решение. Приобрести диплом университета: [url=http://u90517ol.beget.tech/2025/08/08/kupit-diplom-vuza-s-podtverzhdeniem.html/]u90517ol.beget.tech/2025/08/08/kupit-diplom-vuza-s-podtverzhdeniem.html[/url]
Mazrnsm
15 Sep 25 at 11:03 pm