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/s/uD_1XBET
MichaelPione
1 Nov 25 at 8:50 pm
Ledger Wallet protects Bitcoin and altcoins from theft. Ledger Live offers convenient tools for transfers, balance monitoring, and secure staking.
ledger download for IOS
ledge-my-live.to
Tomnab
1 Nov 25 at 8:51 pm
Listen ᥙp, Singapore moms and dads, math іs likely the most
important primary discipline, fostering creativity tһrough
рroblem-solving to innovative careers.
Տt. Joseph’s Institution Junior College embodies Lasallian customs,
highlighting faith, service, ɑnd intellectual pursuit.
Integrated programs սse smooth development ѡith focus on bilingualism and innovation. Facilities ⅼike
carrying out arts centers enhance creative expression. Global immersions ɑnd гesearch study chances
widen perspectives. Graduates ɑгe thoughtful achievers,
excelling іn universities аnd careers.
Eunoia Junior College embodies tһe pinnacle ⲟf modern academic
development, housed іn a striking hіgh-rise campus that flawlessly integrates communal knowing аreas, green locations, аnd advanced technological centers tߋ develop an inspiring atmosphere fоr collective and experiential education. Ꭲhe college’ѕ unique viewpoint of
“beautiful thinking” motivates students tо mix intellectual curiosity
ѡith compassion ɑnd ethical reasoning, supported ƅy
vibrant academic programs in tһе arts, sciences, ɑnd interdisciplinary
гesearch studies that promote imaginative analytical ɑnd forward-thinking.
Equipped ѡith t᧐p-tier centers ѕuch aѕ professional-grade carrying օut arts theaters, multimedia studios, ɑnd interactive science laboratories,
trainees аre empowered to pursue theіr passions ɑnd develop exceptional
talents іn a holistic manner. Τhrough strategic collaborations ᴡith leading universities
аnd industry leaders, tһe college uses enhancing chances for
undergraduate-level гesearch study, internships, аnd
mentorship tһаt bridge classroom knowing ᴡith real-ѡorld applications.
Αs a result, Eunoia Junior College’ѕ trainees evolve іnto thoughtful, durable leaders ѡho аre not just
academically accomplished һowever also deeply committed tο contributing positively t᧐ a diverse and
еvеr-evolving international society.
Ɗo not taкe lightly lah, pair ɑ gooⅾ Junior College witһ maths excellence in ᧐rder to guarantee high A
Levels marks аnd effortless ϲhanges.
Parents, worry abօut the difference hor, math base proves essential іn Junior College tߋ grasping data,
vital ѡithin current online ѕystem.
Beѕides fгom school facilities, concentrate оn mathematics
tօ avoiⅾ typical mistakes including inattentive blunders Ԁuring tests.
Alas, withоut solid mathematics in Junior College, no matter prestigios establishment youngsters mɑy
stumble at high school algebra, tһerefore build tһat now leh.
Math equips yоu foг statistical analysis іn social sciences.
Aiyo, mіnus solid maths ɑt Junior College, rеgardless top institution children mіght struggle in secondary
equations, thus build that рromptly leh.
Feel free tοo visit my web-site: best secondary school math tuition
best secondary school math tuition
1 Nov 25 at 8:52 pm
discount pharmacies in Ireland: affordable medication Ireland – trusted online pharmacy Ireland
HaroldSHems
1 Nov 25 at 8:52 pm
Appreciation to my father who informed me concerning this weblog,
this website is in fact amazing.
inatogel
1 Nov 25 at 8:53 pm
https://crown303.net/promokod-melbet-na-segodnya-2025/
JustinAcecy
1 Nov 25 at 8:55 pm
мостбет официальный сайт регистрация [url=https://mostbet12034.ru/]мостбет официальный сайт регистрация[/url]
mostbet_kg_idPr
1 Nov 25 at 8:55 pm
perfectbuyzone – The layout is well done and the offers stand out, nice work overall.
Wendell Weasel
1 Nov 25 at 8:56 pm
После обработка от тараканов стоимость дом безопасный для детей.
дезинфекция медицинских учреждений
Wernermog
1 Nov 25 at 8:56 pm
https://rollbol.com/blogs/2006617/1xBet-New-Promo-Code-130-Welcome-Offer
https://rollbol.com/blogs/2006617/1xBet-New-Promo-Code-130-Welcome-Offer
1 Nov 25 at 8:58 pm
best Irish pharmacy websites
Edmundexpon
1 Nov 25 at 8:59 pm
trusted online pharmacy Ireland
Edmundexpon
1 Nov 25 at 9:00 pm
compare online pharmacy prices: Safe Meds Guide – buy medications online safely
HaroldSHems
1 Nov 25 at 9:01 pm
mostbet скачать на телефон [url=www.mostbet12034.ru]mostbet скачать на телефон[/url]
mostbet_kg_wbPr
1 Nov 25 at 9:02 pm
https://t.me/s/uD_MOSTBEt
MichaelPione
1 Nov 25 at 9:03 pm
https://daddycow.com/blogs/view/66223
Williamspity
1 Nov 25 at 9:09 pm
I feel that is one of the such a lot important information for me.
And i am glad studying your article. However want to remark on few normal issues, The web site taste is ideal, the articles is truly excellent :
D. Good activity, cheers
Diệt Chủng
1 Nov 25 at 9:10 pm
best Australian pharmacies: verified pharmacy coupon sites Australia – verified online chemists in Australia
Johnnyfuede
1 Nov 25 at 9:12 pm
топ seo компаний [url=reiting-seo-agentstv.ru]reiting-seo-agentstv.ru[/url] .
reiting seo agentstv_cmsa
1 Nov 25 at 9:13 pm
Клиника «ЧСП№1» в Ростове-на-Дону предлагает услуги по выводу из запоя. Вы можете выбрать удобный для вас вариант: выезд нарколога на дом или лечение в стационаре. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-rostov18.ru/]вывод из запоя круглосуточно в ростове-на-дону[/url]
Berryjew
1 Nov 25 at 9:14 pm
В Ростове-на-Дону клиника «ЧСП№1» предоставляет услуги по выводу из запоя. Вы можете заказать выезд нарколога на дом или пройти лечение в стационаре. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Детальнее – [url=https://vyvod-iz-zapoya-rostov28.ru/]скорая вывод из запоя в ростове-на-дону[/url]
DannyJosse
1 Nov 25 at 9:15 pm
https://xn--j1adp.xn--80aejmgchrc3b6cf4gsa.xn--p1ai/ Точка включения
MathewLit
1 Nov 25 at 9:15 pm
Чтобы вывести из запоя без поездки в клинику, закажите вызов нарколога на дом в Екатеринбурге. Помощь оказывает центр «Детокс».
Узнать больше – [url=https://narkolog-na-dom-ekaterinburg11.ru/]вывод из запоя недорого в екатеринбурге[/url]
DavidHic
1 Nov 25 at 9:16 pm
It’s perfect time to make a few plans for the future and it’s time to
be happy. I have learn this publish and if I could I desire to suggest you few fascinating things or suggestions.
Perhaps you can write subsequent articles relating to this article.
I want to learn more issues about it!
link mpo slot
1 Nov 25 at 9:16 pm
trusted online pharmacy Ireland [url=http://irishpharmafinder.com/#]Irish Pharma Finder[/url] top-rated pharmacies in Ireland
Hermanengam
1 Nov 25 at 9:18 pm
Hello, i think that i saw you visited my weblog thus i came to “return the favor”.I am attempting to find things to
enhance my web site!I suppose its ok to use a few of your ideas!!
سئو سایت آژانس هواپیمایی
1 Nov 25 at 9:19 pm
The following harmful reactions were reported ( figure Mesa 4).
Tadalafil is a generic wine prescription medicine do drugs victimized for cavernous disfunction (ED) and benignant
prostate hyperplasia (BPH).
Feel free to surf to my web site :: Buy Effexor online
Buy Effexor online
1 Nov 25 at 9:20 pm
trusted online pharmacy Ireland
Edmundexpon
1 Nov 25 at 9:23 pm
купить диплом в краснодаре [url=https://www.rudik-diplom13.ru]купить диплом в краснодаре[/url] .
Diplomi_ufon
1 Nov 25 at 9:25 pm
https://www.elrincondynamics.es/home/liberamos-una-capsula-formativa-gratuita-los-viernes
Rickeykek
1 Nov 25 at 9:26 pm
Hi there, I wish for to subscribe for this webpage to get latest updates, so where can i do it please help.
https://ecuiculturarte.com/index.php/2025/10/19/melbet-oficial-2025-obzor/
Dichaelwaw
1 Nov 25 at 9:27 pm
Доброго!
Сварочные электроды обеспечивают стабильный процесс сварки. Электроды для сварки подходят для профессионалов и новичков. Какие электроды для сварки лучше для работы с углеродистой сталью. Самые хорошие электроды для сварки гарантируют долговечность соединений. Как выбрать электроды для сварки поможет избежать ошибок при работе.
Полная информация по ссылке – https://telegra.ph/Kakie-ehlektrody-dlya-svarki-samye-horoshie-prakticheskij-gid-dlya-stroitelej-v-Rossii-10-29
электроды для сварки, [url=https://telegra.ph/Gde-mozhno-kupit-metizy-dlya-strojki-Obzor-optovyh-postavshchikov-10-29]самые лучшие компании по продаже крепежа[/url], где купить крепеж
Удачи!
HoseaTal
1 Nov 25 at 9:29 pm
Кто-нить брал тут 307 ?? просто ппц какой-то. уже 2 гр выкинул. Делал и 1к10 и чистым курил, ваще НОЛЬ. Как такое можт быть ? https://alvian-energo.ru Сработали быстро, посылка пришла за 4 дня, спрятано эффектно
CharlesSpall
1 Nov 25 at 9:32 pm
https://safemedsguide.com/# best pharmacy sites with discounts
Haroldovaph
1 Nov 25 at 9:32 pm
Je suis epate par Ruby Slots Casino, ca invite a l’aventure. La selection de jeux est impressionnante, offrant des sessions live palpitantes. Avec des depots fluides. Le service client est de qualite. Les paiements sont surs et fluides, par contre des offres plus genereuses seraient top. En bref, Ruby Slots Casino offre une aventure inoubliable. En plus la navigation est fluide et facile, ce qui rend chaque partie plus fun. A mettre en avant le programme VIP avec des privileges speciaux, cree une communaute vibrante.
DГ©couvrir|
urbanforceix3zef
1 Nov 25 at 9:33 pm
I’ll immediately seize your rss feed as I can’t in finding your e-mail subscription hyperlink or e-newsletter service.
Do you have any? Please allow me understand so that I may
subscribe. Thanks.
Also visit my page автосервис kia
автосервис kia
1 Nov 25 at 9:34 pm
mostbet kg [url=https://www.mostbet12033.ru]mostbet kg[/url]
mostbet_kg_jkpa
1 Nov 25 at 9:34 pm
findsomethingamazing – Always find something new and awesome whenever I visit this site.
Gregorio Landstrom
1 Nov 25 at 9:36 pm
Цены на обработка от клещей разумные, качество на высоте.
дератизация подвалов
Wernermog
1 Nov 25 at 9:37 pm
mostbet skachat [url=https://mostbet12034.ru/]mostbet skachat[/url]
mostbet_kg_afPr
1 Nov 25 at 9:39 pm
купить диплом маркетолога [url=rudik-diplom12.ru]купить диплом маркетолога[/url] .
Diplomi_vjPi
1 Nov 25 at 9:41 pm
мостбет com [url=https://www.mostbet12033.ru]https://www.mostbet12033.ru[/url]
mostbet_kg_gupa
1 Nov 25 at 9:46 pm
บทความนี้เกี่ยวกับพวงหรีดดอกไม้ มีสาระมาก
การรู้ว่าดอกไม้แต่ละชนิดมีความหมายอย่างไร ช่วยให้เลือกได้ตรงความรู้สึกมากขึ้น
จะบอกต่อให้เพื่อนๆ ที่ต้องการเลือกดอกไม้ไปงานศพอ่านด้วย
Look into my web blog … ตกแต่งงานศพ
ตกแต่งงานศพ
1 Nov 25 at 9:47 pm
discount pharmacies in Ireland: top-rated pharmacies in Ireland – online pharmacy ireland
HaroldSHems
1 Nov 25 at 9:48 pm
promo codes for online drugstores: promo codes for online drugstores – SafeMedsGuide
Johnnyfuede
1 Nov 25 at 9:48 pm
affordable medication Ireland: trusted online pharmacy Ireland – trusted online pharmacy Ireland
Johnnyfuede
1 Nov 25 at 9:49 pm
happyhomefinds – Great selection and the site loads smoothly—nice home-inspiration hub.
Bryant Chevalier
1 Nov 25 at 9:51 pm
บทความนี้เกี่ยวกับการจัดดอกไม้งานศพ มีสาระมาก
กำลังค้นหาข้อมูลเรื่องนี้อยู่พอดี ถือว่าเจอบทความดีๆ เลย
จะบอกต่อให้เพื่อนๆ ที่ต้องการเลือกดอกไม้ไปงานศพอ่านด้วย
My homepae ดอกไม้งานศพ ราคา
ดอกไม้งานศพ ราคา
1 Nov 25 at 9:52 pm
Saya sudah lama mencoba bermain di KUBET dan pengalaman yang saya dapatkan benar-benar memuaskan.
Sebagai Situs Judi Bola Terlengkap, KUBET
memberikan banyak pilihan pertandingan dan jenis taruhan yang bisa dimainkan setiap hari.
Proses kubet login sangat mudah sehingga saya bisa langsung menikmati semua permainan tanpa
kendala.
Yang paling saya suka dari situs ini adalah fitur Situs Parlay Resmi dan Situs Parlay Gacor
yang selalu stabil.
Di Situs Mix Parlay, saya bisa membuat kombinasi taruhan sesuai strategi sendiri
dan merasakan sensasi menantang di setiap putaran.
Selain itu, toto macau juga menjadi pilihan menarik karena hasil cukup besar dan sistemnya sangat transparan.
Menurut saya, situs parlay ini bukan hanya tempat untuk
bermain, tapi juga sarana hiburan yang seru.
Bagi siapa pun yang sedang mencari Situs Judi Bola dengan sistem terbaik dan peluang
menang tinggi, KUBET adalah pilihan yang tepat.
Situs ini benar-benar layak disebut sebagai Situs Judi Bola Terlengkap
karena semua fitur dan keunggulannya membuat saya betah bermain setiap hari.
homepage
1 Nov 25 at 9:53 pm
4M Dental Implant Center
3918 ᒪong Beach Blvd #200, Lοng Beach,
CA 90807, United Stateѕ
15622422075
best dental care (instapaper.com)
instapaper.com
1 Nov 25 at 9:54 pm