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=http://narkologicheskaya-klinika-28.ru/]http://narkologicheskaya-klinika-28.ru/[/url] .
narkologicheskaya klinika_zpMa
27 Oct 25 at 11:01 pm
можно ли купить диплом медсестры [url=frei-diplom13.ru]можно ли купить диплом медсестры[/url] .
Diplomi_jzkt
27 Oct 25 at 11:02 pm
Parents, steady lah, excellent school alongside strong mathematics foundation signifies yߋur kid
cann handle ratios as ᴡell aѕ spatial concepts with assurance, guiding
in improved ɡeneral educational performance.
Jurong Pioneer Junior College, formed fгom а
tactical merger, ρrovides a forward-thinking education tһat highlights
China readiness ɑnd international engagement. Modern schools provide outstanding resources fߋr commerce,
sciences, and arts, fostering practical skills ɑnd creativity.
Students tɑke pleasure in enriching programs ⅼike international collaborations ɑnd
character-building efforts. Тһe college’ѕ supportive neighborhood promotes strength ɑnd management tһrough diverse c᧐-curricular activities.
Graduates arе ԝell-equipped fߋr dynamic professions, embodying care ɑnd constant improvement.
Singapore Sports School masterfully stabilizes fіrst-rate
athletic training with a extensive academic curriculum,
devoted tⲟ supporting elite professional athletes who
stand oᥙt not onlʏ іn sports һowever likewiѕе іn individual and professional life domains.
Ƭhe school’ѕ customized academic pathways offer versatile
scheduling tօ accommodate intensive training аnd competitions,
mɑking surе students maintain high scholastic requirements whіle pursuing
their sporting enthusiasms ԝith undeviating focus. Boasting tօp-tier centers ⅼike Olympic-standard training arenas, sports science laboratories,
ɑnd healing centers, tоgether ԝith professional training
fгom renowned experts, tһе instittution supports peak physical efficiency ɑnd holistic
professional athlete development. International exposures tһrough worldwide
competitions, exchange programs ѡith overseas sports academies, аnd leadership workshops build
durability, strategic thinking, ɑnd extensive networks tһat extend beyond
the playing field. Students graduate ɑѕ disciplined, goal-oriented leaders, ԝell-prepared for professions іn expert sports,
sports management, оr һigher education, highlighting Singapore Sports School’ѕ extraordinary function іn promoting champions of character and accomplishment.
Folks, kiasu style on lah, robust primary maths гesults iin improved science understanding ⲣlus construction dreams.
Οh, mathematics serves aѕ the foundation stone іn primary
schooling, assisting children іn spatial analysis fօr design careers.
Listen սp, Singapore folks, math proves prօbably the extremely important primary discipline, fostering
imagination іn issue-resolving tо groundbreaking jobs.
Ⲟh dear, minuѕ strong maths at Junior College,
no matter t᧐ⲣ school kids сould stumble аt higһ school calculations,
tһus cultivate that promptly leh.
A-level distinctions іn Math signal potential tߋ
recruiters.
Listen սρ, Singapore parents, mathematics іs ⅼikely the extremely іmportant primary
subject, encouraging creativity fоr ρroblem-solving fοr creative professions.
Аlso visit my website – Broadrick Secondary School
Broadrick Secondary School
27 Oct 25 at 11:02 pm
психолог нарколог [url=www.narkologicheskaya-klinika-27.ru]психолог нарколог[/url] .
narkologicheskaya klinika_qzpl
27 Oct 25 at 11:02 pm
kontol
kontol I will right away clutch your rss feed as
I can not to find your email subscription link or e-newsletter
service. Do you have any? Kindly let me understand so that I
may just subscribe. Thanks.
anjing
27 Oct 25 at 11:03 pm
купить диплом в буденновске [url=rudik-diplom12.ru]rudik-diplom12.ru[/url] .
Diplomi_trPi
27 Oct 25 at 11:03 pm
Hi there, You’ve done a great job. I will certainly digg it and personally suggest to my
friends. I am sure they will be benefited from this website.
خدمات طراحی سایت کافه
27 Oct 25 at 11:05 pm
кракен клиент
kraken client
Henryamerb
27 Oct 25 at 11:06 pm
oldschoolopen – Found exactly what I needed, instructions were clear and concise.
Michal Tollerud
27 Oct 25 at 11:07 pm
легально купить диплом о высшем образовании [url=http://frei-diplom2.ru/]легально купить диплом о высшем образовании[/url] .
Diplomi_lzEa
27 Oct 25 at 11:09 pm
клиника наркологическая москва [url=http://www.narkologicheskaya-klinika-28.ru]http://www.narkologicheskaya-klinika-28.ru[/url] .
narkologicheskaya klinika_ilMa
27 Oct 25 at 11:10 pm
Автоматические выключатели
JulioGer
27 Oct 25 at 11:10 pm
SC88 – siêu nền tảng cá cược trực tuyến hàng
đầu thuộc hệ thống OKVIP, nơi hội tụ hơn 1000+
trò chơi đỉnh cao như bắn cá, nổ hũ, thể thao, casino, xổ số và nhiều sảnh cược độc quyền khác.
Với đội ngũ CSKH chuyên nghiệp trực tuyến 24/7,
SC88.COM cam kết mang đến trải nghiệm mượt mà, minh
bạch và tràn đầy ưu đãi. Đặc biệt, thành viên đăng ký mới nhận ngay 888K thưởng
chào mừng – khởi đầu may mắn, nhân đôi cơ
hội chiến thắng! https://sc88.day/
sc88
27 Oct 25 at 11:11 pm
https://t.me/s/bs_1Win/741
Georgerah
27 Oct 25 at 11:11 pm
Расташоп
Расташоп
27 Oct 25 at 11:12 pm
купить смс номер
MiguelActic
27 Oct 25 at 11:12 pm
letter4reform – Thought-provoking discussions that inspire action towards meaningful change.
Ashley Riquelme
27 Oct 25 at 11:12 pm
kraken вход
кракен официальный сайт
Henryamerb
27 Oct 25 at 11:12 pm
csiingenieros.com – Content reads clearly, helpful examples made concepts easy to grasp.
Debra Shaddix
27 Oct 25 at 11:13 pm
\занимаюсь тестированием вместе с кролями в течении нескольких дней. Все никак не мог понять. https://foxst.ru через в/в непробывал такое не люблю,
JasonBoomi
27 Oct 25 at 11:13 pm
zz-meta – Found some great resources here, really helpful for beginners.
Laurence Gunthrop
27 Oct 25 at 11:13 pm
купить медицинский диплом медсестры [url=http://frei-diplom13.ru/]купить медицинский диплом медсестры[/url] .
Diplomi_kfkt
27 Oct 25 at 11:13 pm
центр наркологической помощи [url=narkologicheskaya-klinika-25.ru]центр наркологической помощи[/url] .
narkologicheskaya klinika_yhPl
27 Oct 25 at 11:14 pm
https://t.me/s/bs_1Win/698
Georgerah
27 Oct 25 at 11:14 pm
lotsofonlinepeople – The design is modern, making navigation a breeze throughout.
Avery Larrivee
27 Oct 25 at 11:15 pm
Thanks a lot for sharing this with all of us you actually
realize what you are speaking about! Bookmarked.
Kindly additionally discuss with my website =). We will have a hyperlink exchange agreement among us
insights
27 Oct 25 at 11:15 pm
Мы дозировано упоминаем географию — важнее не слово «Нижний Новгород», а предсказуемость процесса. Пациент получает «вечерний протокол» — краткие инструкции на ближайшие 12 часов: как пить воду малыми порциями, как приглушить свет, какое «окно тишины» соблюсти перед сном, когда связаться с дежурным врачом и какие маркеры фиксировать в «дневнике симптомов» (шкалы тремора, тревоги, тошноты по 0–10; время засыпания; число пробуждений).
Получить дополнительную информацию – https://narkologicheskaya-klinika-v-nizhnem-novgorode16.ru/narkologiya-nizhnij-novgorod-besplatno/
Prestonned
27 Oct 25 at 11:16 pm
купить аттестат за 11 класс [url=www.rudik-diplom9.ru]купить аттестат за 11 класс[/url] .
Diplomi_wvei
27 Oct 25 at 11:16 pm
chopchopgrubshop – Always a pleasure to visit, never disappointed with the meals.
Sherika Alperin
27 Oct 25 at 11:17 pm
What’s up Dear, are you in fact visiting this website daily,
if so then you will without doubt take fastidious
know-how.
AYUTOGEL
27 Oct 25 at 11:17 pm
Heya i’m for the first time here. I came across this board and I find It truly useful & it helped me out much.
I hope to give something back and aid others like you helped me.
Here is my homepage zinnat02
zinnat02
27 Oct 25 at 11:17 pm
I’m really enjoying the design and layout of your
blog. It’s a very easy on the eyes which makes it much more pleasant for
me to come here and visit more often. Did you hire out a developer to create your theme?
Fantastic work!
Website mua bán vũ khí
27 Oct 25 at 11:18 pm
Ich bin vollig uberzeugt von Cat Spins Casino, es begeistert mit Dynamik. Das Spieleportfolio ist unglaublich breit, mit Live-Sportwetten. 100 % bis zu 500 € mit Freispielen. Der Service ist immer zuverlassig. Auszahlungen sind blitzschnell, allerdings gro?ere Angebote waren super. In Summe, Cat Spins Casino ist perfekt fur Casino-Liebhaber. Au?erdem die Navigation ist einfach und klar, jeden Augenblick spannender macht. Ein attraktives Extra die zahlreichen Sportwetten-Moglichkeiten, die die Gemeinschaft starken.
Mehr wissen|
Nightbearar3zef
27 Oct 25 at 11:18 pm
гидроизоляция подвала изнутри цена м2 [url=http://www.gidroizolyaciya-podvala-cena.ru]http://www.gidroizolyaciya-podvala-cena.ru[/url] .
gidroizolyaciya podvala cena_hnKt
27 Oct 25 at 11:18 pm
Link exchange is nothing else except it is just placing the
other person’s weblog link on your page at suitable place and other person will also do similar in favor of you.
Thanks
27 Oct 25 at 11:18 pm
купить диплом о среднем специальном [url=rudik-diplom1.ru]купить диплом о среднем специальном[/url] .
Diplomi_qaer
27 Oct 25 at 11:18 pm
J’ai une passion debordante pour Sugar Casino, c’est une plateforme qui deborde de dynamisme. Le choix de jeux est tout simplement enorme, comprenant des jeux crypto-friendly. Il booste votre aventure des le depart. Le service client est de qualite. Les gains arrivent sans delai, parfois plus de promotions frequentes boosteraient l’experience. Au final, Sugar Casino offre une experience hors du commun. En plus le site est rapide et engageant, facilite une immersion totale. Un plus les options variees pour les paris sportifs, garantit des paiements rapides.
Lire les dГ©tails|
skyfireos5zef
27 Oct 25 at 11:19 pm
https://blogs.lanacion.com.ar/data/datos-abiertos/iodc15-carla-bonina-y-datos-abiertos-en-latinoamerica/
https://blogs.lanacion.com.ar/data/datos-abiertos/iodc15-carla-bonina-y-datos-abiertos-en-latinoamerica/
27 Oct 25 at 11:19 pm
кракен vk3
kraken сайт
Henryamerb
27 Oct 25 at 11:21 pm
кракен маркетплейс
kraken onion
Henryamerb
27 Oct 25 at 11:22 pm
С первого звонка администратор бережно собирает фактуру: сколько длится эпизод, что человек уже принимал за последние двое суток, как прошла ночь, есть ли помощник на вечер и ночь, какие хронические заболевания и аллергии известны. Дежурный врач оценивает риски и предлагает старт: анонимный визит на дом по Клину или немедленную госпитализацию. На месте проводится очная оценка и допуск к терапии, запускается инфузионная поддержка с мониторингом давления, пульса и сатурации, корректируется вода и электролиты, по показаниям — осторожная нормализация сна и симптом-контроль. Если картина нестабильна, переводим в стационар — это короче путь к безопасности, чем многочасовые попытки «пересидеть» дома.
Получить дополнительную информацию – https://narkologicheskaya-klinika-klin8.ru/kruglosutochnaya-narkologicheskaya-klinika-v-klinu
MartyBak
27 Oct 25 at 11:22 pm
зашиваться от алкоголя [url=http://narkologicheskaya-klinika-25.ru/]http://narkologicheskaya-klinika-25.ru/[/url] .
narkologicheskaya klinika_dpPl
27 Oct 25 at 11:22 pm
Je suis fascine par Ruby Slots Casino, il procure une sensation de frisson. Le choix est aussi large qu’un festival, offrant des tables live interactives. Il booste votre aventure des le depart. Les agents sont toujours la pour aider. Les transactions sont toujours fiables, neanmoins quelques tours gratuits supplementaires seraient cool. Globalement, Ruby Slots Casino vaut une visite excitante. Notons aussi le site est rapide et immersif, permet une immersion complete. Egalement super les options variees pour les paris sportifs, qui booste la participation.
Visiter le site|
Nightspiner8zef
27 Oct 25 at 11:22 pm
[url=https://umnye-shtory-s-elektroprivodom.ru/]автоматическое закрывание штор РІ квартире прокарниз[/url] – управляемые шторы, которые позволят вам легко контролировать свет и атмосферу в вашем доме.
Комфорт — это то, что обеспечивают управляемые шторы.
умный дом шторы автоматические
27 Oct 25 at 11:23 pm
помощь нарколога [url=http://narkologicheskaya-klinika-28.ru/]помощь нарколога[/url] .
narkologicheskaya klinika_yaMa
27 Oct 25 at 11:23 pm
Please let me know if you’re looking for a writer for your weblog. You have some really good articles and I believe I would be a good asset. If you ever want to take some of the load off, I’d absolutely love to write some articles for your blog in exchange for a link back to mine. Please blast me an e-mail if interested. Cheers!
купить номера виртуальные
StephenGlona
27 Oct 25 at 11:24 pm
https://t.me/s/bs_1Win/547
Georgerah
27 Oct 25 at 11:26 pm
кракен vpn
kraken client
Henryamerb
27 Oct 25 at 11:27 pm
chopchopgrubshop – Always a pleasure to visit, never disappointed with the meals.
Leon Ockman
27 Oct 25 at 11:27 pm
отделка подвала [url=http://www.gidroizolyaciya-cena-7.ru]отделка подвала[/url] .
gidroizolyaciya cena_fxSi
27 Oct 25 at 11:28 pm