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!
How to transition to a low-waste lifestyle without overwhelm https://ecofriendlystore.ru/
EcoFriendNeuct
28 Oct 25 at 7:27 am
kraken vk5
kraken vk6
Henryamerb
28 Oct 25 at 7:27 am
купить диплом в новотроицке [url=http://rudik-diplom4.ru]купить диплом в новотроицке[/url] .
Diplomi_giOr
28 Oct 25 at 7:27 am
купить диплом пту в реестре [url=http://frei-diplom2.ru]купить диплом пту в реестре[/url] .
Diplomi_kiEa
28 Oct 25 at 7:27 am
купить диплом в кургане [url=https://rudik-diplom9.ru]купить диплом в кургане[/url] .
Diplomi_qlei
28 Oct 25 at 7:28 am
Букмекерская контора Melbet является одним из столпов международной беттинговой индустрии. За счет масштабной маркетинговой компании, высоких коэффициентов и оперативной технической поддержки БК Мелбет удалось привлечь и удержать большое количество игроков. На сегодняшний день, букмекер предлагает получить один из самых высоких бонусов на рынке – 50 000 рублей. Размер бонуса в Melbet составляет 100% от суммы первого пополнения, но не менее 100 рублей и не более 50 000. К примеру, если пополнить баланс на сумму 4000, то справа от основного счета появится бонусный. Как видим, использовать промокод мелбет 2026 имеет смысл, особенно тем бетторам и бонусхантерам, которые привыкли заключать пари по-крупному. С учетом того, что он бесплатный – воспользоваться им может абсолютно любой игрок.
Georgeduh
28 Oct 25 at 7:28 am
наркологические клиники москва [url=https://narkologicheskaya-klinika-28.ru/]наркологические клиники москва[/url] .
narkologicheskaya klinika_juMa
28 Oct 25 at 7:29 am
Eh eh, composed pom ⲣi pi, math proves рart in thе tⲟⲣ subjects in Junior College, establishing groundwork tօ A-Level calculus.
In aԁdition beyond school resources, concentrate ⲟn maths
іn orԁer tⲟ stop typical mistakes ѕuch as sloppy mistakes in tests.
Mums ɑnd Dads, competitive mode οn lah,
robust primary maths leads t᧐ bettеr STEM comprehension аnd construction dreams.
Anglo-Chinese School (Independent) Junior College ρrovides a faith-inspired education tһat harmonizes intellectual pursuits ѡith ethical worths, empowering students tⲟ end up being
compassionate worldwide people. Ιts International Baccalaureate program motivates crucial thinking ɑnd query, supported by first-rate resources ɑnd devoted teachers.
Students excel іn a wide range ߋf co-curricularactivities,
fгom robotics to music, constructing versatility аnd creativity.
The school’ѕ focus ߋn service knowing instills a sense of obligation аnd neighborhood engagement fгom an еarly stage.
Graduates ɑге well-prepared foг prestigious universities, continuing
а tradition of excellence аnd stability.
Nanyang Junior College masters promoting bilingual proficiency аnd cultural
quality, skillfully weaving tоgether abundant Chinese heritage wіth modern international
education tⲟ form positive,culturally agile residents ᴡho
агe poised tο lead іn multicultural contexts.
Tһe college’s sophisticated centers, consisting оf specialized STEM laboratories, carrying оut arts theaters,
annd language immersion centers, support robust programs
іn science, technology, engineering, mathematics,
arts, аnd humanities tһаt motivate development, importaznt thinking, and artistic expression. Ιn a vibrant ɑnd
inclusive neighborhood, students engage іn management opportunities ѕuch ɑs
trainee governance functions аnd global exchange programs with partner organizations
abroad, ѡhich widen tһeir ⲣoint of views and build impοrtant
international competencies. Ꭲhe emphasis ⲟn core worths like stability and
strength іѕ incorporated into daily life thгough mentorship schemes, neighborhood service initiatives,
аnd wellness programs that cultivate psychological intelligence аnd individual development.
Graduates ᧐f Nanyang Junior College routinely master admissions t᧐ toρ-tier
universities, promoting ɑ proud legacy of impressive accomplishments,
cultural gratitude, аnd a deep-seated enthusiasm fօr continuous self-improvement.
Don’t mess аround lah, pair a excellent Junior College ᴡith
math proficiency fοr guarantee superior А Levels гesults
ⲣlus seamless shifts.
Parents, dread the difference hor, math foundation proves essential ɑt Junior
College іn understanding infoгmation, vital in current tech-driven ѕystem.
Оh mɑn, reɡardless if institution remains atas, math acts liҝе the
critical discipline in building assurance гegarding calculations.
Alas, primary maths teaches real-ԝorld applications ѕuch
as financial planning, sо ensure yoᥙr youngster masters tһis гight starting early.
Avoid play play lah, pair а reputable Junior College ѡith
maths proficiency tо assure superior А Levels scores and effortless shifts.
Folks, worry ɑbout the difference hor,math
groundwork proves essential іn Junior College for understanding data, vital ԝithin todɑy’s online
economy.
Scoring ᴡell in A-levels oⲣens doors to top universities in Singapore ⅼike NUS and NTU, setting yⲟu up foг a bright future lah.
Wow, mathematics serves ɑѕ tһe groundwork stone fⲟr primary schooling, helping youngsters with dimensional analysis for design routes.
Alas, lacking solid mathematics ɑt Junior College,
regardless leading establishment kids mіght falter in secolndary calculations,
tһerefore build thi immedіately leh.
mү web blog … best maths tuition for lower secondary n in singapore
best maths tuition for lower secondary n in singapore
28 Oct 25 at 7:29 am
ремонт подвала в частном доме [url=www.gidroizolyaciya-podvala-cena.ru/]www.gidroizolyaciya-podvala-cena.ru/[/url] .
gidroizolyaciya podvala cena_hsKt
28 Oct 25 at 7:30 am
анонимный наркологический центр [url=www.narkologicheskaya-klinika-27.ru/]анонимный наркологический центр[/url] .
narkologicheskaya klinika_jspl
28 Oct 25 at 7:30 am
https://t.me/s/bs_1Win/447
Georgerah
28 Oct 25 at 7:31 am
сырость в подвале многоквартирного дома [url=https://gidroizolyaciya-cena-7.ru]https://gidroizolyaciya-cena-7.ru[/url] .
gidroizolyaciya cena_ndSi
28 Oct 25 at 7:32 am
кракен ios
kraken tor
Henryamerb
28 Oct 25 at 7:32 am
купить диплом электромонтера [url=http://rudik-diplom8.ru/]купить диплом электромонтера[/url] .
Diplomi_pkMt
28 Oct 25 at 7:33 am
интернет продвижение москва [url=https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru]интернет продвижение москва[/url] .
optimizaciya i seo prodvijenie saitov moskva_bbPi
28 Oct 25 at 7:34 am
https://t.me/s/bs_1Win/1147
Georgerah
28 Oct 25 at 7:34 am
купить диплом техникума в астрахани [url=http://www.frei-diplom8.ru]купить диплом техникума в астрахани[/url] .
Diplomi_cdsr
28 Oct 25 at 7:34 am
купить диплом в смоленске [url=https://rudik-diplom9.ru/]https://rudik-diplom9.ru/[/url] .
Diplomi_dxei
28 Oct 25 at 7:35 am
гидроизоляция подвала изнутри цена м2 [url=http://gidroizolyaciya-cena-7.ru/]http://gidroizolyaciya-cena-7.ru/[/url] .
gidroizolyaciya cena_beSi
28 Oct 25 at 7:36 am
ремонт подвала в частном доме [url=https://gidroizolyaciya-cena-8.ru/]gidroizolyaciya-cena-8.ru[/url] .
gidroizolyaciya cena_vvKn
28 Oct 25 at 7:36 am
Просьба подкорректировать самим бредовые сообщения. https://nasha-shapka.ru ну если для кавото это естественно, для меня нет…кавото и палынь прет..
JasonBoomi
28 Oct 25 at 7:37 am
купить гриндер для травы
купить гриндер для травы
28 Oct 25 at 7:39 am
kraken android
кракен обмен
Henryamerb
28 Oct 25 at 7:39 am
устранение протечек в подвале [url=www.gidroizolyaciya-podvala-cena.ru]www.gidroizolyaciya-podvala-cena.ru[/url] .
gidroizolyaciya podvala cena_cpKt
28 Oct 25 at 7:39 am
частные наркологические клиники в москве [url=https://narkologicheskaya-klinika-28.ru]частные наркологические клиники в москве[/url] .
narkologicheskaya klinika_gjMa
28 Oct 25 at 7:39 am
I blog quite often and I really appreciate your content. The article has
really peaked my interest. I will book mark your website and keep checking for new information about once per week.
I subscribed to your RSS feed too.
Azorilix
28 Oct 25 at 7:39 am
где купить диплом техникума всем [url=http://www.frei-diplom9.ru]где купить диплом техникума всем[/url] .
Diplomi_hmea
28 Oct 25 at 7:40 am
купить диплом во владикавказе [url=http://rudik-diplom6.ru]http://rudik-diplom6.ru[/url] .
Diplomi_scKr
28 Oct 25 at 7:41 am
Получить диплом университета поспособствуем. Купить диплом магистра в Улан-Удэ – [url=http://diplomybox.com/kupit-diplom-magistra-v-ulan-ude/]diplomybox.com/kupit-diplom-magistra-v-ulan-ude[/url]
Cazrzdj
28 Oct 25 at 7:41 am
Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
Не упусти важное! – https://www.helferei-weiler.ch/hello-world-2
Santosvet
28 Oct 25 at 7:41 am
Your style is very unique in comparison to other folks I have read stuff from.
Thanks for posting when you have the opportunity, Guess I will just bookmark this web site.
flumberico official
28 Oct 25 at 7:42 am
частные наркологические клиники в москве [url=http://narkologicheskaya-klinika-27.ru/]частные наркологические клиники в москве[/url] .
narkologicheskaya klinika_nypl
28 Oct 25 at 7:42 am
Unquestionably imagine that that you stated. Your favourite reason seemed to be at the net
the easiest thing to remember of. I say to you, I definitely get annoyed at the same time as folks think about issues that
they just do not realize about. You managed to hit the nail upon the top and defined out the whole
thing with no need side-effects , other people could take
a signal. Will likely be back to get more.
Thank you
mm88
28 Oct 25 at 7:42 am
купить диплом высшего образования с занесением в реестр [url=www.frei-diplom2.ru/]купить диплом высшего образования с занесением в реестр[/url] .
Diplomi_viEa
28 Oct 25 at 7:43 am
наркологические услуги в москве [url=https://www.narkologicheskaya-klinika-25.ru]https://www.narkologicheskaya-klinika-25.ru[/url] .
narkologicheskaya klinika_qiPl
28 Oct 25 at 7:43 am
гидроизоляция подвала цена за м2 [url=http://www.gidroizolyaciya-cena-7.ru]гидроизоляция подвала цена за м2[/url] .
gidroizolyaciya cena_npSi
28 Oct 25 at 7:45 am
психолог нарколог в москве [url=https://narkologicheskaya-klinika-28.ru/]психолог нарколог в москве[/url] .
narkologicheskaya klinika_zgMa
28 Oct 25 at 7:45 am
Карнизы с электроприводом становятся все более популярными в современных интерьере. Такие конструкции предлагают комфорт и эстетику для любого помещения. Используя электропривод, можно легко управлять шторами или занавесками при помощи дистанционного управления .
Откройте для себя элегантность и удобство [url=https://karnizy-s-elektroprivodom-dlya-shtor.ru/]карнизы с электроприводом для штор прокарниз[/url], которые сделают управление шторами простым и современным.
удобство в использовании . Данные конструкции универсальны и подойдут для. Также стоит отметить, что эти карнизы комфортную обстановку в доме или офисе.
Установка таких систем возможна в любом помещении . Установка не требует значительных усилий, и с этим может справиться практически каждый. Кроме того, такие карнизы возможно интегрировать в .
Несмотря на множество преимуществ, существуют и несколько ограничений. стоимость таких систем может быть высокой . В любом случае,, ведь значительно облегчают повседневные задачи .
карнизы с электроприводом raex прокарниз
28 Oct 25 at 7:46 am
наркологическая услуга москва [url=http://narkologicheskaya-klinika-25.ru/]http://narkologicheskaya-klinika-25.ru/[/url] .
narkologicheskaya klinika_dhPl
28 Oct 25 at 7:46 am
https://t.me/bs_1Win/465
Georgerah
28 Oct 25 at 7:46 am
https://www.mirkeramiki.com.ua/
ChrisCeshy
28 Oct 25 at 7:47 am
kraken vk3
кракен актуальная ссылка
Henryamerb
28 Oct 25 at 7:47 am
диплом об окончании техникума купить в спб [url=http://frei-diplom9.ru/]диплом об окончании техникума купить в спб[/url] .
Diplomi_zjea
28 Oct 25 at 7:47 am
кракен vk2
кракен обмен
Henryamerb
28 Oct 25 at 7:48 am
https://t.me/bs_1Win/446
Georgerah
28 Oct 25 at 7:48 am
купить диплом занесением реестр киев [url=http://frei-diplom2.ru/]http://frei-diplom2.ru/[/url] .
Diplomi_qeEa
28 Oct 25 at 7:49 am
гидроизоляция подвала [url=https://gidroizolyaciya-cena-7.ru/]гидроизоляция подвала[/url] .
gidroizolyaciya cena_tdSi
28 Oct 25 at 7:49 am
Wow, this paragraph is pleasant, my younger sister is analyzing these
things, therefore I am going to tell her.
Luvox Bit
28 Oct 25 at 7:50 am
сырость в подвале многоквартирного дома [url=https://gidroizolyaciya-podvala-cena.ru/]gidroizolyaciya-podvala-cena.ru[/url] .
gidroizolyaciya podvala cena_ofKt
28 Oct 25 at 7:50 am
купить диплом с занесением реестра [url=https://frei-diplom2.ru]купить диплом с занесением реестра[/url] .
Diplomi_iwEa
28 Oct 25 at 7:52 am