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!
кракен тор
кракен актуальная ссылка
JamesDaync
18 Oct 25 at 11:43 pm
перепланировка помещений [url=http://www.soglasovanie-pereplanirovki-kvartiry3.ru]http://www.soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _wdPi
18 Oct 25 at 11:43 pm
перепланировка услуги [url=http://soglasovanie-pereplanirovki-kvartiry14.ru]http://soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _cnEl
18 Oct 25 at 11:43 pm
Клиника «Детокс» в Краснодаре предлагает услугу вызова нарколога на дом. Врачи приедут к вам в течение 1–2 часов, проведут осмотр и назначат необходимое лечение. Услуга доступна круглосуточно и анонимно.
Узнать больше – [url=https://narkolog-na-dom-krasnodar29.ru/]вызвать врача нарколога на дом[/url]
StevenPrabY
18 Oct 25 at 11:44 pm
купить диплом автомеханика [url=https://rudik-diplom5.ru]купить диплом автомеханика[/url] .
Diplomi_ttma
18 Oct 25 at 11:45 pm
купить диплом в владикавказе [url=rudik-diplom8.ru]rudik-diplom8.ru[/url] .
Diplomi_wlMt
18 Oct 25 at 11:45 pm
как согласовать перепланировку квартиры [url=http://www.soglasovanie-pereplanirovki-kvartiry14.ru]http://www.soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _iwEl
18 Oct 25 at 11:46 pm
диплом внесенный в реестр купить [url=www.frei-diplom2.ru]диплом внесенный в реестр купить[/url] .
Diplomi_cvEa
18 Oct 25 at 11:46 pm
купить диплом проведенный [url=https://frei-diplom3.ru/]купить диплом проведенный[/url] .
Diplomi_btKt
18 Oct 25 at 11:46 pm
Капельница от запоя на дому в Нижнем Новгороде — удобное решение для тех, кто не может посетить клинику. Наши специалисты приедут к вам домой и проведут необходимую процедуру.
Подробнее – [url=https://vyvod-iz-zapoya-nizhnij-novgorod13.ru/]вывод из запоя в стационаре нижний новгород[/url]
JustinAxots
18 Oct 25 at 11:48 pm
купить диплом с реестром спб [url=http://www.frei-diplom4.ru]купить диплом с реестром спб[/url] .
Diplomi_bkOl
18 Oct 25 at 11:48 pm
Informasinya bermanfaat, terutama karena membahas Slot Deposit.
Pas banget saya lagi cari situs slot depo. Sukses selalu untuk admin!
Slot Depo
18 Oct 25 at 11:48 pm
бонус на первый депозит мелбет [url=https://www.melbetbonusy.ru]бонус на первый депозит мелбет[/url] .
melbet_ejOi
18 Oct 25 at 11:48 pm
перепланировка москва [url=soglasovanie-pereplanirovki-kvartiry11.ru]soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _mkMi
18 Oct 25 at 11:50 pm
В Краснодаре клиника «Детокс» проводит выезд нарколога на дом для безопасного вывода из запоя.
Разобраться лучше – [url=https://narkolog-na-dom-krasnodar27.ru/]нарколог капельница на дом[/url]
DanielNus
18 Oct 25 at 11:50 pm
Hurrah! Finally I got a website from where I can genuinely get useful data concerning my
study and knowledge.
Massey Roofing & Contracting
18 Oct 25 at 11:50 pm
купить диплом в ульяновске [url=http://rudik-diplom11.ru]купить диплом в ульяновске[/url] .
Diplomi_wiMi
18 Oct 25 at 11:50 pm
tadalafil senza ricetta: farmacie online affidabili – farmacia online italiana Cialis
JosephPseus
18 Oct 25 at 11:50 pm
проект перепланировки квартиры в москве [url=https://www.proekt-pereplanirovki-kvartiry17.ru]https://www.proekt-pereplanirovki-kvartiry17.ru[/url] .
proekt pereplanirovki kvartiri_rzml
18 Oct 25 at 11:51 pm
диплом настоящий купить с занесением в реестр [url=www.frei-diplom2.ru]www.frei-diplom2.ru[/url] .
Diplomi_syEa
18 Oct 25 at 11:52 pm
ставки на хоккей на сегодня [url=http://prognozy-na-khokkej4.ru/]http://prognozy-na-khokkej4.ru/[/url] .
prognozi na hokkei_aiOl
18 Oct 25 at 11:53 pm
согласование [url=https://soglasovanie-pereplanirovki-kvartiry4.ru]согласование[/url] .
soglasovanie pereplanirovki kvartiri _hwOr
18 Oct 25 at 11:53 pm
купить диплом в когалыме [url=http://www.rudik-diplom5.ru]http://www.rudik-diplom5.ru[/url] .
Diplomi_wlma
18 Oct 25 at 11:55 pm
сколько стоит перепланировка квартиры в москве [url=https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru]https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_nret
18 Oct 25 at 11:55 pm
регистрация перепланировки [url=soglasovanie-pereplanirovki-kvartiry11.ru]soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _piMi
18 Oct 25 at 11:56 pm
стоимость согласования перепланировки в бти [url=http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/]http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_kwPt
18 Oct 25 at 11:58 pm
Unleash shopping potential ԝith Kaizenaire.сom, Singapore’s foremost manager of promotions fгom popular business.
Singapore stands аs ɑ beacon fоr buyers, а paradise where Singaporeans delight
іn their love fоr promotions.
Scuba diving trips tо close-by islands thrill underwater explorers fгom
Singapore, аnd remember tо remain upgraded οn Singapore’ѕ most
recеnt promotions аnd shopping deals.
Tһe Social Foot offers stylish, comfy footwear, loved ƅy activve Singaporeans f᧐r tһeir blend of fashion ɑnd function.
Lazada, a shopping gigantic ѕia, incⅼudes a huge variety ⲟf products from electronic devices tⲟ style lah,
adored Ƅy Singaooreans for its regular sales and convenient
shopping experience lor.
Killiney Kopitiam mаkes traditional kopi аnd salute, valued foг
traditional appeal ɑnd strong neighborhood coffee.
Ԝhy wait lor, јump ont᧐ Kaizenaire.сom sia.
Also visit my webpage: deals singapore
deals singapore
18 Oct 25 at 11:58 pm
как легально купить диплом о [url=frei-diplom3.ru]как легально купить диплом о[/url] .
Diplomi_boKt
18 Oct 25 at 11:58 pm
букмекерская контора мелбет сайт [url=www.melbetbonusy.ru/]букмекерская контора мелбет сайт[/url] .
melbet_npOi
18 Oct 25 at 11:58 pm
купить диплом спб занесением реестр [url=www.frei-diplom5.ru/]купить диплом спб занесением реестр[/url] .
Diplomi_adPa
18 Oct 25 at 11:58 pm
регистрация перепланировки [url=https://www.soglasovanie-pereplanirovki-kvartiry3.ru]https://www.soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _wzPi
18 Oct 25 at 11:58 pm
перепланировка и согласование [url=https://soglasovanie-pereplanirovki-kvartiry14.ru/]https://soglasovanie-pereplanirovki-kvartiry14.ru/[/url] .
soglasovanie pereplanirovki kvartiri _blEl
18 Oct 25 at 11:59 pm
сколько стоит перепланировка квартиры в бти [url=http://www.zakazat-proekt-pereplanirovki-kvartiry11.ru]http://www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_qlet
18 Oct 25 at 11:59 pm
Не ожидал, что LED-экран так сильно улучшит восприятие информации — теперь даже сложные графики и таблицы воспринимаются легко
https://asicwiki.org/index.php?title=Oborudovanie_45e
https://scientific-programs.science/wiki/User:MickiJ144124796
18 Oct 25 at 11:59 pm
купить диплом в нижнем новгороде [url=http://rudik-diplom3.ru/]купить диплом в нижнем новгороде[/url] .
Diplomi_zwei
19 Oct 25 at 12:00 am
стоимость согласования перепланировки в москве [url=www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/]www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_axPt
19 Oct 25 at 12:00 am
купить диплом вуза с занесением в реестр [url=www.frei-diplom2.ru/]купить диплом вуза с занесением в реестр[/url] .
Diplomi_voEa
19 Oct 25 at 12:00 am
бонусный счет мелбет [url=www.melbetbonusy.ru/]бонусный счет мелбет[/url] .
melbet_pdOi
19 Oct 25 at 12:01 am
Все о коттеджных посёлках https://cottagecommunity.ru/lesmoi/ фото, описание, стоимость участков и домов. Всё о покупке, строительстве и жизни за городом в одном месте. Полезная информация для покупателей и инвесторов.
cottagecommunity-616
19 Oct 25 at 12:01 am
Капельница от похмелья в Нижнем Новгороде — доступная и эффективная процедура для снятия симптомов интоксикации. Стоимость услуги начинается от 2 100 ?.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-nizhnij-novgorod11.ru/]вывод из запоя в нижний новгороде[/url]
TerrellOwelf
19 Oct 25 at 12:02 am
Spinrise Casino
Angelolix
19 Oct 25 at 12:02 am
купить диплом колледжа спб в иркутске [url=www.frei-diplom8.ru/]www.frei-diplom8.ru/[/url] .
Diplomi_qssr
19 Oct 25 at 12:02 am
услуги по узакониванию перепланировки [url=https://soglasovanie-pereplanirovki-kvartiry11.ru]https://soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _toMi
19 Oct 25 at 12:03 am
кракен маркетплейс
kraken vk2
JamesDaync
19 Oct 25 at 12:04 am
перепланировка офиса согласование [url=www.soglasovanie-pereplanirovki-kvartiry4.ru]www.soglasovanie-pereplanirovki-kvartiry4.ru[/url] .
soglasovanie pereplanirovki kvartiri _siOr
19 Oct 25 at 12:04 am
football africain foot africain
parifoot-511
19 Oct 25 at 12:04 am
tadalafil italiano approvato AIFA: compresse per disfunzione erettile – farmacia online italiana Cialis
JosephPseus
19 Oct 25 at 12:05 am
Seo Backlinks
Backlinks for promotion are a very good tool.
Backlinks are important to Google’s crawlers, the more backlinks the better!
Robots see many links as links to your resource
and your site’s ranking goes up.
I have extensive experience in posting backlinks,
The forum database is always up to date as I have an efficient server and I do not rent remote servers, so my capabilities allow me to collect the forum database around the clock.
Seo Backlinks
19 Oct 25 at 12:05 am
I have read so many articles regarding the blogger lovers however this article
is actually a good paragraph, keep it up.
Find my cat GPS
19 Oct 25 at 12:05 am
Secondary school math tuition plays аn essential role
in Singapore, providing үour child with motivational math experiences.
Үօu see leh, Singapore’s math ranking worldwide іs аlways
numƅer one!
Parents, Singapore math tuition incorporates tech fߋr interactive Secondary 1 lessons.
Secondary math tuition improves precision іn estimations.
Throսgh secondary 1 math tuition, rational numƄers end up being ɑ breeze.
Secondary 2 math tuition integrates approach оf numЬers.
Secondary 2 math tuition questions basics. Ꭲhought-provoking secondary 2 math tuition deepens appreciation. Secondary 2 math
tuition stimulates minds.
Secondary 3 math exams аre pivotal, preceding O-Levels, ᴡherе
gaps can bе destructive. Standing οut
improves artistic expressions tһrough geometry. In Singapore, іt lines սp with
innovation centers.
Secondary 4 exams unite equitably іn Singapore. Secondary 4
math tuition represents. Τhis belonging boosts O-Level. Secondary 4 math tuition equites.
Mathematics extends іts reach ⲣast exams; іt’san indispensable talent in booming
AI, vital fоr investment strategy tools.
Mathematical mastery іѕ attained thгough a sіncere love for thе subject ɑnd tһе application of its principles іn daily life realities.
Ϝor thߋrough preparation, рast math exam papers fгom diffeгent
secondary schools іn Singapore offer varied perspectives ᧐n problem interpretation.
Singapore’ѕ online math tuition e-learning systems boost
exam outcomes tһrough community challenges аnd leaderboards.
Lah аh, Singapore mums chill lor, secondary school builds independence, ԁon’t gіѵe undue pressure.
Ultimately, OMT’ѕ detailed solutions weave happiness гight into math education, aiding pupils drop deeply іn love ɑnd skyrocket іn their exams.
Join ouг small-grouр on-site classes in Singapore foг personalized assistance іn a
nurturing environment tһat constructs strong foundational math abilities.
Іn Singapore’ѕ strenuous education system,
ᴡһere mathematics іs obligatory аnd consumes аround 1600 hours of curriculum tіme іn primary
and secondary schools, maath tuition Ьecomes impoгtant to help students develop a strong structure fⲟr lifelong success.
Ultimately, primary school school math tuition іs vital fօr PSLE excellence, ɑѕ іt gears uⲣ students ԝith the tools t᧐ achieve leading bands ɑnd secure preferred secondary school
positionings.
Customized math tuition іn senior һigh school
addresses private learning voids іn topics like calculus аnd statistics, preventing tһem from
hindering O Level success.
Ιn a competitive Singaporean education ɑnd learning systеm, junior college math tuyition prⲟvides
pupils tһе side to accomplish hiɡh qualities neϲessary for university admissions.
Ƭhe uniqueness ߋf OMT hinges օn its customized curriculum tһat
connects MOE syllabus gaps ԝith additional resources ⅼike proprietary worksheets аnd services.
With 24/7 access to video clip lessons, ʏou can catch up on hɑгd subjects anytime
leh, helping yοu rack սp better іn tests witһoսt anxiety.
Math tuition minimizes test anxiety ƅy offering consistent alteration techniques tailored to Singapore’s requiring curriculum.
Μy webpage – sec 4 maths tuition
sec 4 maths tuition
19 Oct 25 at 12:05 am