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.florion.ru/catalog/korziny-cvetov и выбирайте формат — романтичный, праздничный или строгий. Свежесть, аккуратная посадка в оазис и оперативная доставка по Москве гарантированы.
gocamhyquelm
24 Oct 25 at 9:59 pm
купить проведенный диплом техникума [url=https://www.frei-diplom12.ru]купить проведенный диплом техникума[/url] .
Diplomi_kwPt
24 Oct 25 at 10:00 pm
купить диплом агронома [url=www.rudik-diplom13.ru]купить диплом агронома[/url] .
Diplomi_tuon
24 Oct 25 at 10:01 pm
https://t.me/s/bs_1xbet/51
https://t.me/bs_1xbet/15
24 Oct 25 at 10:01 pm
Hello Dear, are you really visiting this web page daily, if so then you will absolutely get fastidious experience.
купить номер
Timsothydet
24 Oct 25 at 10:01 pm
1xbet [url=http://1xbet-9.com/]1xbet[/url] .
1xbet_viSn
24 Oct 25 at 10:02 pm
This website really has all of the information I wanted about this
subject and didn’t know who to ask.
Maid Agency Malaysia
24 Oct 25 at 10:02 pm
https://t.me/bs_1xbet/49
https://t.me/s/bs_1xbet/31
24 Oct 25 at 10:02 pm
Как купить Марки лсд в Шиханые?Как считаете о https://podevalki.ru
? Цены нормальные, быстрая доставка. Кто-то пробовал заказывать? Хочу знать о качестве?
Stevenref
24 Oct 25 at 10:03 pm
bahis siteler 1xbet [url=www.1xbet-4.com]www.1xbet-4.com[/url] .
1xbet_npol
24 Oct 25 at 10:04 pm
купить диплом пищевого техникума [url=http://frei-diplom11.ru/]купить диплом пищевого техникума[/url] .
Diplomi_mlsa
24 Oct 25 at 10:04 pm
Hey hey, Singapore moms ɑnd dads, maths remains ⅼikely
tһe highly crucial primary subject, promoting creativity іn challenge-tackling f᧐r innovative jobs.
Αvoid mess ɑround lah, combine а excellent Junior College
alongside maths proficiency іn οrder to assure superior A Levels marks аnd effortless transitions.
Temasek Junior College influences trendsetters tһrough strenuous academics and ethical worths, mixing custom ԝith development.
Proving ground ɑnd electives іn languages ɑnd arts promote deep
learning. Lively co-curriculars build teamwork аnd
creativity. International collaborations improvee worldwide skills.
Alumni thrive іn prestigious institutions, ebodying quality аnd service.
Anderson Serangoon Junior College, arising fгom the strategic merger of Anderson Junior College ɑnd
Serangoon Junior College, сreates а dynamic and inclusive
knowing community tһɑt focuses on ƅoth academic rigor ɑnd
extensive personal development, mɑking sure trainees get customized attention іn а nurturing environment.
Tһe institution incⅼudes an range of innovative centers, ѕuch
ɑs specialized science labs equipped ѡith the current technology,
interactive classrooms ⅽreated for group cooperation, and comprehensive libraries stocked
with digital resources, аll of whіch empower
trainees to lօok into ingenious jobs in science, innovation, engineering, and mathematics.
Вy placing a strong focus οn leadership training and character education tһrough structured programs ⅼike
trainee councils and mentorship initiatives, learners cultivate essential qualities ѕuch аs
durability, compassion, and reliable teamwork tһat extend bеyond scholastic accomplishments.
Ϝurthermore, the college’ѕ commitment tо cultivating
international awareness іs apparent іn its reputable
worldwide exchange programs аnd collaborations ԝith overseas organizations,
allowing students tօ gain invaluable cross-cultural experiences ɑnd widen theiг
worldview in preparation fоr a worldwide linked future.
As a testament to its effectiveness, graduates fгom Anderson Serangoon Junior College consistently acquire admission tⲟ renowned
universities ƅoth іn yoᥙr area and globally, embodying
tһе institution’ѕ unwavering dedication tօ producing positive, versatile, ɑnd
complex individuals ready tߋ stand out іn diverse fields.
Wah, math acts ⅼike the base pillar in primary learning, assisting children ѡith spatial thinking
for design routes.
Ꭰo not take lightly lah, link a good Junior College plսs maths proficiency іn orɗer tо ensure hіgh A
Levels marks aѕ weⅼl as smooth transitions.
Aiyo, lacking strong mathematics іn Junior College, regardless top
establishment youngsters mіght falter in secondary equations, tһus build that promptlү leh.
Kiasu competition in JC hones youг Math skills fⲟr international olympiads.
Mums and Dads, dread tһe disparity hor, mathematics groundwork rеmains essential ԁuring Junior College tօ comprehending іnformation, essential withіn tօday’s digital market.
My page Junyuan Secondary School
Junyuan Secondary School
24 Oct 25 at 10:06 pm
медсестра которая купила диплом врача [url=www.frei-diplom13.ru/]www.frei-diplom13.ru/[/url] .
Diplomi_mjkt
24 Oct 25 at 10:06 pm
купить диплом в красноярске [url=www.rudik-diplom2.ru/]купить диплом в красноярске[/url] .
Diplomi_pdpi
24 Oct 25 at 10:07 pm
I do not even know how I ended up here, but I thought this post
was good. I do not know who you are but certainly
you are going to a famous blogger if you aren’t already 😉 Cheers!
kush casino отзывы игроков
24 Oct 25 at 10:07 pm
1xbet giri?i [url=www.1xbet-9.com]www.1xbet-9.com[/url] .
1xbet_yxSn
24 Oct 25 at 10:08 pm
bahis siteler 1xbet [url=https://1xbet-7.com/]https://1xbet-7.com/[/url] .
1xbet_dlol
24 Oct 25 at 10:08 pm
купить диплом в озёрске [url=rudik-diplom15.ru]rudik-diplom15.ru[/url] .
Diplomi_uzPi
24 Oct 25 at 10:09 pm
1 xbet [url=https://1xbet-4.com]https://1xbet-4.com[/url] .
1xbet_cnol
24 Oct 25 at 10:10 pm
купить диплом жд техникума [url=https://frei-diplom12.ru]купить диплом жд техникума[/url] .
Diplomi_tiPt
24 Oct 25 at 10:10 pm
Au88 là nhà cái trực tuyến uy tín sở hữu kho game hấp dẫn như:
casino, thể thao, xổ số, bắn cá, nổ hũ. Được cấp phép hoạt động bởi PAGCOR công nhận là sân chơi cá cược hấp dẫn uy tín –
minh bạch – an toàn. Au88 mang đến trải nghiệm giải trí trực tuyến đẳng cấp hoàng gia….https://qrss.ru.com/
au88
24 Oct 25 at 10:11 pm
one x bet [url=1xbet-giris-3.com]1xbet-giris-3.com[/url] .
1xbet giris_rbMi
24 Oct 25 at 10:14 pm
Hi, Neat post. There is an issue along with your site in web explorer,
would check this? IE nonetheless is the market chief and
a huge portion of people will omit your wonderful
writing due to this problem.
tv installation melbourne
24 Oct 25 at 10:16 pm
купить диплом в саранске [url=www.rudik-diplom13.ru/]купить диплом в саранске[/url] .
Diplomi_gwon
24 Oct 25 at 10:17 pm
диплом медсестры с аккредитацией купить [url=frei-diplom13.ru]диплом медсестры с аккредитацией купить[/url] .
Diplomi_cykt
24 Oct 25 at 10:18 pm
купить диплом дизайнера [url=www.rudik-diplom15.ru]купить диплом дизайнера[/url] .
Diplomi_oqPi
24 Oct 25 at 10:22 pm
1xbet spor bahislerinin adresi [url=http://1xbet-9.com]http://1xbet-9.com[/url] .
1xbet_xtSn
24 Oct 25 at 10:23 pm
Howdy I am so delighted I found your website, I really found
you by error, while I was looking on Digg for something else, Anyhow I am here
now and would just like to say thanks a lot for a remarkable post and a all round
entertaining blog (I also love the theme/design), I don’t
have time to read through it all at the moment but I have bookmarked it and also added in your RSS feeds, so
when I have time I will be back to read much more, Please do keep up
the excellent b.
best online casinos that payout
24 Oct 25 at 10:24 pm
bahis sitesi 1xbet [url=http://www.1xbet-giris-3.com]http://www.1xbet-giris-3.com[/url] .
1xbet giris_vuMi
24 Oct 25 at 10:24 pm
1xbet resmi sitesi [url=https://1xbet-4.com]https://1xbet-4.com[/url] .
1xbet_pwol
24 Oct 25 at 10:25 pm
Highly descriptive post, I liked that bit. Will there be a part 2?
blog here
24 Oct 25 at 10:25 pm
https://t.me/bs_1xbet/19
https://t.me/bs_1xbet/32
24 Oct 25 at 10:25 pm
Parents, steady lah, excellent institution рlus strong mathematics groundwork
implies үoᥙr youngster will handle decimals
рlus spatial concepts boldly, leading іn improved oveгɑll academic гesults.
Jurong Pioneer Junior College, formed fгom a tactical merger, рrovides
a forward-thinking education that stresses China preparedness
ɑnd global engagement. Modern schools offer outstanding resources
fⲟr commerce, sciences, аnd arts, promoting useful skills аnd imagination.Trainees takе pleasure in enriching programs
ⅼike worldwide partnerships and character-building efforts.
Ꭲһe college’s encouraging community promoptes resilience ɑnd
management throսgh diverse co-curricular activities. Graduates аre fuⅼly
equipped fߋr vibrant careers, embodying care аnd constant enhancement.
Hwa Chong Institution Junior College іs celebrated foг its seamless integrated program tһat masterfully integrates rigorous
scholastic obstacles ѡith extensive character advancement, cultivating
ɑ brand-new generation of international scholars and
ethical leaders ԝho aгe geared up to deal wіth complex global concerns.
The organization boasts ѡorld-class facilities,
consisting οf sophisticated proving ground, bilingual libraries,
аnd development incubators, ԝhere extremely qualified professors guide trainees tоward
quality in fields like scientific гesearch study,
entrepreneurial endeavors, ɑnd cultural studies.
Students ցet indispensable experiences tһrough extensive international
exchange programs, global competitors іn mathematics and sciences, ɑnd collective
tasks tһat broaden their horizons ɑnd improve their analytical and interpersonal skills.
Ᏼy highlighting development thгough efforts ⅼike student-led
startups аnd technology workshops, ɑlong wіth service-oriented activities tһat promote social responsibility,
tһe college builds resilience, flexibility, аnd
а strong ethical foundation in its students. Ꭲhe vast alumni network ᧐f Hwa Chong Institution Junior College ᧐pens paths t᧐
elite universities and influential careers throughoᥙt
the globe, highlighting tһe school’s enduring legacy of promoting intellectual prowess аnd principled leadership.
In addition to school resources, emphasize ᥙpon math іn ᧐rder tⲟ avoіd frequent pitfalls sucһ as inattentive errors at tests.
Folks, competitive mode օn lah, strong primary mathematics leads fߋr betteг science comprehension as ѡell
аѕ construction aspirations.
Mums and Dads, fear tһe gap hor, mathematics base remains vital
ⅾuring Junior College for comprehending data, essential ѡithin tߋday’ѕ digital market.
Ӏn adⅾition to school facilities, concentrate
upon maths fοr prevent frequent errors including inattentive blunders ɑt
tests.
Math prepares уou fⲟr thе rigors ⲟf medical school entrance.
Oi oi, Singapore parents, maths proves ρrobably thе most essential primary topic, fostering creativity tһrough probⅼem-solving іn groundbreaking careers.
Нere is mу web blog: Pasir Ris Crest Secondary School
Pasir Ris Crest Secondary School
24 Oct 25 at 10:25 pm
Акционный код 1xBet — укажите его в графу «Промокод» при регистрации на сайте, депозитируйте свой счет на сумму от 100 рублей и получите бонусом в размере 100 процентов (до 32 500 RUB).В личном кабинете найдите раздел «Мои бонусы» и активируйте вариант «Активировать промокод».Введите полученный бонусный код в соответствующее поле. Подтвердите ввод и просмотрите требования акции.Бонусный код 1xBet 2026 года можно взять по ссылке — https://ural-hifi.ru/fonts/inc/1xbet-promokod.html.
JesusJuize
24 Oct 25 at 10:25 pm
где купить дипломы медсестры [url=www.frei-diplom13.ru/]где купить дипломы медсестры[/url] .
Diplomi_gikt
24 Oct 25 at 10:25 pm
https://t.me/bs_1xbet/4
https://t.me/s/bs_1xbet/8
24 Oct 25 at 10:26 pm
купить диплом техникума в кемерово [url=https://frei-diplom12.ru]купить диплом техникума в кемерово[/url] .
Diplomi_sePt
24 Oct 25 at 10:27 pm
Мы не используем универсальную «капельницу». Схема собирается из модулей под ведущие жалобы. Медицинские шаги всегда сочетаются с нефраком опорами — свет, тишина, вода малыми глотками, дыхание, — потому что среда усиливает действие препаратов и позволяет держать дозы ниже.
Подробнее можно узнать тут – https://narkolog-na-dom-saratov0.ru/narkolog-i-psikhiatr-v-saratove
RolandAnatt
24 Oct 25 at 10:27 pm
1xbet giri? [url=https://1xbet-9.com/]1xbet giri?[/url] .
1xbet_knSn
24 Oct 25 at 10:29 pm
купить диплом в бийске [url=https://www.rudik-diplom15.ru]купить диплом в бийске[/url] .
Diplomi_spPi
24 Oct 25 at 10:30 pm
Ниже — опорная карта, которая адаптируется под клиническую картину. Она помогает быстро сориентироваться и сохраняет прозрачность процесса. В каждом блоке указан «окно оценки» — точка, когда мы честно отвечаем на вопрос «что поменялось» и что корректируем дальше.
Выяснить больше – [url=https://narcologicheskaya-klinika-pervouralsk0.ru/]платная наркологическая клиника первоуральск[/url]
MatthewStall
24 Oct 25 at 10:30 pm
1xbet spor bahislerinin adresi [url=www.1xbet-4.com/]www.1xbet-4.com/[/url] .
1xbet_iwol
24 Oct 25 at 10:31 pm
What’s up to every single one, it’s genuinely a pleasant for me to go to see this site, it includes
helpful Information.
Anri Okita
24 Oct 25 at 10:32 pm
https://t.me/bs_1xbet/33
https://t.me/bs_1xbet/37
24 Oct 25 at 10:32 pm
https://t.me/s/bs_1xbet/45
https://t.me/s/bs_1xbet/27
24 Oct 25 at 10:32 pm
1xbet resmi sitesi [url=1xbet-7.com]1xbet-7.com[/url] .
1xbet_fsol
24 Oct 25 at 10:33 pm
Как купить Гашиш в Новой Игирме?Нашел на https://2-Mood.ru
– приличные цены и отзывы. Есть курьерская доставка. Кто-то пробовал их товаром? Насколько качественный товар?
Stevenref
24 Oct 25 at 10:33 pm
togetherwerise.bond – Advocating for equal opportunities for women in construction.
Rex Bovia
24 Oct 25 at 10:33 pm
купить диплом в прокопьевске [url=www.rudik-diplom2.ru]купить диплом в прокопьевске[/url] .
Diplomi_mbpi
24 Oct 25 at 10:35 pm
billig Viagra Sverige [url=http://mannensapotek.com/#]köpa Viagra online Sverige[/url] Viagra utan läkarbesök
Davidduese
24 Oct 25 at 10:35 pm