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!
купить диплом проведенный [url=https://frei-diplom4.ru/]купить диплом проведенный[/url] .
Diplomi_tsOl
2 Nov 25 at 5:53 pm
When I originally commented I clicked the “Notify me when new comments are added”
checkbox and now each time a comment is added I get several e-mails with the same
comment. Is there any way you can remove people from that service?
Thank you!
VU88
2 Nov 25 at 5:53 pm
745648.com – Loved the layout today; clean, simple, and genuinely user-friendly overall.
Jessie Camlin
2 Nov 25 at 5:55 pm
1xbet yeni adresi [url=www.1xbet-giris-4.com]www.1xbet-giris-4.com[/url] .
1xbet giris_nxSa
2 Nov 25 at 5:55 pm
1xbet g?ncel giri? [url=https://1xbet-giris-5.com/]1xbet g?ncel giri?[/url] .
1xbet giris_ipSa
2 Nov 25 at 5:56 pm
code promo 1xbet cote d’ivoire 2026
AbrahamERAME
2 Nov 25 at 5:56 pm
потолочкин ру натяжные потолки [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru]потолочкин ру натяжные потолки[/url] .
natyajnie potolki nijnii novgorod_zoma
2 Nov 25 at 5:57 pm
บทความนี้เกี่ยวกับพวงหรีดดอกไม้ เป็นประโยชน์สุดๆ
กำลังค้นหาข้อมูลเรื่องนี้อยู่พอดี ถือว่าเจอบทความดีๆ เลย
จะเก็บข้อมูลนี้ไว้ใช้แน่นอน ขอบคุณอีกครั้งครับ/ค่ะ
Alsoo visit my web blog – ร้านจัดดอกไม้งานศพ
ร้านจัดดอกไม้งานศพ
2 Nov 25 at 5:57 pm
1xbet giri? 2025 [url=http://1xbet-giris-2.com/]http://1xbet-giris-2.com/[/url] .
1xbet giris_euPt
2 Nov 25 at 5:58 pm
легально купить диплом о высшем образовании [url=http://www.frei-diplom3.ru]легально купить диплом о высшем образовании[/url] .
Diplomi_jvKt
2 Nov 25 at 5:58 pm
trusted online pharmacy UK: Uk Meds Guide – online pharmacy
Johnnyfuede
2 Nov 25 at 6:00 pm
купить диплом вуза с проводкой [url=http://frei-diplom4.ru/]http://frei-diplom4.ru/[/url] .
Diplomi_obOl
2 Nov 25 at 6:00 pm
https://t.me/official_1win_aviator/147
PokerPhantom
2 Nov 25 at 6:00 pm
агентство продвижения сайтов [url=http://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]агентство продвижения сайтов[/url] .
agentstvo poiskovogo prodvijeniya_iqKt
2 Nov 25 at 6:01 pm
https://t.me/s/uD_fLAgmAn
AlbertTeery
2 Nov 25 at 6:02 pm
1xbet giri? linki [url=https://1xbet-giris-4.com]https://1xbet-giris-4.com[/url] .
1xbet giris_ngSa
2 Nov 25 at 6:02 pm
1 x bet giri? [url=https://1xbet-giris-2.com]https://1xbet-giris-2.com[/url] .
1xbet giris_tqPt
2 Nov 25 at 6:03 pm
https://t.me/s/ud_MOstBeT
AlbertTeery
2 Nov 25 at 6:04 pm
“[url=https://peretyazhka-bel.ru/]Перетяжка диванов[/url]”
Перетяжка позволяет вернуть предметам интерьера первоначальную свежесть.
Такой подход не только экономит бюджет, но и позволяет индивидуализировать интерьер. Вы можете выбрать любой цвет и фактуру ткани под стиль комнаты.
—
### **2. Какие материалы лучше использовать?**
Для перетяжки применяют различные ткани, отличающиеся износостойкостью и внешним видом. Хлопок и лён подойдут для помещений с невысокой нагрузкой.
Также важно учитывать наполнитель, который влияет на комфорт. Поролон средней плотности обеспечит мягкость и долговечность.
—
### **3. Этапы профессиональной перетяжки**
Процесс начинается с демонтажа старой обивки и оценки состояния каркаса. Мастер удаляет изношенную ткань и проверяет прочность конструкции.
Далее выбирают материал и производят раскрой. Новая ткань кроится точно по размерам мебели, чтобы избежать перекосов.
—
### **4. Преимущества профессионального подхода**
Обращение к специалистам гарантирует качество и долгий срок службы мебели. Профессионалы используют надёжные крепления и прочные швы.
Кроме того, экономится время и исключаются ошибки. Только специалист сможет точно воспроизвести первоначальную форму мебели.
—
### **Спин-шаблон:**
#### **1. Почему стоит выбрать перетяжку мебели?**
– Смена ткани помогает сохранить любимый диван или кресло, избежав покупки новой мебели.
– Это отличный способ адаптировать мебель под меняющиеся предпочтения в оформлении дома.
#### **2. Какие материалы лучше использовать?**
– Кожа и экокожа придают мебели благородный вид и просты в уходе.
– Холофайбер и синтепон лучше сохраняют форму и упругость.
#### **3. Этапы профессиональной перетяжки**
– Старая ткань аккуратно снимается, а каркас проверяется на наличие повреждений.
– Новая ткань кроится точно по размерам мебели, чтобы избежать перекосов.
#### **4. Преимущества профессионального подхода**
– Профессионалы используют надёжные крепления и прочные швы.
– Самостоятельная перетяжка может привести к перекосам и быстрому износу.
peretyazhk_wlKi
2 Nov 25 at 6:05 pm
купить проведенный диплом высокие [url=frei-diplom3.ru]купить проведенный диплом высокие[/url] .
Diplomi_uaKt
2 Nov 25 at 6:05 pm
купить диплом с реестром вуза [url=http://www.frei-diplom4.ru]купить диплом с реестром вуза[/url] .
Diplomi_syOl
2 Nov 25 at 6:08 pm
1xbet giri? [url=https://1xbet-giris-5.com/]1xbet giri?[/url] .
1xbet giris_kzSa
2 Nov 25 at 6:10 pm
сео агентство [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]сео агентство[/url] .
agentstvo poiskovogo prodvijeniya_ziKt
2 Nov 25 at 6:10 pm
Отличное качество реги! Советую! https://priv-church.ru/sankt-peterburg.html В итоге-“радостно” ожидал курьера эти дни,забавлянка придет мне позже желаемого… ;(
ThomasronsE
2 Nov 25 at 6:13 pm
trusted online pharmacy UK: cheap medicines online UK – best UK pharmacy websites
HaroldSHems
2 Nov 25 at 6:13 pm
Hey there, You have done a great job. I will definitely digg
it and personally suggest to my friends. I am sure they’ll be benefited
from this site.
부산출장마사지
2 Nov 25 at 6:16 pm
купить диплом в петропавловске-камчатском [url=http://www.rudik-diplom6.ru]купить диплом в петропавловске-камчатском[/url] .
Diplomi_dgKr
2 Nov 25 at 6:17 pm
verified pharmacy coupon sites Australia [url=http://aussiemedshubau.com/#]best Australian pharmacies[/url] best Australian pharmacies
Hermanengam
2 Nov 25 at 6:17 pm
seo продвижение сайта агентство [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru]seo продвижение сайта агентство[/url] .
agentstvo poiskovogo prodvijeniya_ejKt
2 Nov 25 at 6:18 pm
прицеп 5440: Легендарная модель, проверенная временем. Надежность и простота обслуживания. Отличный выбор для опытных водителей.
Richardaquat
2 Nov 25 at 6:18 pm
купить вкладыш к диплому техникума [url=https://frei-diplom10.ru]купить вкладыш к диплому техникума[/url] .
Diplomi_yvEa
2 Nov 25 at 6:18 pm
куплю диплом младшей медсестры [url=https://frei-diplom14.ru]https://frei-diplom14.ru[/url] .
Diplomi_huoi
2 Nov 25 at 6:18 pm
купить диплом в казани [url=https://www.rudik-diplom14.ru]купить диплом в казани[/url] .
Diplomi_ezea
2 Nov 25 at 6:19 pm
Вызвать уничтожение тараканов горячим туманом на дом, кто знает номер?
санитарная обработка
KennethceM
2 Nov 25 at 6:19 pm
Complimenti per il contenuto! È sempre utile leggere approfondimenti sul mondo delle biciclette
cargo. Anche noi di Green Speedy stiamo lavorando a nuove soluzioni modulari
per rendere la mobilità urbana più accessibile ed ecologica.
soluzioni di micromobilità
2 Nov 25 at 6:20 pm
1 xbet [url=https://1xbet-giris-5.com/]https://1xbet-giris-5.com/[/url] .
1xbet giris_xxSa
2 Nov 25 at 6:22 pm
pharmacy discount codes AU [url=http://aussiemedshubau.com/#]online pharmacy australia[/url] best Australian pharmacies
Hermanengam
2 Nov 25 at 6:23 pm
top digital agency [url=http://www.luchshie-digital-agencstva.ru]top digital agency[/url] .
lychshie digital agentstva_smoi
2 Nov 25 at 6:23 pm
продвижение сайта в топ 10 профессионалами [url=http://reiting-kompanii-po-prodvizheniyu-sajtov.ru]http://reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .
agentstvo poiskovogo prodvijeniya_qbKt
2 Nov 25 at 6:25 pm
What we’re covering
[url=https://megaweb-13at.com]megaweb5.com[/url]
• Israel is facing growing condemnation after it attacked Hamas leadership in the capital of Qatar, a US ally and key mediator in Gaza ceasefire talks — putting hostage negotiations at risk.
[url=https://megaweb-16at.com]megaweb 4[/url]
• Hamas said the strike killed five members but failed to assassinate the negotiating delegation, the target of the strikes.
• US President Donald Trump has criticized the strike, saying that by the time his administration learned of the attack and told the Qataris, there was little he could do to stop it.
• The attack is the first publicly acknowledged strike on a Gulf state by Israel. Qatar’s prime minister was visibly angry and said his country’s tradition of diplomacy “won’t be deterred.”
https://mgmarket8.net
mgmarket5 at
JamesBus
2 Nov 25 at 6:27 pm
Однако детская [url=https://www.petlovestudio.com/stomatologicheskaja-klinika-zdorovye-zuby-dlja/]https://www.petlovestudio.com/stomatologicheskaja-klinika-zdorovye-zuby-dlja/[/url] является важным учреждением здравоохранения для малышей. Потерять временную жевательную единицу можно и весьма раньше, к примеру, из-за кариеса, бруксизма, флюороза, травм, воспалительных болезней десен и т.д.
RobertTub
2 Nov 25 at 6:28 pm
This design is spectacular! You obviously know how to
keep a reader amused. Between your wit and
your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job.
I really loved what you had to say, and more than that, how you presented it.
Too cool!
incorporation services
2 Nov 25 at 6:28 pm
1xbetgiri? [url=1xbet-giris-2.com]1xbet-giris-2.com[/url] .
1xbet giris_ykPt
2 Nov 25 at 6:29 pm
1xbet tr [url=http://1xbet-giris-4.com/]1xbet tr[/url] .
1xbet giris_fySa
2 Nov 25 at 6:30 pm
купить диплом техникума в красноярске [url=www.frei-diplom10.ru/]купить диплом техникума в красноярске[/url] .
Diplomi_auEa
2 Nov 25 at 6:31 pm
hey there and thank you for your information – I’ve definitely
picked up anything new from right here. I did however expertise some technical points using this website, since I experienced to
reload the site a lot of times previous to I could get
it to load properly. I had been wondering if your web host is OK?
Not that I am complaining, but sluggish loading instances times will sometimes affect your
placement in google and can damage your high-quality score
if ads and marketing with Adwords. Anyway I am
adding this RSS to my e-mail and can look out for much more of your respective exciting
content. Make sure you update this again soon.
طراحی سایت با وردپرس قیمت
2 Nov 25 at 6:34 pm
UK online pharmacies list: affordable medications UK – UkMedsGuide
Johnnyfuede
2 Nov 25 at 6:36 pm
this link
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
this link
2 Nov 25 at 6:36 pm
“[url=https://peretyazhka-bel.ru/]Перетяжка прямых диванов[/url]”
Перетяжка позволяет вернуть предметам интерьера первоначальную свежесть.
Такой подход не только экономит бюджет, но и позволяет индивидуализировать интерьер. Вы можете выбрать любой цвет и фактуру ткани под стиль комнаты.
—
### **2. Какие материалы лучше использовать?**
Для перетяжки применяют различные ткани, отличающиеся износостойкостью и внешним видом. Микрофибра и жаккард устойчивы к истиранию и подходят для ежедневного использования.
Также важно учитывать наполнитель, который влияет на комфорт. Поролон средней плотности обеспечит мягкость и долговечность.
—
### **3. Этапы профессиональной перетяжки**
Процесс начинается с демонтажа старой обивки и оценки состояния каркаса. Сначала снимают старую обивку, затем осматривают деревянные и металлические элементы.
Далее выбирают материал и производят раскрой. Раскрой выполняется с запасом для удобства последующего натяжения.
—
### **4. Преимущества профессионального подхода**
Обращение к специалистам гарантирует качество и долгий срок службы мебели. Мастера подбирают оптимальные методы перетяжки для разных типов мебели.
Кроме того, экономится время и исключаются ошибки. Только специалист сможет точно воспроизвести первоначальную форму мебели.
—
### **Спин-шаблон:**
#### **1. Почему стоит выбрать перетяжку мебели?**
– Смена ткани помогает сохранить любимый диван или кресло, избежав покупки новой мебели.
– Новая обивка позволяет полностью изменить дизайн старой мебели.
#### **2. Какие материалы лучше использовать?**
– Хлопок и лён подойдут для помещений с невысокой нагрузкой.
– Поролон средней плотности обеспечит мягкость и долговечность.
#### **3. Этапы профессиональной перетяжки**
– Сначала снимают старую обивку, затем осматривают деревянные и металлические элементы.
– Обивочный материал тщательно размечается и вырезается с учётом всех деталей.
#### **4. Преимущества профессионального подхода**
– Мастера подбирают оптимальные методы перетяжки для разных типов мебели.
– Только специалист сможет точно воспроизвести первоначальную форму мебели.
peretyazhk_kvKi
2 Nov 25 at 6:36 pm
продвижение сайта агентство [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]продвижение сайта агентство[/url] .
agentstvo poiskovogo prodvijeniya_hvKt
2 Nov 25 at 6:37 pm