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=www.frei-diplom2.ru]купить медицинский диплом с занесением в реестр[/url] .
Diplomi_wnEa
1 Nov 25 at 5:09 am
https://t.me/ud_Rox/51
MichaelPione
1 Nov 25 at 5:09 am
купить проведенный диплом спб [url=https://www.frei-diplom5.ru]https://www.frei-diplom5.ru[/url] .
Diplomi_ckPa
1 Nov 25 at 5:09 am
купить аттестат за 9 класс [url=http://www.rudik-diplom5.ru]купить аттестат за 9 класс[/url] .
Diplomi_ggma
1 Nov 25 at 5:10 am
старые дипломы купить [url=https://rudik-diplom8.ru/]старые дипломы купить[/url] .
Diplomi_kqMt
1 Nov 25 at 5:10 am
купить диплом техникума строительного [url=http://www.frei-diplom11.ru]купить диплом техникума строительного[/url] .
Diplomi_bbsa
1 Nov 25 at 5:11 am
купить диплом с занесением в реестры [url=https://frei-diplom6.ru]купить диплом с занесением в реестры[/url] .
Diplomi_umOl
1 Nov 25 at 5:12 am
Купить диплом колледжа в Николаев [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_zmea
1 Nov 25 at 5:12 am
В Ростове-на-Дону клиника «ЧСП№1» предлагает квалифицированный вывод из запоя в стационаре и на дому.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-rostov27.ru/]вывод из запоя клиника[/url]
CarmineFubok
1 Nov 25 at 5:13 am
куплю диплом младшей медсестры [url=https://www.frei-diplom13.ru]https://www.frei-diplom13.ru[/url] .
Diplomi_vukt
1 Nov 25 at 5:13 am
купить диплом в северодвинске [url=www.rudik-diplom10.ru/]купить диплом в северодвинске[/url] .
Diplomi_vnSa
1 Nov 25 at 5:14 am
купить диплом без внесения в реестр [url=http://frei-diplom5.ru/]купить диплом без внесения в реестр[/url] .
Diplomi_jePa
1 Nov 25 at 5:15 am
Sizi gecmisten ilham alan guzellik ipuclar?yla dolu bu nostaljik yolculuga davet ediyoruz. 90’lar modas?n?n s?rlar?na goz atal?m m??
Кстати, если вас интересует Ev Dekorasyonunda Modern ve Estetik Cozumler, посмотрите сюда.
Ссылка ниже:
[url=https://evimturk.com]https://evimturk.com[/url]
Nostalji dolu bu yolculukta bizimle oldugunuz icin tesekkur ederiz. 90’lar modas? ve guzelliginin ruhunu hissedin.
Josephassof
1 Nov 25 at 5:16 am
как купить диплом техникума с занесением в реестр цена в [url=https://frei-diplom2.ru]как купить диплом техникума с занесением в реестр цена в[/url] .
Diplomi_kgEa
1 Nov 25 at 5:16 am
best Australian pharmacies [url=https://aussiemedshubau.shop/#]pharmacy discount codes AU[/url] cheap medicines online Australia
Hermanengam
1 Nov 25 at 5:17 am
Wonderful beat ! I would like to apprentice while you amend your web site, how could i subscribe for a blog site?
The account helped me a acceptable deal. I had been a
little bit acquainted of this your broadcast provided bright
clear concept
Read more
1 Nov 25 at 5:18 am
купить диплом в минеральных водах [url=https://rudik-diplom2.ru/]https://rudik-diplom2.ru/[/url] .
Diplomi_itpi
1 Nov 25 at 5:18 am
купить диплом с реестром цена [url=http://frei-diplom5.ru]купить диплом с реестром цена[/url] .
Diplomi_epPa
1 Nov 25 at 5:19 am
купить диплом с занесением в реестр барнаул [url=https://frei-diplom6.ru/]купить диплом с занесением в реестр барнаул[/url] .
Diplomi_nlOl
1 Nov 25 at 5:19 am
купить диплом в каспийске [url=http://www.rudik-diplom10.ru]http://www.rudik-diplom10.ru[/url] .
Diplomi_qqSa
1 Nov 25 at 5:19 am
РедМетСплав предлагает широкий ассортимент высококачественных изделий из ценных материалов. Не важно, какие объемы вам необходимы – от мелких партий до крупных поставок, мы гарантируем своевременную реализацию вашего заказа.
Каждая единица изделия подтверждена всеми необходимыми документами, подтверждающими их соответствие стандартам. Дружелюбная помощь – наша визитная карточка – мы на связи, чтобы разрешать ваши вопросы по мере того как находить ответы под специфику вашего бизнеса.
Доверьте ваш запрос специалистам РедМетСплав и убедитесь в множестве наших преимуществ
Наши товары:
Полоса магниевая SISMg4637-04 – SS 144637 Порошок магниевый SISMg4637-03 – SS 144637 представляет собой высококачественный магниевый продукт, обладающий уникальными свойствами и широким спектром применения. Этот порошок идеально подходит для использования в различных отраслях, включая металлообработку и производство легких сплавов. Благодаря своим характеристикам, он обеспечивает отличную прочность и легкость изделий. Купить Порошок магниевый SISMg4637-03 – SS 144637 можно по выгодной цене. Он станет надежным выбором как для профессионалов, так и для любителей. Пользуйтесь современным материалом, чтобы достичь новых вершин в своих проектах.
SheilaAlemn
1 Nov 25 at 5:21 am
https://aussiemedshubau.com/# pharmacy online
Haroldovaph
1 Nov 25 at 5:23 am
https://safemedsguide.com/# cheapest pharmacies in the USA
Haroldovaph
1 Nov 25 at 5:24 am
I quite like reading an article that will make men and women think.
Also, thanks for allowing me to comment!
Velora Nexen
1 Nov 25 at 5:24 am
купить диплом в петропавловске-камчатском [url=http://rudik-diplom8.ru]купить диплом в петропавловске-камчатском[/url] .
Diplomi_irMt
1 Nov 25 at 5:25 am
What we’re covering
• Zelensky in Washington: European leaders will join Ukrainian President Volodymyr Zelensky at the White House, as he meets with US President Donald Trump this afternoon. Trump said Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
[url=https://kra-37-at.com]kra36 cc[/url]
• Potential security guarantees: At last week’s summit with Trump, Russian President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
[url=https://kra-34at.com]kra36 at[/url]
• On the ground: Zelensky condemned Russia’s latest strikes across Ukraine, which killed at least 10 people, saying the Kremlin intends to “humiliate diplomatic efforts” and underscores “why reliable security guarantees are required.”
kra30 cc
https://kra-36cc.net
Jasonsodia
1 Nov 25 at 5:25 am
What a stuff of un-ambiguity and preserveness of precious experience concerning unpredicted
feelings.
Honestly
1 Nov 25 at 5:26 am
купить диплом техникума 1989 [url=www.frei-diplom11.ru/]купить диплом техникума 1989[/url] .
Diplomi_rosa
1 Nov 25 at 5:26 am
What we’re covering
• Zelensky in Washington: European leaders will join Ukrainian President Volodymyr Zelensky at the White House, as he meets with US President Donald Trump this afternoon. Trump said Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
[url=https://kra-37cc.com]kra30 cc[/url]
• Potential security guarantees: At last week’s summit with Trump, Russian President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
[url=https://kra35-cc.com]kra30[/url]
• On the ground: Zelensky condemned Russia’s latest strikes across Ukraine, which killed at least 10 people, saying the Kremlin intends to “humiliate diplomatic efforts” and underscores “why reliable security guarantees are required.”
kra33 СЃСЃ
https://kra38-at.cc
Stephengoots
1 Nov 25 at 5:27 am
Выезд на дом
Подробнее – [url=https://narkologicheskaya-pomoshch-orekhovo-zuevo7.ru/]narkologicheskaya-pomoshch-orekhovo-zuevo7.ru/[/url]
HarleyMardy
1 Nov 25 at 5:27 am
купить диплом в биробиджане [url=rudik-diplom10.ru]купить диплом в биробиджане[/url] .
Diplomi_jeSa
1 Nov 25 at 5:27 am
trusted online pharmacy Ireland
Edmundexpon
1 Nov 25 at 5:28 am
SafeMedsGuide: Safe Meds Guide – buy medications online safely
HaroldSHems
1 Nov 25 at 5:28 am
техникум какое образование украина [url=https://educ-ua7.ru/]https://educ-ua7.ru/[/url] .
Diplomi_hpea
1 Nov 25 at 5:28 am
купить аттестат школы [url=https://rudik-diplom2.ru/]купить аттестат школы[/url] .
Diplomi_mwpi
1 Nov 25 at 5:29 am
купить диплом в керчи [url=https://www.rudik-diplom9.ru]https://www.rudik-diplom9.ru[/url] .
Diplomi_qkei
1 Nov 25 at 5:29 am
Way cool! Some very valid points! I appreciate you penning this write-up plus the rest of the website is
really good.
تعمیر ماشین لباسشویی بکو
1 Nov 25 at 5:31 am
cashback Spinbara Spinbara Casino login jest prosty i szybki, wystarczy podac swoj adres e-mail i haslo, aby uzyskac dostep do swojego konta.
MerlinFenny
1 Nov 25 at 5:31 am
Fantastic blog you have here but I was wanting to know if you knew of any message boards that cover the same topics talked about here?
I’d really like to be a part of group where I can get feedback from other
experienced people that share the same interest. If you have any suggestions,
please let me know. Cheers!
Read more
1 Nov 25 at 5:32 am
Hey hey, Singapore parents, maths іѕ likely tһe extremely іmportant primary discipline, promoting innovation іn challenge-tackling іn groundbreaking jobs.
Do not mess аround lah, combine a excellent Junior College
alongside mathematics excellence t᧐ guarantee higһ A Levels resultѕ
and seamless changes.
Mums and Dads, worry aƄout tһe difference hor, maths base proves vital іn Junior
College to comprehending data, crucial fօr current digital
market.
Tampines Meridian Junior College, fгom a vibrant merger, supplies
ingenious education іn drama and Malay language
electives. Cutting-edge facilities support diverse streams,
including commerce. Talent advancement ɑnd overseas programs foster leadership ɑnd
cultural awareness. А caring neighborhood motivates
empathy аnd strength. Trainees prosper іn holistic advancement, prepared f᧐r global challenges.
Dunman Нigh School Junior College differentiates
іtself tһrough its extraordinary multilingual education structure,ѡhich skillfully merges Eastern cultural
wisdom ᴡith Western analytical аpproaches, supporting students іnto flexible, culturally sensitive thinkers ѡho aгe skilled аt bridging diverse
ρoint of viewss іn a globalized woгld. Tһе school’s incorporated
ѕix-yеar program guarantees ɑ smooth and enriched transition,
featuring specialized curricula іn STEM fields witһ access to state-of-the-art research study labs ɑnd in humanities ԝith
immersive language immersion modules, ɑll designed tо promote intellectual depth
аnd ingenious prоblem-solving. Іn a nurturing and harmonious campus environment, students actively tɑke рart in leadership roles, creative ventures ⅼike debate
cⅼubs and cultural festivals, ɑnd community
tasks tһat boost theіr social awareness and collaborative
skills. Τһe college’ѕ robust global immersion initiatives, consisting ⲟf
student exchanges with partner schools in Asia ɑnd Europe, іn аddition to
worldwide competitions, offer hands-᧐n experiences that
hone cross-cultural competencies ɑnd prepare trainees for
growing in multicultural settings. Ꮤith a consistent record оf outstanding academic performance,
Dunman Ηigh School Junior College’ѕ graduates safe аnd secure positionings in premier universities
worldwide, exemplifying tһe institution’s
commitment tο fostering scholastic rigor, personal quality, ɑnd a lifelong passion for learning.
Aνoid take lightly lah, pair a reputable Junior College ѡith mathematics superiority to
ensure superior А Levels marks рlus effortless shifts.
Mums ɑnd Dads, dread thе disparity hor, math foundation іѕ
critical ԁuring Junior College for grasping information, crucial
for tоday’s online economy.
Listen uρ, composed pom рi pi, mathematics is
рart іn the һighest disciplines at Junior College,
building base for A-Level advanced math.
Ӏn addіtion frⲟm establishment amenities, focus ѡith mathematics fօr avoid frequent mistakes ѕuch аs inattentive errors
at tests.
Alas, minuѕ solid maths in Junior College, noo matter
tօp establishment children coᥙld falter
in secondary algebra, therefore develop іt immediately
leh.
A-level success stories іn Singapore ⲟften start with kiasu study habits fгom JC Ԁays.
Mums and Dads, ffear tһe disparity hor, mathematics base proves vital ɑt Junior College
іn grasping іnformation, vital for current tech-driven ѕystem.
Wah lao, еvеn whether institution proves atas, mathematics serves аs the maҝe-օr-break
topic to cultivates poise гegarding calculations.
Ꮇу webpage – National Junior College
National Junior College
1 Nov 25 at 5:32 am
купить дипломы о высшем с занесением [url=http://rudik-diplom12.ru/]купить дипломы о высшем с занесением[/url] .
Diplomi_jqPi
1 Nov 25 at 5:32 am
купить диплом в новоалтайске [url=www.rudik-diplom4.ru]купить диплом в новоалтайске[/url] .
Diplomi_atOr
1 Nov 25 at 5:33 am
Can you tell us more about this? I’d want to find out more details.
how to withdraw crypto to bank account
1 Nov 25 at 5:33 am
купить диплом в махачкале [url=www.rudik-diplom8.ru/]купить диплом в махачкале[/url] .
Diplomi_ncMt
1 Nov 25 at 5:34 am
диплом купить с занесением в реестр [url=www.frei-diplom6.ru]диплом купить с занесением в реестр[/url] .
Diplomi_kkOl
1 Nov 25 at 5:34 am
купить диплом в мурманске с занесением в реестр [url=www.frei-diplom5.ru/]купить диплом в мурманске с занесением в реестр[/url] .
Diplomi_erPa
1 Nov 25 at 5:34 am
забьется, такое бывает у них. купить Кокаин, Мефедрон, Экстази заказывали реагент jv 61, брали 15 гр, с данным продовцом работаю с 11 года, сейчас регу тянул на зону, в целом все хорошо как обычно какачество соответствует заявленному, единственное проблеммы с отправкой возникают но думаю эти проблемы временные, поссылка дошла за два дня после отправки,, затестить сиогли на днях как все зашло, с первой прикурки чесно сказать прихуели думали что опять дживи 100 пришел, но ннет , держало часа по два сначало, на третий день время прихода испало до 4 0мин, вообщем все понравилось в очередной раз, на днях закажем еще
StephenZew
1 Nov 25 at 5:35 am
discount pharmacies in Ireland
Edmundexpon
1 Nov 25 at 5:35 am
купить диплом медсестры [url=www.rudik-diplom11.ru/]купить диплом медсестры[/url] .
Diplomi_esMi
1 Nov 25 at 5:36 am
купить проведенный диплом кого [url=https://frei-diplom4.ru]купить проведенный диплом кого[/url] .
Diplomi_bxOl
1 Nov 25 at 5:36 am