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://xn--krken21-bn4c.com
Howardreomo
19 Sep 25 at 4:20 pm
купить диплом технолога [url=www.rudik-diplom1.ru/]купить диплом технолога[/url] .
Diplomi_iter
19 Sep 25 at 4:21 pm
за1мы онлайн [url=https://zaimy-16.ru]https://zaimy-16.ru[/url] .
zaimi_miMi
19 Sep 25 at 4:25 pm
займ всем [url=zaimy-16.ru]займ всем[/url] .
zaimi_czMi
19 Sep 25 at 4:27 pm
https://clearmedshub.com/# ClearMedsHub
RichardceaNy
19 Sep 25 at 4:27 pm
«ПрофПруд» в Мытищах — магазин «всё для водоема» с акцентом на надежные бренды Германии, Нидерландов, Дании, США и России и собственное производство пластиковых и стеклопластиковых чаш. Здесь подберут пленку ПВХ, бутилкаучук, насосы, фильтры, скиммеры, подсветку, биопрепараты и корм, помогут с проектом и шеф-монтажом. Удобно начать с каталога на https://profprud.ru — есть схема создания пруда, статьи, видео и консультации, гарантия до 10 лет, доставка по РФ и бесплатная по Москве и МО при крупном заказе: так ваш водоем станет тихой гаванью без лишних хлопот.
vivejwenly
19 Sep 25 at 4:29 pm
https://pubhtml5.com/homepage/xchmr
HarryPaync
19 Sep 25 at 4:30 pm
мфо займ [url=https://zaimy-16.ru]мфо займ[/url] .
zaimi_ovMi
19 Sep 25 at 4:30 pm
займы россии [url=http://zaimy-16.ru]займы россии[/url] .
zaimi_wyMi
19 Sep 25 at 4:33 pm
You should be a part of a contest for one of the best blogs on the net.
I most certainly will highly recommend this site!
Net Rowdex
19 Sep 25 at 4:34 pm
kraken зеркало рабочее kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
19 Sep 25 at 4:41 pm
kraken onion зеркала kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
19 Sep 25 at 4:43 pm
микрозайм все [url=zaimy-16.ru]zaimy-16.ru[/url] .
zaimi_clMi
19 Sep 25 at 4:44 pm
Howdy! Quick question that’s totally off topic. Do you know how to make your
site mobile friendly? My site looks weird when viewing from my apple iphone.
I’m trying to find a template or plugin that might
be able to correct this problem. If you have any recommendations, please share.
With thanks!
dewascatter slot
19 Sep 25 at 4:45 pm
микрозаймы онлайн [url=http://zaimy-16.ru]микрозаймы онлайн[/url] .
zaimi_qcMi
19 Sep 25 at 4:46 pm
I am curious to find out what blog system you’re working with?
I’m experiencing some small security problems with my latest site and I would like to find something more safeguarded.
Do you have any recommendations?
چگونه لارنژیت را درمان کنیم
19 Sep 25 at 4:46 pm
It’s awesome to pay a visit this web site and reading the views of all mates about this article, while I
am also keen of getting know-how.
درمان برونشیت در کودکان
19 Sep 25 at 4:47 pm
I was recommended this web site by my cousin. I am not
sure whether this post is written by him as no one else
know such detailed about my problem. You are amazing! Thanks!
is roblox fps unlocker safe
19 Sep 25 at 4:49 pm
https://vitaledgepharma.com/# VitalEdgePharma
RichardceaNy
19 Sep 25 at 4:49 pm
займы всем [url=www.zaimy-16.ru]займы всем[/url] .
zaimi_ihMi
19 Sep 25 at 4:49 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
blsp at
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 4:50 pm
Hello it’s me, I am also visiting this site daily, this website is actually pleasant and the
people are really sharing fastidious thoughts.
آمبولانس خصوصی سمنان
19 Sep 25 at 4:51 pm
все займы рф [url=zaimy-16.ru]zaimy-16.ru[/url] .
zaimi_jqMi
19 Sep 25 at 4:51 pm
bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года
bs2web at
bs2best.at blacksprut marketplace Official
CharlesNarry
19 Sep 25 at 4:51 pm
официальные займы онлайн на карту бесплатно [url=http://zaimy-16.ru]http://zaimy-16.ru[/url] .
zaimi_cdMi
19 Sep 25 at 4:51 pm
Fine way of telling, and good piece of writing to take facts on the topic of my presentation subject, which i am going to deliver in institution of higher education.
چگونه سئو کار شویم
19 Sep 25 at 4:54 pm
https://muckrack.com/person-27905116
HarryPaync
19 Sep 25 at 4:54 pm
все микрозаймы на карту [url=http://zaimy-16.ru]http://zaimy-16.ru[/url] .
zaimi_dqMi
19 Sep 25 at 4:55 pm
buy xtc prague cocain in prague from peru
prague-drugs-452
19 Sep 25 at 4:56 pm
Wow, maths serves аs tһe groundwork pillar of primary education, aiding
kids ѡith dimensional analysis f᧐r architecture careers.
Aiyo, lacking strong math аt Junior College, еѵen toр school kids сould struggle
аt hiցh school equations, ѕo cultivate tһis immediatelу leh.
Hwa Chong Institution Junior College іѕ renowned fօr its integrated program tһat effortlessly
combines academic rigor ᴡith character development,
producing worldwide scholars аnd leaders. Ꮃorld-class facilities
аnd professional professors assistance excellence іn researⅽh,
entrepreneurship, аnd bilingualism. Trainees benefit fгom
substantial worldwide exchanges and competitions, broadening viewpoints аnd refining skills.
The organization’s concentrate on innovation and service cultivates strength ɑnd ethical values.
Alumni networks ߋpen doors tߋ top universities ɑnd prominent professions worldwide.
Tampines Meridian Junior College, born fгom the dynamic merger of Tampines Junior College
ɑnd Meridian Junior College, ⲣrovides an ingenious and culturally rich
education highlighted Ƅy specialized electives іn drama and Malay language, supporting meaningful ɑnd multilingual
skills іn a forward-thinking neighborhood. Ꭲһe college’s cutting-edge facilities, encompassing
theater аreas, commerce simulation laboratories, аnd science innovation
centers, assistance varied academic streams tһat encourage interdisciplinary expedition аnd practical skill-building aсross arts, sciences, and service.
Talent advancement programs, combined ԝith overseas immersion journeys аnd cultural
celebrations, foster strong management qualities, cultural awareness, аnd flexibility to international dynamics.
Ԝithin a caring and compassionate campus culture, students participate іn wellness efforts,
peer support ցroups, and co-curricular clubѕ tһat prdomote strength,
emotional intelligence, аnd collaborative spirit.
Ꭺs a outcome, Tampines Meridian Junior College’ѕ trainees
achieve holistic growth аnd are well-prepared tо tackle
worldwide challenges, ƅecoming confident, versatile people ɑll set fοr
university success ɑnd beyond.
Wah lao, no matter thouցh establishment proves atas,
mathematics acts ⅼike tһе mɑke-oг-break topic in developing poise wiyh figures.
Aiyah, primary mathematics instructs practical implementations ⅼike money management, thus guarantee yoᥙr kid masters it riցht starting young
age.
Aiyo, minus robust maths in Junior College, no matter leading institution kids mіght struggle
in next-level algebra, tһus cultivate that іmmediately leh.
Օh dear, lacking strong maths ԁuring Junior College, еven leading
school children cⲟuld falter at hugh school algebra,
tһus cultivate that now leh.
Good grades іn A-levels mean lesѕ debt frߋm loans іf you ɡet merit-based aid.
Αpart from school amenities, concentrate оn maths
fօr avoіd common pitfalls such aѕ careless
miistakes in assessments.
Feel free tο surf tօ my blog post :: Jurong Pioneer Junior College
Jurong Pioneer Junior College
19 Sep 25 at 4:56 pm
займы онлайн [url=www.zaimy-16.ru/]займы онлайн[/url] .
zaimi_lrMi
19 Sep 25 at 4:57 pm
I’m not sure where you are getting your info, but good topic.
I needs to spend some time learning more or understanding more.
Thanks for wonderful info I was looking for this info for my mission.
Feel free to surf to my webpage taking minutes in zoom meeting
taking minutes in zoom meeting
19 Sep 25 at 4:59 pm
kraken darknet kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
19 Sep 25 at 5:01 pm
Heya i’m for the first time here. I came across this board and I find
It really useful & it helped me out a lot. I hope to give something back and
aid others like you aided me.
آمبولانس خصوصی تهران
19 Sep 25 at 5:02 pm
микрозайм всем [url=zaimy-16.ru]zaimy-16.ru[/url] .
zaimi_mkMi
19 Sep 25 at 5:02 pm
Потрібні лише перевірені київські новини без інформаційного шуму? На «В місті Київ» ви знайдете головне про транспорт, бізнес, культуру, здоров’я та афішу. Ми подаємо коротко, по суті та з посиланнями на першоджерела. Оновлення виходять оперативно, а зручна навігація допомагає швидко знайти потрібне. Деталі на https://vmisti.kyiv.ua/ Приєднуйтесь до спільноти уважних читачів і дізнавайтеся про міські зміни першими. Підписуйтеся і розкажіть про нас друзям!
CyrylewKek
19 Sep 25 at 5:04 pm
I’d like to find out more? I’d want to find out more details.
beste online casino schweiz
19 Sep 25 at 5:05 pm
купить диплом о среднем образовании в реестр [url=www.frei-diplom6.ru/]купить диплом о среднем образовании в реестр[/url] .
Diplomi_vbOl
19 Sep 25 at 5:06 pm
купить диплом о среднем специальном образовании с занесением в реестр [url=frei-diplom3.ru]купить диплом о среднем специальном образовании с занесением в реестр[/url] .
Diplomi_jeKt
19 Sep 25 at 5:06 pm
как купить диплом о высшем образовании с занесением в реестр отзывы [url=www.frei-diplom5.ru/]как купить диплом о высшем образовании с занесением в реестр отзывы[/url] .
Diplomi_isPa
19 Sep 25 at 5:07 pm
все займы онлайн на карту [url=http://www.zaimy-16.ru]все займы онлайн на карту[/url] .
zaimi_viMi
19 Sep 25 at 5:07 pm
I have been surfing online more than 4 hours today, yet I never found any interesting
article like yours. It is pretty worth enough for me.
In my opinion, if all web owners and bloggers made good content as
you did, the web will be a lot more useful than ever before.
برونشیت ریه خطرناک است
19 Sep 25 at 5:10 pm
список займов онлайн на карту [url=zaimy-16.ru]zaimy-16.ru[/url] .
zaimi_xqMi
19 Sep 25 at 5:11 pm
Hi, I do believe this is a great site. I stumbledupon it 😉
I am going to return once again since i have book-marked it.
Money and freedom is the best way to change, may you be
rich and continue to help other people.
سئو سایت در اراک
19 Sep 25 at 5:14 pm
VitalEdgePharma [url=https://vitaledgepharma.shop/#]VitalEdge Pharma[/url] VitalEdge Pharma
Michealstilm
19 Sep 25 at 5:14 pm
все онлайн займы [url=www.zaimy-16.ru]все онлайн займы[/url] .
zaimi_ojMi
19 Sep 25 at 5:15 pm
Hey there! This is my first visit to your blog! We are a collection of volunteers and starting a new project in a community in the same niche.
Your blog provided us beneficial information to work on. You have done a
wonderful job!
India Shine Technologies
19 Sep 25 at 5:16 pm
все микрозаймы на карту [url=https://zaimy-16.ru/]https://zaimy-16.ru/[/url] .
zaimi_fpMi
19 Sep 25 at 5:16 pm
Ищете все самые свежие новости? Посетите сайт https://scanos.news/ и вы найдете последние новости и свежие события сегодня из самых авторитетных источников на ленте агрегатора. Вы можете читать события в мире, в России, новости экономики, спорта, науки и многое другое. Свежая лента новостей всегда для вас!
viqimrSem
19 Sep 25 at 5:17 pm
взо [url=http://www.zaimy-16.ru]взо[/url] .
zaimi_fnMi
19 Sep 25 at 5:17 pm