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://t.me/Official_1xbet_1xbet/s/675
AlbertEnark
16 Oct 25 at 7:54 pm
https://t.me/Official_1xbet_1xbet/s/819
AlbertEnark
16 Oct 25 at 7:56 pm
โพสต์นี้ อ่านแล้วได้ความรู้เพิ่ม ครับ
ดิฉัน ไปเจอรายละเอียดของ ข้อมูลเพิ่มเติม
ลองเข้าไปอ่านได้ที่ Rosella
เหมาะกับคนที่กำลังหาข้อมูลในด้านนี้
เพราะให้ข้อมูลเชิงลึก
ขอบคุณที่แชร์ ข้อมูลที่มีประโยชน์ นี้
จะคอยดูว่ามีเนื้อหาใหม่ๆ
มาเสริมอีกหรือไม่
Rosella
16 Oct 25 at 7:56 pm
mostbet login [url=www.mostbet4182.ru]mostbet login[/url]
mostbet_uz_rfkt
16 Oct 25 at 7:58 pm
купить диплом в москве с занесением в реестр [url=http://www.frei-diplom1.ru]купить диплом в москве с занесением в реестр[/url] .
Diplomi_rjOi
16 Oct 25 at 7:59 pm
Интернет вещей — связующее звено эпох кракен onion kraken актуальные ссылки kraken зеркало kraken ссылка зеркало
RichardPep
16 Oct 25 at 8:00 pm
https://t.me/Official_1xbet_1xbet/s/212
AlbertEnark
16 Oct 25 at 8:00 pm
https://t.me/Official_1xbet_1xbet/s/798
AlbertEnark
16 Oct 25 at 8:00 pm
https://plisio.net/th/blog/brian-niccol-net-worth
CameronJaisp
16 Oct 25 at 8:01 pm
Всем привет! Хороший магазин. Удачи и развития в дальнейшем!
https://telegra.ph/Kupit-pricel-opticheskij-dlya-karabina-7h62h54-10-12-4
Верно. Но это уже другой критерий – грамотное описание
Jamessmori
16 Oct 25 at 8:04 pm
Hello would you mind stating which blog platform you’re using?
I’m planning to start my own blog soon but I’m
having a difficult time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design seems different then most blogs and I’m looking for
something unique. P.S My apologies for being off-topic
but I had to ask!
bandar togel
16 Oct 25 at 8:07 pm
OMT’s emphasis on error evaluation transforms mistakes
rigt іnto learning adventures, aiding pupils love
math’ѕ forgiving nature ɑnd objective һigh in tests.
Transform mathematics challenges іnto triumphs ԝith OMT Math Tuition’s
blend οf online and ⲟn-site alternatives, Ƅacked Ьу a performance history of student
excellence.
Αs mathematics forms tһe bedrock of abstract tһougһt and
crucial analytical іn Singapore’ѕ education ѕystem, professional math tuition supplies tһe individualized guidance essential tο turn difficulties іnto triumphs.
primary school math tuition іs vital foг PSLE preparation as it
helps trainees master tһe fundamental concepts ⅼike
fractions and decimals, ᴡhich are gгeatly evaluated іn the exam.
Proviɗed tһe һigh stakes of Օ Levels fօr senior hіgh school development іn Singapore, math tuition tɑkes full advantage оf chances for leading qualities ɑnd wanted placements.
Ultimately, junior college math tuition іs key tߋ securing
tⲟp A Level results, opening up doors to prestigious scholarships ɑnd college opportunities.
The individuality ߋf OMT hinges on іts customized curriculum tһat connects MOE curriculum voids
ѡith auxiliary resources like exclusive worksheets and solutions.
OMT’ѕ ѕystem tracks your improvement with tіmе ѕia, motivating you to aim higher in mathematics grades.
Math tuition develops ɑ strong portfolio of abilities, boosting
Singapore trainees’ resumes fօr scholarships based on examination outcomes.
mү web pagе: math tuition jc
math tuition jc
16 Oct 25 at 8:08 pm
Мы комбинируем медицинские и немедикаментозные решения. Инфузионная терапия — адресная, с контролем безопасности; поведенческие опоры — просты и выполняемы в реальной жизни; телемедицина помогает пройти «трудный час» без лишних поездок и импровизаций. Ниже — ориентиры логики подбора, они не заменяют очный осмотр.
Изучить вопрос глубже – https://narkologicheskaya-klinika-kaliningrad15.ru/kaliningrad-narkologicheskij-dispanser/
Lancewrofe
16 Oct 25 at 8:15 pm
mostbet promokod olish [url=https://mostbet4185.ru/]mostbet promokod olish[/url]
mostbet_uz_fver
16 Oct 25 at 8:16 pm
electlarryarata – The homepage is clean but I expected more content already.
Myrna Mckinny
16 Oct 25 at 8:17 pm
https://t.me/Official_1xbet_1xbet/s/112
AlbertEnark
16 Oct 25 at 8:20 pm
https://t.me/Official_1xbet_1xbet/s/972
AlbertEnark
16 Oct 25 at 8:21 pm
Добрый день!
Бюро переводов документов для нотариального заверения купить легко через наш сервис. Бюро переводов документов для медицинских справок заказать можно срочно. Бюро переводов в москве выполняет переводы всех видов документов. Услуги по нотариальному заверению гарантируют юридическую силу. Переводчик для нотариального перевода делает переводы официальными и точными.
Полная информация по ссылке – https://byuro-perevodov1.ru/
бюро переводов для студентов, переводчик для международных встреч, перевод медицинских документов
бюро переводов для обучения, [url=https://byuro-perevodov1.ru/]бюро переводов с международными переводами[/url], бюро переводов технических текстов
Удачи и хорошего перевода!
Calebmoone
16 Oct 25 at 8:23 pm
натяжные потолки сайт [url=http://www.stretch-ceilings-nizhniy-novgorod-1.ru]натяжные потолки сайт[/url] .
natyajnie potolki nijnii novgorod_ikOn
16 Oct 25 at 8:25 pm
купить диплом об окончании техникума в самаре [url=www.frei-diplom12.ru/]купить диплом об окончании техникума в самаре[/url] .
Diplomi_akPt
16 Oct 25 at 8:25 pm
Добрый день!
Рейтинг компаний по установке VRV и VRF помогает выбрать подрядчика, который не исчезнет после оплаты. В Топ 10 компаний по установке VRV и VRF входят фирмы с официальным статусом, ИНН, ОГРН и реальным офисом. Надёжные компании по установке VRV и VRF работают по договору, предоставляют акты и гарантийные талоны. Компании по продаже и установке VRV и VRF с онлайн-записью и мгновенным расчётом — удобно и прозрачно.
Полная информация по ссылке – https://vrf-montazh.ru/montazh-ventilyatsii/
монтаж вентиляция курган, монтаж вентиляции москва, монтаж канальных кондиционеров
компании по установке кондиционеров, [url=https://vrf-montazh.ru/top-10-kompaniy-po-ustanovke-ventilyatsii-2025/]компании по установке вентиляции и ремонту в Москве[/url], вентиляция предприятия монтаж
Удачи и хорошего климата!
AlbertBex
16 Oct 25 at 8:26 pm
Хотите узнать больше о природе нашей страны? Присоединяйтесь к обсуждению.
Зацепил раздел про Изучение ООПТ России: парки, заповедники, водоемы.
Ссылка ниже:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Природа – наш главный учитель и защитник. Берегите её!
fixRow
16 Oct 25 at 8:26 pm
https://t.me/Official_1xbet_1xbet/s/1526
AlbertEnark
16 Oct 25 at 8:26 pm
Lovesomething says
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
Lovesomething says
16 Oct 25 at 8:26 pm
https://t.me/Official_1xbet_1xbet/s/795
AlbertEnark
16 Oct 25 at 8:26 pm
Thanks for a marvelous posting! I actually enjoyed reading
it, you are a great author.I will make certain to bookmark your blog and will often come back someday.
I want to encourage you to continue your great work, have a nice holiday weekend!
мелстрой казино ссылка
16 Oct 25 at 8:26 pm
stacoa.org – The style and tone give trust and sincerity.
Marquis Debari
16 Oct 25 at 8:28 pm
https://plisio.net/vi/blog/how-to-create-a-high-risk-merchant-account
CameronJaisp
16 Oct 25 at 8:29 pm
thespeakeasybuffalo – Love the welcoming tone in the header, feels warm and inviting.
Kalyn Gotthardt
16 Oct 25 at 8:30 pm
новости киберспорта [url=http://www.novosti-sporta-17.ru]http://www.novosti-sporta-17.ru[/url] .
novosti sporta_taOi
16 Oct 25 at 8:32 pm
laetly.com – Cool brand name, I’m curious about what you sell here.
Richie Liss
16 Oct 25 at 8:34 pm
Register at moree glory casino login and receive bonuses on your first deposit on online casino games and slots right now!
Miguelhen
16 Oct 25 at 8:39 pm
myvetcoach.org – The tone is kind and motivational, exactly what I need.
Elayne Nebgen
16 Oct 25 at 8:41 pm
Анонимность — не опция, а стандарт: документы формулируются нейтрально, чеки не содержат «говорящих» формулировок, фото- и видеосъёмка исключены. При необходимости подписывается расширенное соглашение о конфиденциальности. Доступ к записи визита и параметрам процедуры разграничен по ролям; копии передаются по защищённому каналу и удаляются по регламенту хранения.
Углубиться в тему – [url=https://narkolog-na-dom-petrozavodsk15.ru/]нарколог на дом цены в петрозаводске[/url]
Gordonkab
16 Oct 25 at 8:42 pm
mostbet uz skachat kompyuter [url=https://www.mostbet4182.ru]mostbet uz skachat kompyuter[/url]
mostbet_uz_bmkt
16 Oct 25 at 8:42 pm
norigamihq – Hoping this becomes a valuable resource soon.
Dale Aagaard
16 Oct 25 at 8:43 pm
В этом информативном обзоре собраны самые интересные статистические данные и факты, которые помогут лучше понять текущие тренды. Мы представим вам цифры и графики, которые иллюстрируют, как развиваются различные сферы жизни. Эта информация станет отличной основой для глубокого анализа и принятия обоснованных решений.
Детали по клику – https://www.moksatechnologies.com/category/uncategorized/page/303
CurtisElult
16 Oct 25 at 8:43 pm
click through the up coming internet page
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
click through the up coming internet page
16 Oct 25 at 8:43 pm
купить диплом биолога [url=https://www.rudik-diplom2.ru]купить диплом биолога[/url] .
Diplomi_sxpi
16 Oct 25 at 8:44 pm
https://t.me/Official_1xbet_1xbet/s/454
AlbertEnark
16 Oct 25 at 8:46 pm
I’ve been following the Minotaurus presale closely, and it’s impressive how they’ve structured the tokenomics for long-term sustainability. The vesting bonuses are a smart incentive that could really reward patient holders. Excited to see $MTAUR launch and disrupt the blockchain gaming space.
mtaur token
WilliamPargy
16 Oct 25 at 8:46 pm
https://t.me/Official_1xbet_1xbet/s/183
AlbertEnark
16 Oct 25 at 8:47 pm
https://t.me/Official_1xbet_1xbet/s/826
AlbertEnark
16 Oct 25 at 8:51 pm
https://plisio.net/ru/blog/bitcoin-mining-with-your-smartphone
CameronJaisp
16 Oct 25 at 8:51 pm
https://t.me/Official_1xbet_1xbet/s/922
AlbertEnark
16 Oct 25 at 8:52 pm
Технологии делают жизнь проще kraken зеркало kraken darknet market kraken darknet ссылка сайт kraken darknet
RichardPep
16 Oct 25 at 8:53 pm
linebet registration
linebet affiliate login
16 Oct 25 at 8:54 pm
спорт онлайн [url=www.novosti-sporta-17.ru/]www.novosti-sporta-17.ru/[/url] .
novosti sporta_ugOi
16 Oct 25 at 8:55 pm
I got this web site from my buddy who informed me about this website and at the moment this time I
am browsing this web site and reading very informative articles here.
pocket wifi
16 Oct 25 at 8:56 pm
hecimagine.com – Seems like a bridge between disadvantaged students and HEC Paris.
Hollis Glazner
16 Oct 25 at 8:56 pm