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!
OMT’s helpful comments loopholes encourage growth attitude, assisting
pupils adore math аnd really feel motivated fⲟr exams.
Dive into self-paced math proficiency ѡith OMT’s
12-month e-learning courses, tߋtal with practice worksheets and recorded sessions
fоr comprehensive revision.
In a system where mathematics education һaѕ actuaⅼly progressed tο
promote development аnd worldwide competitiveness, enrolling in math tuition
mɑkes sure students stay ahead by deepening theiг understanding ɑnd application of essential ideas.
primary tuition іs іmportant for PSLE aѕ it uses remedial assistance for topics ⅼike еntire numbers and measurements, guaranteeing no foundational weaknesses continue.
Ɗetermining аnd fixing cеrtain weaknesses, like in chance օr coordinate geometry, mаkes
secondary tuition indispensable fօr O Level excellence.
Preparing fⲟr thе changability of A Level concerns, tuition develops flexible analytic methods fⲟr real-time
exam circumstances.
OMT’ѕ customized syllabus distinctively straightens ᴡith MOE structure by providing connecting components fߋr smooth changes between primary, secondary, and JC math.
OMT’ѕ cost effective online choide lah, supplying һigh quality tuition ԝithout damaging the financial institution fⲟr mucһ ƅetter mathematics outcomes.
Tuition facilities mɑke use of innovative devices ⅼike
visual һelp, improving understanding for far better retention in Singapore mathematics exams.
math tuition
6 Oct 25 at 8:06 am
заказать кухню спб [url=https://www.kuhni-spb-4.ru]https://www.kuhni-spb-4.ru[/url] .
kyhni spb_vjer
6 Oct 25 at 8:06 am
https://clomicareusa.shop/# Generic Clomid
DavidThink
6 Oct 25 at 8:07 am
купить диплом техникума ссср в оренбурге [url=https://www.frei-diplom7.ru]купить диплом техникума ссср в оренбурге[/url] .
Diplomi_tiei
6 Oct 25 at 8:07 am
кухня на заказ спб [url=https://www.kuhni-spb-2.ru]https://www.kuhni-spb-2.ru[/url] .
kyhni spb_dkmn
6 Oct 25 at 8:10 am
кухни на заказ санкт петербург от производителя [url=kuhni-spb-4.ru]kuhni-spb-4.ru[/url] .
kyhni spb_grer
6 Oct 25 at 8:11 am
кухни на заказ спб [url=www.kuhni-spb-3.ru/]кухни на заказ спб[/url] .
kyhni spb_myMr
6 Oct 25 at 8:11 am
В течение полугода пациент может бесплатно посещать онлайн-группы поддержки и консультироваться у психологов клиники.
Подробнее можно узнать тут – [url=https://lechenie-narkomanii-volgograd9.ru/]www.domen.ru[/url]
Jimmyornaw
6 Oct 25 at 8:11 am
Hi, just wanted to tell you, I loved this post. It was
funny. Keep on posting!
Westwood Bitnova Scam
6 Oct 25 at 8:12 am
https://krasavchikbro.ru
EdwardTrege
6 Oct 25 at 8:13 am
Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
Получить полную информацию – https://www.sptinkgroup.com/a-post-without-image
JimmieInofs
6 Oct 25 at 8:14 am
кухни на заказ спб недорого с ценами [url=https://kuhni-spb-4.ru/]https://kuhni-spb-4.ru/[/url] .
kyhni spb_ocer
6 Oct 25 at 8:14 am
คอนเทนต์นี้ อ่านแล้วเข้าใจเรื่องนี้มากขึ้น ครับ
ผม เคยติดตามเรื่องนี้จากหลายแหล่ง เนื้อหาในแนวเดียวกัน
ซึ่งอยู่ที่ 123bet
ลองแวะไปดู
มีการสรุปเนื้อหาไว้อย่างดี
ขอบคุณที่แชร์ เนื้อหาที่น่าสนใจ นี้
และอยากเห็นบทความดีๆ แบบนี้อีก
123bet
6 Oct 25 at 8:15 am
lovemoda.store – Navigation seems intuitive, easier to browse different collections.
Phuong Luciani
6 Oct 25 at 8:16 am
В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
Узнать больше > – https://longhai24h.com/bao-ve-yeu-nhan
MichaelFup
6 Oct 25 at 8:16 am
современные кухни на заказ в спб [url=https://kuhni-spb-2.ru/]https://kuhni-spb-2.ru/[/url] .
kyhni spb_prmn
6 Oct 25 at 8:17 am
купить диплом техникума в воронеже [url=https://frei-diplom10.ru]купить диплом техникума в воронеже[/url] .
Diplomi_fiEa
6 Oct 25 at 8:19 am
Анонимные методы борьбы с алкоголизмом становится востребованным, так как многие люди стремятся вернуться к нормальной жизни в условиях конфиденциальности. На сайте narkolog-tula027.ru представлены различные программы реабилитации, включая detox-программы, которые обеспечивают комфортные условия для лечения. Помощь врачей при алкоголизме включает методы кодирования и психотерапию при зависимостях. Группы поддержки в анонимном формате помогают справиться с психологическими проблемами, а опора близких играет важную роль в процессе восстановления от алкогольной зависимости. Консультации по алкоголизму онлайн и консультации без раскрытия данных обеспечивают доступ к профессиональной помощи при запойном состоянии. Лечение без названия дает возможность людям быть уверенными в конфиденциальности. Важно помнить, что первый шаг к выздоровлению, это обращение за помощью.
vivodtulaNeT
6 Oct 25 at 8:21 am
купить диплом агронома [url=https://rudik-diplom10.ru/]купить диплом агронома[/url] .
Diplomi_hhSa
6 Oct 25 at 8:21 am
Этот обзор дает возможность взглянуть на историю и науку под новым углом. Мы представляем редкие факты, неожиданные связи и значимые события, которые помогут вам глубже понять развитие цивилизации и роль человека в ней.
Полезно знать – https://fuji-cryptofx.com/hello-world
Jeffreybuppy
6 Oct 25 at 8:22 am
купить диплом техникума и поступить в вуз [url=https://www.frei-diplom8.ru]купить диплом техникума и поступить в вуз[/url] .
Diplomi_qzsr
6 Oct 25 at 8:22 am
как купить диплом колледжа [url=http://frei-diplom12.ru]http://frei-diplom12.ru[/url] .
Diplomi_ddPt
6 Oct 25 at 8:22 am
кухни на заказ производство спб [url=kuhni-spb-3.ru]kuhni-spb-3.ru[/url] .
kyhni spb_fyMr
6 Oct 25 at 8:22 am
Публикация предлагает читателю не просто информацию, а инструменты для анализа и саморазвития. Мы стимулируем критическое мышление, предлагая различные точки зрения и призывая к самостоятельному поиску решений.
Полная информация здесь – https://www.avisng.com/make-reservation
Haroldalatt
6 Oct 25 at 8:23 am
производство кухонь в спб на заказ [url=https://kuhni-spb-4.ru]https://kuhni-spb-4.ru[/url] .
kyhni spb_eter
6 Oct 25 at 8:27 am
https://amoxdirectusa.com/# buying amoxicillin online
DavidThink
6 Oct 25 at 8:27 am
forexplatform.website – I just discovered this blog and love the clear insights shared.
Renaldo Wisnowski
6 Oct 25 at 8:27 am
усиление грунтов [url=https://privetsochi.ru/blog/realty_sochi/93972.html/]privetsochi.ru/blog/realty_sochi/93972.html[/url] .
ysilenie gryntov_ifSr
6 Oct 25 at 8:28 am
manchunyuan1.xyz – Clean layout and useful topics, I’ll definitely return regularly.
Nilda Levell
6 Oct 25 at 8:28 am
buying propecia tablets [url=https://regrowrxonline.com/#]RegrowRx Online[/url] buy propecia
Davidbax
6 Oct 25 at 8:29 am
купить диплом в глазове [url=www.rudik-diplom10.ru]купить диплом в глазове[/url] .
Diplomi_zlSa
6 Oct 25 at 8:29 am
купить диплом мед колледжа в красноярске [url=https://frei-diplom8.ru]https://frei-diplom8.ru[/url] .
Diplomi_visr
6 Oct 25 at 8:30 am
где можно купить диплом медицинского колледжа [url=www.frei-diplom12.ru]www.frei-diplom12.ru[/url] .
Diplomi_jlPt
6 Oct 25 at 8:30 am
купить старый диплом техникума [url=www.frei-diplom11.ru/]купить старый диплом техникума[/url] .
Diplomi_vwsa
6 Oct 25 at 8:30 am
наркология анонимно [url=http://www.narkologicheskaya-klinika-19.ru]http://www.narkologicheskaya-klinika-19.ru[/url] .
narkologicheskaya klinika _ibmi
6 Oct 25 at 8:30 am
chinh-sua-anh.online – The pricing page is clear, no hidden surprises, that’s rare.
Justin Schulteis
6 Oct 25 at 8:30 am
кухни на заказ петербург [url=http://www.kuhni-spb-2.ru]http://www.kuhni-spb-2.ru[/url] .
kyhni spb_xjmn
6 Oct 25 at 8:30 am
lovemoda.store – I’ll check back when they list their bestsellers or deals.
Alphonso Knoll
6 Oct 25 at 8:31 am
изготовление кухни на заказ в спб [url=www.kuhni-spb-3.ru]www.kuhni-spb-3.ru[/url] .
kyhni spb_qkMr
6 Oct 25 at 8:32 am
more information
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
more information
6 Oct 25 at 8:33 am
52ch.cc – This site seems to cover a lot of topics, quite impressive indeed.
Daniela Bisonette
6 Oct 25 at 8:34 am
экстренное вытрезвление в москве [url=https://narkologicheskaya-klinika-19.ru]https://narkologicheskaya-klinika-19.ru[/url] .
narkologicheskaya klinika _pmmi
6 Oct 25 at 8:35 am
Temukan link alternatif resmi BEJOGAMING untuk akses tanpa blokir.
Dapatkan link alternatif terbaru dan terpercaya untuk bermain di
BEJOGAMING.
Link Alternatif BEJOGAMING
6 Oct 25 at 8:36 am
Важность сайта рейтингов для развития вашего бизнеса
Сегодня конкуренция среди компаний значительно возросла, и каждый бизнес стремится выделиться среди конкурентов. Одним из наиболее эффективных инструментов привлечения клиентов является создание качественного и удобного веб-сайта. Однако недостаточно просто создать сайт — важно также отслеживать его эффективность и понимать, насколько он соответствует ожиданиям пользователей. Именно здесь приходят на помощь сайты рейтингов.
[url=https://cis-awards.ru/reitingi]Сайт рейтинги для бизнеса[/url]
¦ Что такое сайты рейтингов?
Сайт рейтинга представляет собой онлайн-платформу, где пользователи оставляют отзывы и оценки о товарах, услугах или компаниях. Эти площадки позволяют потенциальным клиентам ознакомиться с мнением реальных покупателей перед принятием решения о покупке. Для бизнеса же наличие положительных отзывов и высоких оценок повышает доверие потребителей и увеличивает вероятность выбора именно вашей компании.
¦ Как сайты рейтингов помогают бизнесу?
[url=https://cis-awards.ru/top10_kompanii_v_sfere_ii]https://cis-awards.ru/top10_kompanii_v_sfere_ii[/url]
1. Повышение доверия: Положительные отзывы и высокие рейтинги создают позитивный имидж компании, что привлекает новых клиентов.
2. Анализ конкурентоспособности: Рейтинги позволяют сравнивать свою компанию с аналогичными предприятиями отрасли, выявлять сильные и слабые стороны продукта или услуги.
3. Обратная связь: Отзывы пользователей предоставляют ценный источник информации о качестве товаров и услуг, позволяя оперативно реагировать на жалобы и улучшать качество обслуживания.
4. SEO-продвижение: Сайты рейтингов часто индексируются поисковиками, что способствует повышению видимости сайта компании в поисковых системах.
Топ-9 компаний разрабатывающих стратегии для бизнеса в 2026 году
https://cis-awards.ru/reitingi
¦ Какие факторы влияют на позицию в рейтинге?
Для успешного продвижения своего бренда на сайтах рейтингов необходимо учитывать ряд факторов:
– Качество предоставляемых услуг или продукции.
– Уровень удовлетворенности клиентов.
– Активность компании в социальных сетях и маркетинге.
– Скорость реагирования на отрицательные отзывы.
¦ Заключение
Использование сайтов рейтингов становится неотъемлемой частью стратегии развития любого современного бизнеса. Они обеспечивают объективную оценку качества ваших продуктов и услуг, способствуют привлечению новых клиентов и укреплению позиций компании на рынке. Инвестируя в улучшение своей репутации на таких площадках, вы инвестируете в долгосрочный успех своего дела.
Williamgeani
6 Oct 25 at 8:36 am
производство кухонь в спб на заказ [url=http://kuhni-spb-3.ru/]http://kuhni-spb-3.ru/[/url] .
kyhni spb_hhMr
6 Oct 25 at 8:39 am
https://death-planet.ru
EdwardTrege
6 Oct 25 at 8:39 am
купить диплом фельдшера [url=http://www.rudik-diplom9.ru]купить диплом фельдшера[/url] .
Diplomi_bpei
6 Oct 25 at 8:39 am
частная наркологическая клиника [url=https://narkologicheskaya-klinika-19.ru/]narkologicheskaya-klinika-19.ru[/url] .
narkologicheskaya klinika _eqmi
6 Oct 25 at 8:40 am
This is my first time pay a quick visit at here and i am truly impressed to read
everthing at single place.
https://ipod.cn.com
6 Oct 25 at 8:40 am
Hi there! I could have sworn I’ve been to this site
before but after browsing through some of the post
I realized it’s new to me. Nonetheless, I’m definitely happy I found
it and I’ll be book-marking and checking back frequently!
Noble Flowdex
6 Oct 25 at 8:41 am