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://www.iheir13.com/5214.html
EddieKanna
20 Aug 25 at 11:33 am
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Полная информация здесь – https://afriteq.co.za/regional-manager-limited-time-management
MelvinKex
20 Aug 25 at 11:33 am
https://bio.site/egicyfyeu
Felixhic
20 Aug 25 at 11:37 am
Фильмы и сериалы лучший бесплатный онлайн-кинотеатр с русской озвучкой Онлайн-кинотеатр без регистрации и смс: тысячи фильмов и сериалов бесплатно.
kinobay-158
20 Aug 25 at 11:38 am
прогнозы на футбол [url=https://prognozy-na-futbol-6.ru/]прогнозы на футбол[/url] .
prognozi na fytbol_scsn
20 Aug 25 at 11:38 am
прогноз футбол [url=prognozy-na-futbol-5.ru]прогноз футбол[/url] .
prognozi na fytbol_vnoa
20 Aug 25 at 11:41 am
Excellent blog here! Additionally your site a lot up fast!
What host are you the use of? Can I am getting your associate link to your host?
I desire my site loaded up as fast as yours lol
can solar lights charge in the shade
20 Aug 25 at 11:41 am
Услуга капельницы от запоя на дому – это ключевая услуга наркологов‚ позволяющая оперативно и резко поддержать людям‚ переживающим от алкогольной зависимости. Начальная встреча с наркологом в Красноярске включает диагностику зависимости‚ анализ состояния пациента и составление индивидуального плана лечения. Ключевые услуги нарколога на дому включают медикаментозное лечение‚ выведение из запоя‚ психотерапевтическую помощь при алкоголизме и реабилитационные программы. Поддержка родственников также влияет ключевую функцию в реабилитации алкоголиков. Анонимное лечение обеспечивает удобство и защищенность пациента. помощь нарколога Красноярск
narkologiyakrasnoyarskNeT
20 Aug 25 at 11:41 am
прогнозы бесплатные [url=www.prognozy-na-sport-8.ru/]прогнозы бесплатные[/url] .
prognozi na sport_hwmi
20 Aug 25 at 11:48 am
buy viagra pharmacy: SildenaPeak – SildenaPeak
PeterTEEFS
20 Aug 25 at 11:48 am
Hello superb blog! Does running a blog such as this take a
great deal of work? I have very little understanding of coding however
I had been hoping to start my own blog soon. Anyhow, should you have any
ideas or techniques for new blog owners please share.
I know this is off subject nevertheless I just needed to ask.
Kudos!
kok hoki
20 Aug 25 at 11:49 am
В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
Узнать напрямую – https://toniponsoficial.es/xyz-supplement-your-natural-solution-for-joint-health-and-mobility
Rodneytooft
20 Aug 25 at 11:50 am
прогнозы на сегодня футбол [url=https://prognozy-na-futbol-6.ru/]прогнозы на сегодня футбол[/url] .
prognozi na fytbol_bvsn
20 Aug 25 at 11:50 am
Hello are using WordPress for your blog platform?
I’m new to the blog world but I’m trying to get started and create my
own. Do you require any coding expertise to make your own blog?
Any help would be really appreciated!
ضرایب دروس کنکور انسانی برای دانشگاه فرهنگیان ۱۴۰۴
20 Aug 25 at 11:51 am
plinko game online [url=plinko3001.ru]plinko3001.ru[/url]
plinko_kz_bgEr
20 Aug 25 at 11:52 am
прогноз футбол сегодня [url=http://prognozy-na-futbol-5.ru/]http://prognozy-na-futbol-5.ru/[/url] .
prognozi na fytbol_dwoa
20 Aug 25 at 11:52 am
прогнозы от профессионалов на спорт [url=https://prognozy-na-sport-8.ru]https://prognozy-na-sport-8.ru[/url] .
prognozi na sport_xemi
20 Aug 25 at 11:52 am
Эта статья предлагает живое освещение актуальной темы с множеством интересных фактов. Мы рассмотрим ключевые моменты, которые делают данную тему важной и актуальной. Подготовьтесь к насыщенному путешествию по неизвестным аспектам и узнайте больше о значимых событиях.
Нажми и узнай всё – https://duhaimedemissionne.net/index.php/2023/10/08/chef_entoure_mal
Robertjax
20 Aug 25 at 11:54 am
Refresh Renovation Southwest Charlotte
1251 Arrow Pine Ɗr c121,
Charlotte, NC 28273, United Տtates
+19803517882
Renovations custom and build design
Renovations custom and build design
20 Aug 25 at 11:56 am
He has had more cordial, more productive, meetings with US President Donald Trump since that now-notorious encounter on February 28.
[url=https://kraken2trfqodidvlh4a337cpzfrhdlfldhve5nf7njhumwr7instad-onion.com]kraken7jmgt7yhhe2c4iyilthnhcugfylcztsdhh7otrr6jgdw667pqd.onion[/url]
But for Ukrainian President Volodymyr Zelensky, today’s meeting at the White House will surely trigger awkward memories of that very public clash with the US President almost six months ago. Navigating the treacherous waters in which he finds himself today will be no easier.
[url=https://kraken5af44k24fwzohe6fvqfgxfsee4lgydb3ayzkfhlzqhuwlo33adonion.info]kraken6gf6o4rxewycqwjgfchzgxyfeoj5xafqbfm4vgvyaig2vmxvyd.onion[/url]
Increasingly, it appears likely he will be told to give up land in exchange for some sort of security guarantees.
The land side of that “deal” will be obvious. It can be drawn on a map. Crimea: gone, says Trump. Donetsk: give all of it up, says Putin, apparently with Trump’s blessing.
But the security guarantees? That’s where far more challenging ideas, like credibility, come into play. Could Zelensky rely on the US to deliver on some NATO Article 5-type promise, to defend Ukraine if Russia breaches any peace agreement?
Putin himself might even see an opportunity to further weaken the West, by testing any such guarantees, confident they are a bluff he could call. But all that would be for the future.
For now, it looks like Zelensky will have to weigh up whether he could bring his country with him if he were to cede territory to Russia – some of it still in Ukrainian hands – or whether he and his people could bear the costs of potentially defying Trump a Nobel Peace Prize, and say no.
If he chose the latter, would the US President immediately end all remaining American support for Ukraine, in terms of military aid and intelligence sharing, for instance?
If that happened, to what extent could Zelensky’s European allies really step in and fill in the gaps left by any full US retreat?
It is an almost impossibly hard choice before him.
kraken2trfqodidvlh4aa337cpzfrhdlfldhve5nf7njhumwr7instad.onion
https://kraken2trfqodidvlh4aa337cpzfrhdlfldhve5nf7njhumwr7inst.com
Jamesbow
20 Aug 25 at 11:56 am
Medicament prescribing information. What side effects can this medication cause?
how to get generic ceftin without a prescription
Everything information about medicament. Read information here.
how to get generic ceftin without a prescription
20 Aug 25 at 11:57 am
Jak samodzielnie zdjac https://telegra.ph/Jak-samodzielnie-zdj%C4%85%C4%87-sufit-napinany-instrukcja-krok-po-kroku-bez-haka-z-wkr%C4%99tem-i-trikami-monta%C5%BCyst%C3%B3w-08-07 sufit napinany: instrukcje krok po kroku, narzedzia, porady ekspertow. Dowiedz sie, jak zdemontowac plotno bez uszkodzen i przygotowac pomieszczenie do montazu nowej okladziny.
AlbertStorO
20 Aug 25 at 11:57 am
https://pxlmo.com/smaelsena
Chriszek
20 Aug 25 at 11:58 am
прогноз на футбол сегодня [url=www.prognozy-na-futbol-6.ru/]прогноз на футбол сегодня[/url] .
prognozi na fytbol_ohsn
20 Aug 25 at 12:01 pm
great points altogether, you simply received a new reader.
What may you suggest about your post that you made some days in the past?
Any sure?
aff=KingStore1986
20 Aug 25 at 12:03 pm
футбол прогноз на сегодня [url=prognozy-na-futbol-5.ru]prognozy-na-futbol-5.ru[/url] .
prognozi na fytbol_ptoa
20 Aug 25 at 12:03 pm
прогнозы на футбол сегодня [url=https://www.prognozy-na-futbol-5.ru]прогнозы на футбол сегодня[/url] .
prognozi na fytbol_weoa
20 Aug 25 at 12:06 pm
Aqua Tower seems like a game-changer for keeping clean drinking water easily
accessible. I really like the sleek design and the fact
that it saves space while still being super functional. Perfect for homes or offices where convenience and style both matter!
Aqua Tower
20 Aug 25 at 12:07 pm
Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
Получить исчерпывающие сведения – https://agriprime.pl/witaj-swiecie
Jamesneday
20 Aug 25 at 12:07 pm
Thanks very interesting blog!
kèo cá cược nhà cái hôm nay
20 Aug 25 at 12:07 pm
Right now it sounds like Movable Type is the top blogging platform available right
now. (from what I’ve read) Is that what you’re using
on your blog?
best personal injury lawyers near me
20 Aug 25 at 12:08 pm
Jak samodzielnie zdjac https://telegra.ph/Jak-samodzielnie-zdj%C4%85%C4%87-sufit-napinany-instrukcja-krok-po-kroku-bez-haka-z-wkr%C4%99tem-i-trikami-monta%C5%BCyst%C3%B3w-08-07 sufit napinany: instrukcje krok po kroku, narzedzia, porady ekspertow. Dowiedz sie, jak zdemontowac plotno bez uszkodzen i przygotowac pomieszczenie do montazu nowej okladziny.
AlbertStorO
20 Aug 25 at 12:09 pm
If you are going for most excellent contents like me, simply visit this website every day since it gives quality contents,
thanks
how to clean the tops of solar lights
20 Aug 25 at 12:11 pm
футбол ставки [url=www.prognozy-na-futbol-6.ru]www.prognozy-na-futbol-6.ru[/url] .
prognozi na fytbol_tnsn
20 Aug 25 at 12:12 pm
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Нажми и узнай всё – https://talkingindia.in/finance/pdl-profit-website-se-paise-kaise-kamaye
Robertjax
20 Aug 25 at 12:12 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—37at.ru]kra36 at[/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-39–cc.ru]kra35 at[/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.”
kraken35
https://kra-39at.ru
Kennethdig
20 Aug 25 at 12:13 pm
ставки футбол [url=www.prognozy-na-futbol-6.ru]www.prognozy-na-futbol-6.ru[/url] .
prognozi na fytbol_nwsn
20 Aug 25 at 12:14 pm
1 win bet [url=http://1win22097.ru/]http://1win22097.ru/[/url]
1win_qtpr
20 Aug 25 at 12:14 pm
плинко [url=https://plinko3001.ru]https://plinko3001.ru[/url]
plinko_kz_dqEr
20 Aug 25 at 12:16 pm
https://pxlmo.com/nosTTatiannalovefive
Howardhib
20 Aug 25 at 12:17 pm
https://linkin.bio/subunidyqefoxyq
Chriszek
20 Aug 25 at 12:19 pm
Excellent post. Keep writing such kind of information on your
blog. Im really impressed by your site.
Hey there, You have performed a fantastic job.
I’ll definitely digg it and for my part recommend to my friends.
I’m sure they will be benefited from this web site.
brightest solar lights for walkway
20 Aug 25 at 12:20 pm
King445 คาสิโนออนไลน์ เว็บตรง ครบจบในที่เดียว
คาสิโนออนไลน์ เว็บตรง
20 Aug 25 at 12:22 pm
Woah! I’m really digging the template/theme of this site.
It’s simple, yet effective. A lot of times it’s hard
to get that “perfect balance” between user friendliness and visual appeal.
I must say you have done a superb job with this. Also, the blog loads very fast for me on Firefox.
Exceptional Blog!
how to clean garden lights
20 Aug 25 at 12:22 pm
ставки на футбол сегодня [url=prognozy-na-futbol-5.ru]prognozy-na-futbol-5.ru[/url] .
prognozi na fytbol_znoa
20 Aug 25 at 12:22 pm
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Смотрите также… – https://photoeditor24.com/2021/01/13/hello-world-2
Waynealiep
20 Aug 25 at 12:23 pm
plinko game online [url=https://plinko-kz2.ru]plinko game online[/url]
plinko_kz_kuer
20 Aug 25 at 12:24 pm
купить аттестат за 11 класс в краснодаре [url=www.arus-diplom22.ru/]купить аттестат за 11 класс в краснодаре[/url] .
Diplomi_cwsl
20 Aug 25 at 12:26 pm
Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
Ссылка на источник – https://himachalfastexpress.in/hp-govt-cabinet-takes-important-decisions-april-2022
MelvinKex
20 Aug 25 at 12:27 pm
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Подробнее – https://haval.pk/localization-development-engineers
Waynealiep
20 Aug 25 at 12:27 pm