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!
Thanks very nice blog!
فرهنگیان یا پرستاری
20 Aug 25 at 12:27 pm
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Подробнее тут – http://jyninfo.com/2015/11/24/news-heading-4
MelvinKex
20 Aug 25 at 12:30 pm
прогноз на футбол [url=www.prognozy-na-futbol-6.ru]прогноз на футбол[/url] .
prognozi na fytbol_cosn
20 Aug 25 at 12:30 pm
Hey very cool website!! Guy .. Excellent .. Superb
.. I will bookmark your blog and take the feeds additionally?
I am satisfied to seek out a lot of helpful information right here within the put
up, we’d like develop more techniques on this regard,
thanks for sharing. . . . . .
bandar togel
20 Aug 25 at 12:32 pm
ставки футбол [url=www.prognozy-na-futbol-5.ru]www.prognozy-na-futbol-5.ru[/url] .
prognozi na fytbol_yroa
20 Aug 25 at 12:33 pm
бесплатные прогнозы на спорт с высокой проходимостью [url=www.prognozy-na-sport-8.ru/]www.prognozy-na-sport-8.ru/[/url] .
prognozi na sport_nwmi
20 Aug 25 at 12:34 pm
авиатор игра скачать [url=http://1win22097.ru/]http://1win22097.ru/[/url]
1win_bwpr
20 Aug 25 at 12:34 pm
провайдер по адресу
krasnoyarsk-domashnij-internet006.ru
интернет по адресу дома
inernetadreselini
20 Aug 25 at 12:35 pm
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Ссылка на источник – https://www.oribattery.cn/suspendisse-at-semper-ipsum
Rodneytooft
20 Aug 25 at 12:37 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://kra27cc.ru]kra39[/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-35at.ru]kra32 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.”
kra39 cc
https://kra40-at.ru
Rickylit
20 Aug 25 at 12:38 pm
Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
Получить исчерпывающие сведения – https://apexolution.com/get-ahead-of-your-competition-our-proven-digital
Rodneytooft
20 Aug 25 at 12:39 pm
https://mez.ink/girardil0vez
Chriszek
20 Aug 25 at 12:40 pm
прогноз футбол [url=http://prognozy-na-futbol-6.ru]прогноз футбол[/url] .
prognozi na fytbol_zxsn
20 Aug 25 at 12:41 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://kra38—cc.ru]kra38[/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]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 cc
https://kra–39-cc.ru
Elmercoisp
20 Aug 25 at 12:42 pm
plinko game online [url=www.plinko3002.ru]www.plinko3002.ru[/url]
plinko_kz_nsPa
20 Aug 25 at 12:44 pm
I am sure this article has touched all the internet people, its
really really pleasant paragraph on building up new blog.
how to clean solar panels on garden lights
20 Aug 25 at 12:44 pm
You could definitely see your skills in the work you write.
The world hopes for even more passionate writers such as you
who are not afraid to mention how they believe.
Always go after your heart.
inatogel
20 Aug 25 at 12:44 pm
Right here is the perfect web site for anybody who hopes
to find out about this topic. You realize so much its almost tough to argue with you (not that I personally
would want to…HaHa). You certainly put a brand new spin on a topic that has been written about for decades.
Wonderful stuff, just wonderful!
как похудеть на 15 кг за 1 месяц
20 Aug 25 at 12:48 pm
Online sources for Kamagra in the United States: Kamagra oral jelly USA availability – Kamagra reviews from US customers
RichardTit
20 Aug 25 at 12:50 pm
Obtaining credentials from the reputable Curacao egaming authorities
and enlisting talented developers, Empire furnishes an abundant
game selection spanning over 2,000 titles.
Susana
20 Aug 25 at 12:51 pm
Good info. Lucky me I discovered your blog by accident (stumbleupon).
I have saved as a favorite for later!
xem bóng đá trực tiếp keonhacai
20 Aug 25 at 12:53 pm
блэкспрут вход
RichardPep
20 Aug 25 at 12:53 pm
Психолог
rrrwrf4847
20 Aug 25 at 12:54 pm
бесплатные прогнозы на спорт с высокой проходимостью [url=prognozy-na-sport-8.ru]prognozy-na-sport-8.ru[/url] .
prognozi na sport_tumi
20 Aug 25 at 12:54 pm
психолог запись онлайн
Charliesoall
20 Aug 25 at 12:55 pm
Good post. I’m experiencing some of these issues as well..
w xxxx
20 Aug 25 at 12:57 pm
Tadalify: Tadalify – Tadalify
RichardTit
20 Aug 25 at 12:59 pm
My partner and I stumbled over here by a different web page
and thought I may as well check things out. I like what I see so now
i am following you. Look forward to checking out
your web page for a second time.
Immediate App Ai
20 Aug 25 at 1:00 pm
http://webanketa.com/forms/6mrk6csk68qkgd1kcct68c33/
Chriszek
20 Aug 25 at 1:01 pm
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Ссылка на источник – https://www.iheir13.com/5214.html
EddieKanna
20 Aug 25 at 1:02 pm
где можно купить аттестат 11 классов липецк [url=arus-diplom22.ru]где можно купить аттестат 11 классов липецк[/url] .
Diplomi_fdsl
20 Aug 25 at 1:03 pm
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Разобраться лучше – https://sipenmaru.poltekkespalu.ac.id/2023/01/17/tutorial-cara-pendftaran-jalur-pmdp
EddieKanna
20 Aug 25 at 1:12 pm
Hi, after reading this remarkable piece of writing i am as well happy
to share my knowledge here with mates.
How to order Pentobarbital Sodium (Liquid) (Oral) Online
20 Aug 25 at 1:14 pm
ファイブスターズマーケッツとは?初心者にもわかりやすい取引プラットフォーム
casecreate.jp
20 Aug 25 at 1:14 pm
Долго искал решение и наконец-то нашел:
Между прочим, если вас интересует spb-hotels.ru, загляните сюда.
Вот, делюсь ссылкой:
[url=https://spb-hotels.ru]https://spb-hotels.ru[/url]
Буду рад, если кому-то пригодится.
rusPoito
20 Aug 25 at 1:16 pm
В этой статье представлен занимательный и актуальный контент, который заставит вас задуматься. Мы обсуждаем насущные вопросы и проблемы, а также освещаем истории, которые вдохновляют на действия и изменения. Узнайте, что стоит за событиями нашего времени!
Более подробно об этом – https://nanake555.com/the-rube-foe-%E0%B9%84%E0%B8%A1%E0%B9%88%E0%B9%83%E0%B8%8A%E0%B9%88%E0%B8%9E%E0%B8%A3%E0%B8%B0%E0%B9%80%E0%B8%AD%E0%B8%81-tonights-the-night-%E0%B8%84%E0%B8%B7%E0%B8%99%E0%B8%AA%E0%B8%B3%E0%B8%84
Richardgedge
20 Aug 25 at 1:18 pm
My relatives always say that I am killing my time here
at net, except I know I am getting know-how daily by reading thes nice articles or reviews.
how to clean solar garden lights
20 Aug 25 at 1:18 pm
https://healthmedinfo365.top/buy-now-accutane/
https://healthmedinfo365.top/buy-now-accutane/
20 Aug 25 at 1:22 pm
บทความนี้เจ๋งมากเลย เนื้อหาเกี่ยวกับคอโปโลมันน่าสนใจสุดๆ ข้าไม่เคยทราบมาก่อนว่ามันมีผลต่อลุคขนาดนี้ ประทับใจที่ผู้เขียนขยายความให้เห็นภาพว่าเลือกขอบคอแบบไหนถึงจะเหมาะกับตัวเอง
Feel free to surf to my web site :: สกรีนหมวกเซฟตี้
สกรีนหมวกเซฟตี้
20 Aug 25 at 1:23 pm
https://bio.site/tzjuigpg
Chriszek
20 Aug 25 at 1:23 pm
Yes! Finally someone writes about https://luludaniella.com/.
Luludaniella
20 Aug 25 at 1:31 pm
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Что ещё? Расскажи всё! – https://ticavisiontv.com/regional-fallece-el-ex-general-de-ejercito-humberto-ortega-saavedra-hermano-de-daniel-ortega
Richardgedge
20 Aug 25 at 1:33 pm
NewEra Protect is a wellness supplement created to support immune strength and overall health.
Its blend of natural ingredients is designed to fortify
the body’s defenses, reduce fatigue, and promote daily vitality.
Many people appreciate it as a simple and effective way to stay protected and energized, especially during times when wellness support
is most needed.
NewEra Protect
20 Aug 25 at 1:34 pm
canadian online pharmacy viagra
canadian online pharmacy viagra
20 Aug 25 at 1:37 pm
plinko slot [url=www.plinko-kz2.ru]www.plinko-kz2.ru[/url]
plinko_kz_dier
20 Aug 25 at 1:38 pm
https://bio.site/abydiufudea
Chriszek
20 Aug 25 at 1:44 pm
Tadalify [url=https://tadalify.com/#]tadalafil eli lilly[/url] non prescription cialis
RobertCat
20 Aug 25 at 1:48 pm
I like what you guys are up too. This type of clever work and
coverage! Keep up the fantastic works guys I’ve added you
guys to blogroll.
link bandar123
20 Aug 25 at 1:50 pm
Thank you for the auspicious writeup. It in fact was a amusement account
it. Look advanced to more added agreeable from you!
However, how could we communicate?
سامانه ثبت نام و ارزیابی تکمیلی دانشگاه فرهنگیان
20 Aug 25 at 1:52 pm
Magnificent beat ! I wish to apprentice while you amend your web site, how can i subscribe for a blog web site?
The account helped me a acceptable deal. I had been a little bit acquainted of this your broadcast provided bright clear idea
سامانه ارزیابی تکمیلی فرهنگیان
20 Aug 25 at 1:52 pm