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!
https://git.project-hobbit.eu/zjyohihu
JuliusGlush
21 Aug 25 at 12:26 pm
You actually make it appear really easy together with your presentation but I in finding this
topic to be actually one thing which I think I’d by no means understand.
It seems too complex and very large for me. I am looking
ahead on your next post, I will attempt to get the cling of it! https://suksesvol.org/read-blog/30687_chat-ruletka-18.html
chat ruletka 18+
21 Aug 25 at 12:28 pm
Thanks for your personal marvelous posting! I genuinely enjoyed reading it, you are a great author.
I will make certain to bookmark your blog and will eventually come back
someday. I want to encourage you to definitely continue your great writing, have a
nice weekend!
女性アダルト
21 Aug 25 at 12:31 pm
психолог онлайн помощь в отношениях
Charliesoall
21 Aug 25 at 12:33 pm
https://pxlmo.com/latricejanuary82
CraigCef
21 Aug 25 at 12:37 pm
блэкспрут онион
RichardPep
21 Aug 25 at 12:37 pm
http://pravo-med.ru/articles/18547/
DennisseK
21 Aug 25 at 12:40 pm
прогнозы на спорт бесплатно от профессионалов на сегодня [url=http://prognozy-na-sport-7.ru]http://prognozy-na-sport-7.ru[/url] .
prognozi na sport_elMi
21 Aug 25 at 12:40 pm
купить аттестат средней школы 11 классов искитим [url=https://arus-diplom23.ru/]купить аттестат средней школы 11 классов искитим[/url] .
Diplomi_bcol
21 Aug 25 at 12:45 pm
ктпн комплектные трансформаторные подстанции [url=https://www.transformatornye-podstancii-kupit.ru]https://www.transformatornye-podstancii-kupit.ru[/url] .
transformatornie podstancii kypit_juoi
21 Aug 25 at 12:45 pm
I am curious to find out what blog system you’re using?
I’m having some small security problems with my latest blog and I’d like to find
something more secure. Do you have any recommendations?
마스킹테이프제작
21 Aug 25 at 12:49 pm
прогнозы на ставки на спорт на сегодня [url=http://prognozy-na-sport-7.ru]http://prognozy-na-sport-7.ru[/url] .
prognozi na sport_ixMi
21 Aug 25 at 12:49 pm
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Все материалы собраны здесь – https://linoprost.abopharma.info/2016/02/12/markup-text-alignment
RodneyCarse
21 Aug 25 at 12:54 pm
Thank you for the auspicious writeup. It in fact was a amusement account it.
Look advanced to more added agreeable from you! By the way, how can we communicate?
비아그라 복용방법
21 Aug 25 at 12:55 pm
трансформаторные подстанции 2ктп [url=http://transformatornye-podstancii-kupit.ru]http://transformatornye-podstancii-kupit.ru[/url] .
transformatornie podstancii kypit_anoi
21 Aug 25 at 12:56 pm
https://pixelfed.tokyo/maumau_termenator
CraigCef
21 Aug 25 at 12:58 pm
купить аттестаты за 11 классов в москве цена [url=http://arus-diplom9.ru/]купить аттестаты за 11 классов в москве цена[/url] .
Diplomi_dgEi
21 Aug 25 at 12:58 pm
купить диплом стоимость [url=www.educ-ua5.ru/]купить диплом стоимость[/url] .
Diplomi_jaKl
21 Aug 25 at 1:00 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.
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–37–at.ru]kra31[/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-37—cc.ru]kra33 сс[/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
https://kra–38–at.ru
Frankplary
21 Aug 25 at 1:03 pm
I like looking through a post that will make men and women think.
Also, thank you for allowing for me to comment!
bk8
21 Aug 25 at 1:04 pm
трансформаторная будка цена [url=http://transformatornye-podstancii-kupit.ru]http://transformatornye-podstancii-kupit.ru[/url] .
transformatornie podstancii kypit_aroi
21 Aug 25 at 1:07 pm
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Провести детальное исследование – https://grandeatomy.com.br/novidade-em-produtos
RodneyCarse
21 Aug 25 at 1:09 pm
https://pxlmo.com/pluthzakisdt
Kevinvam
21 Aug 25 at 1:11 pm
Всех приветствую! Хотите узнать больше о продвижении? Подробная информация на тему: https://emamonoseis.gr/asfaltopano-vs-polyourethani/
WilliamLig
21 Aug 25 at 1:14 pm
Многие выбирают 20 Super Blazing Hot играть в 1вин за удобный интерфейс и бонусные акции.
WilliamNex
21 Aug 25 at 1:15 pm
Удобный интерфейс и бонусы доступны в Казино 1win слот 15 Dragon Coins.
Alfonzohut
21 Aug 25 at 1:17 pm
трансформаторная подстанция купить [url=https://transformatornye-podstancii-kupit.ru]https://transformatornye-podstancii-kupit.ru[/url] .
transformatornie podstancii kypit_eioi
21 Aug 25 at 1:18 pm
heterocyclic compounds
Normannus
21 Aug 25 at 1:18 pm
Vavada официальный сайт
Вавада казино официальный сайт
21 Aug 25 at 1:18 pm
Вот, что говорят эксперты по этому поводу:
Между прочим, если вас интересует raregreen.ru, загляните сюда.
Вот, можете почитать:
[url=https://raregreen.ru]https://raregreen.ru[/url]
Надеюсь, смог помочь.
rusPoito
21 Aug 25 at 1:19 pm
https://www.montessorijobsuk.co.uk/author/adahaadacoby/
CraigCef
21 Aug 25 at 1:20 pm
комплектная трансформаторная подстанция цена [url=www.transformatornye-podstancii-kupit.ru/]www.transformatornye-podstancii-kupit.ru/[/url] .
transformatornie podstancii kypit_haoi
21 Aug 25 at 1:20 pm
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Расширить кругозор по теме – https://www.genbitcoins.com/?p=144
TerrySnivY
21 Aug 25 at 1:22 pm
за сколько купить аттестат 11 класса [url=www.arus-diplom23.ru]за сколько купить аттестат 11 класса[/url] .
Diplomi_qkol
21 Aug 25 at 1:22 pm
врачебная косметология цена [url=www.kosmetologiya-moskva-1.ru]врачебная косметология цена[/url] .
kosmetologiya v Moskve_uret
21 Aug 25 at 1:24 pm
Expert service perfection, expert knowledge applied. Expert service discovered. Professional appreciation.
Trusted Cleaning
21 Aug 25 at 1:25 pm
купить украинский диплом о высшем образовании [url=https://www.educ-ua5.ru]купить украинский диплом о высшем образовании[/url] .
Diplomi_hbKl
21 Aug 25 at 1:27 pm
VW108 adalah platform situs terbaik nomor 1 di Indonesia yang
menyediakan berbagai macam permainan slot online terpopuler saat ini untuk menghasilkan profit terbesar 2025.
Situs VW108 bekerja sama dengan provider seperti Pragmatic
Play dan PG Soft untuk berkomitmen menyediakan game slot terbaru 2025.
Selain itu, tersedia link VW108 login untuk akses masuk ke situs online lebih mudah tanpa kendala
apapun.
VW108
21 Aug 25 at 1:28 pm
What a data of un-ambiguity and preserveness of valuable knowledge on the topic of unexpected feelings.
24/7 limo near me
LhaneDrync
21 Aug 25 at 1:30 pm
косметология врачи клиника [url=kosmetologiya-novosibirsk-1.ru]косметология врачи клиника[/url] .
kosmetologiya v Novosibirske_whPl
21 Aug 25 at 1:30 pm
В этой статье вы найдете познавательную и занимательную информацию, которая поможет вам лучше понять мир вокруг. Мы собрали интересные данные, которые вдохновляют на размышления и побуждают к действиям. Открывайте новую информацию и получайте удовольствие от чтения!
Доступ к полной версии – https://adc-life.com/archives/155
RickyPrima
21 Aug 25 at 1:31 pm
It’s amazing to go to see this web site and reading the views of all colleagues on the topic
of this article, while I am also eager of getting familiarity.
Petronas Platform
21 Aug 25 at 1:31 pm
It’s really a cool and helpful piece of information. I’m
glad that you just shared this helpful information with us.
Please stay us informed like this. Thanks for sharing.
Zentro Forge Link
21 Aug 25 at 1:31 pm
What we’re covering
• Zelensky in Washington: Ukrainian President Volodymyr Zelensky has arrived in Washington, DC, where he will be joined by key European leaders when he meets with Donald Trump this afternoon. Trump says Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
[url=https://kpa19.at]kra15 at[/url]
• Potential security guarantees: At last week’s summit with Trump, President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
[url=https://kr11-at.com]kra15 cc[/url]
• Change in tactics: Trump is now focused on securing a peace deal without pursuing a ceasefire due to his progress with Putin, Witkoff said. In seeking this deal, Trump has backed away from his threat of new sanctions on Moscow, despite calls to impose more economic pressure.
kra13
https://kra16-at.com
BryanMok
21 Aug 25 at 1:34 pm
оказание косметологических услуг [url=http://www.kosmetologiya-moskva-1.ru]оказание косметологических услуг[/url] .
kosmetologiya v Moskve_inet
21 Aug 25 at 1:34 pm
Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
Перейти к статье – https://www.tassarnasfavorit.se/39664841_2021830671463437_725516046122876928_n
TerrySnivY
21 Aug 25 at 1:35 pm
Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех!
Ознакомьтесь с аналитикой – https://iejem.org/index.php/2023/02/09/issue-1-10
RickyPrima
21 Aug 25 at 1:35 pm
столбовая мачтовая трансформаторная подстанция [url=https://transformatornye-podstancii-kupit.ru/]transformatornye-podstancii-kupit.ru[/url] .
transformatornie podstancii kypit_kyoi
21 Aug 25 at 1:36 pm
консультация косметолога цена [url=www.kosmetologiya-moskva-1.ru]консультация косметолога цена[/url] .
kosmetologiya v Moskve_myet
21 Aug 25 at 1:40 pm
косметология цены [url=www.kosmetologiya-novosibirsk-1.ru/]косметология цены[/url] .
kosmetologiya v Novosibirske_amPl
21 Aug 25 at 1:40 pm