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://feminine.kyiv.ua мода, красота, здоровье, отношения и семья. Полезные советы, вдохновляющие статьи, лайфхаки для дома и карьеры. Всё самое интересное для современных женщин.
StephenVew
10 Sep 25 at 6:37 pm
Автомобильный портал https://troeshka.com.ua онлайн-ресурс для автовладельцев. Каталог машин, тест-драйвы, аналитика авторынка и советы специалистов. Будьте в курсе новинок и технологий автоиндустрии.
ClaytonAnaer
10 Sep 25 at 6:38 pm
Сайт для женщин https://lolitaquieretemucho.com мода, красота, здоровье, отношения, семья и карьера. Полезные советы, статьи, рецепты и лайфхаки. Пространство для вдохновения и развития, созданное для современных женщин.
MichaelWOULP
10 Sep 25 at 6:39 pm
Все будет равно чувак!!!!!!!!
https://rant.li/fzihmeca/kirov-kupit-narkotik
Вот мой отзыв по работе данного магазина.
RogerCer
10 Sep 25 at 6:39 pm
This is really interesting, You’re a very skilled blogger.
I’ve joined your rss feed and look forward to seeking more
of your excellent post. Also, I’ve shared your site in my social networks!
skyiwredshjnhjgeleladu7m7mgpuxgsnfxzhncwtvmhr7l5bniutayd
10 Sep 25 at 6:40 pm
швейная фабрика [url=http://www.nitkapro.ru]http://www.nitkapro.ru[/url] .
shveinoe proizvodstvo_mtea
10 Sep 25 at 6:40 pm
I every time used to read paragraph in news papers but now as I am
a user of internet so Niagara Falls Tours from Toronto
now I am using net for content, thanks to web.
Niagara Falls Tours from Toronto
10 Sep 25 at 6:40 pm
1win vhod [url=https://1win12002.ru]https://1win12002.ru[/url]
1win_kwKa
10 Sep 25 at 6:41 pm
Получить диплом о высшем образовании можем помочь. Купить диплом Барнаул – [url=http://diplomybox.com/kupit-diplom-barnaul/]diplomybox.com/kupit-diplom-barnaul[/url]
Cazrrrj
10 Sep 25 at 6:43 pm
Важно указывать для получения средств только
тот метод, который вы использовали для пополнения баланса.
покер дом скачать
10 Sep 25 at 6:44 pm
Клиника «НаркоМед Плюс» использует комплексный подход для эффективного снятия симптомов ломки с применением современных методов детоксикации и поддержки организма. Основные группы препаратов включают:
Подробнее можно узнать тут – https://snyatie-lomki-nnovgorod8.ru/
Larrymit
10 Sep 25 at 6:45 pm
где можно купить диплом [url=www.educ-ua5.ru]где можно купить диплом[/url] .
Diplomi_ykKl
10 Sep 25 at 6:45 pm
J’adore l’exuberance de MrPlay Casino, c’est un casino en ligne qui deborde de panache comme un festival. La selection de jeux du casino est une veritable parade de divertissement, offrant des sessions de casino en direct qui font danser. Le personnel du casino offre un accompagnement digne d’un maestro, repondant en un clin d’?il festif. Les paiements du casino sont securises et fluides, quand meme plus de tours gratuits au casino ce serait enivrant. Dans l’ensemble, MrPlay Casino c’est un casino a rejoindre sans attendre pour les joueurs qui aiment parier avec style au casino ! A noter la navigation du casino est intuitive comme une danse, facilite une experience de casino festive.
mr.play mobiili|
zanycricket2zef
10 Sep 25 at 6:45 pm
авиатор игра [url=http://www.aviator-igra-3.ru]авиатор игра[/url] .
aviator igra_eomi
10 Sep 25 at 6:47 pm
I am not sure where you are getting your information,
but great topic. I needs to spend some time learning much more or understanding more.
Thanks for great info I was looking for this information for
my mission.
Alfonzo
10 Sep 25 at 6:48 pm
excellent points altogether, you simply won a brand new reader.
What could you recommend about your submit that you just
made some days ago? Any positive?
BlorBytAi
10 Sep 25 at 6:48 pm
When I originally commented I seem to have clicked the -Notify me when new comments are
added- checkbox and now each time a comment
is added I recieve four emails with the same comment.
Is there a way you can remove me from that service? Thanks!
pabipemkabagam.org
10 Sep 25 at 6:49 pm
авиатор 1win [url=https://aviator-igra-5.ru/]авиатор 1win[/url] .
aviator igra_pmKt
10 Sep 25 at 6:50 pm
купить диплом в полтаве [url=http://educ-ua5.ru]http://educ-ua5.ru[/url] .
Diplomi_jqKl
10 Sep 25 at 6:51 pm
Thank you for the auspicious writeup. It if truth
be told used to be a entertainment account
it. Glance complicated to more added agreeable from you!
By the way, how can we keep up a correspondence?
Chong
10 Sep 25 at 6:51 pm
masbet [url=https://mostbet12004.ru]masbet[/url]
mostbet_cmOt
10 Sep 25 at 6:52 pm
где играть в авиатор [url=https://aviator-igra-3.ru]где играть в авиатор[/url] .
aviator igra_wvmi
10 Sep 25 at 6:52 pm
I really like your blog.. very nice colors & theme. Did you create this website
yourself or did you hire someone to do it for you?
Plz answer back as I’m looking to design my own blog and
would like to find out where u got this from. many thanks
Bedrock Restoration of Edina water damage restoration companies
10 Sep 25 at 6:53 pm
промокод 1win на пополнение [url=www.1win12005.ru]www.1win12005.ru[/url]
1win_adol
10 Sep 25 at 6:53 pm
Анонимная помощь при запое — врачи «Alco.Rehab» (Москва) приедут к вам в течение часа.
Детальнее – http://vyvod-iz-zapoya-moskva13.ru/
Williamvaw
10 Sep 25 at 6:53 pm
авиатор игра 1win [url=http://www.aviator-igra-5.ru]авиатор игра 1win[/url] .
aviator igra_cpKt
10 Sep 25 at 6:54 pm
Outstanding quest there. What happened after?
Take care!
Kode Syair Toto Macau
10 Sep 25 at 6:54 pm
Доброго!
Долго думал как поднять сайт и свои проекты и нарастить ИКС Яндекса и узнал от крутых seo,
топовых ребят, именно они разработали недорогой и главное лучший прогон Хрумером – https://monstros.site
Линкбилдинг seo помогает достигать лучших результатов. Он включает создание ссылок и работу с трастовыми площадками. Программы для автоматизации ускоряют процесс. Чем больше качественных ссылок, тем выше позиции. Линкбилдинг seo – залог успешного продвижения.
продвижение сайта ремонт, kpi seo продвижения, Ссылочные прогоны и их эффективность
линкбилдинг сео, способов раскрутки сайта, продвижение сайта за звонки
!!Удачи и роста в топах!!
Seofoumn
10 Sep 25 at 6:54 pm
It’s really a cool and useful piece of information. I’m satisfied that you shared this
helpful info with us. Please stay us informed like this.
Thanks for sharing.
Madonna
10 Sep 25 at 6:55 pm
https://reloadingammo.ca/pages/1xbet_promo_code_today___welcome_bonus.html
gtoqtkj
10 Sep 25 at 6:56 pm
играть в авиатор [url=https://www.aviator-igra-5.ru]играть в авиатор[/url] .
aviator igra_vwKt
10 Sep 25 at 6:56 pm
Ahaa, its pleasant discussion about this article at this place
at this web site, I have read all that, so at this time me also commenting here.
Zack
10 Sep 25 at 6:56 pm
darknet drugs dark web market dark web market urls [url=https://darkmarketgate.com/ ]darknet drug market [/url]
Donaldfup
10 Sep 25 at 6:56 pm
купить учебный диплом [url=http://www.educ-ua20.ru]купить учебный диплом[/url] .
Diplomi_ufEn
10 Sep 25 at 6:57 pm
20
Углубиться в тему – http://vyvod-iz-zapoya-moskva11.ru/
DavidAnita
10 Sep 25 at 6:58 pm
plane crash game money [url=http://aviator-igra-3.ru/]http://aviator-igra-3.ru/[/url] .
aviator igra_whmi
10 Sep 25 at 6:59 pm
купить диплом специалиста [url=http://www.educ-ua17.ru]купить диплом специалиста[/url] .
Diplomi_vfSl
10 Sep 25 at 6:59 pm
Adoro o clima explosivo de PlayUzu Casino, da uma energia de cassino que e um redemoinho. Os titulos do cassino sao um espetaculo vibrante, oferecendo sessoes de cassino ao vivo que sao um trovao. Os agentes do cassino sao rapidos como um raio, respondendo mais rapido que um estalo. Os saques no cassino sao velozes como um furacao, mesmo assim as ofertas do cassino podiam ser mais generosas. Na real, PlayUzu Casino e o point perfeito pros fas de cassino para quem curte apostar com estilo no cassino! De bonus a plataforma do cassino detona com um visual que e puro trovao, aumenta a imersao no cassino a mil.
cupones playuzu sin depГіsito|
nuttyparrot4zef
10 Sep 25 at 6:59 pm
как использовать бонусы 1win казино [url=https://www.1win12003.ru]https://www.1win12003.ru[/url]
1win_onoi
10 Sep 25 at 7:00 pm
Je trouve absolument envoutant Posido Casino, on dirait une tempete sous-marine de fun. La selection du casino est une vague de plaisirs, comprenant des jeux de casino adaptes aux cryptomonnaies. Le personnel du casino offre un accompagnement digne d’un capitaine, repondant en un eclat d’ecume. Les retraits au casino sont rapides comme un courant marin, par moments des recompenses de casino supplementaires feraient nager de joie. En somme, Posido Casino promet un divertissement de casino aquatique pour ceux qui cherchent l’adrenaline fluide du casino ! En plus le site du casino est une merveille graphique fluide, facilite une experience de casino aquatique.
posido.|
fluffycuttlefish9zef
10 Sep 25 at 7:01 pm
*Седативные препараты применяются строго по показаниям и под мониторингом дыхания.
Подробнее можно узнать тут – [url=https://vivod-iz-zapoya-rostov14.ru/]наркологический вывод из запоя ростов-на-дону[/url]
Carlosjak
10 Sep 25 at 7:02 pm
Сотрудники , знают свое дело , лучше другого.
https://yamap.com/users/4803098
Если растворяется без подогрева – то РЅРµ РЅСѓР¶РЅРѕ. Р’ ацетоне как правило (если РїСЂРѕРґСѓРєС‚ чистый) так Рё растворяется, Рё РІ осадок РЅРµ выпадает, РЅР° спирту придется немного подогреть
RogerCer
10 Sep 25 at 7:03 pm
авиатор 1win [url=aviator-igra-5.ru]авиатор 1win[/url] .
aviator igra_jvKt
10 Sep 25 at 7:05 pm
Мы предлагаем документы институтов, которые находятся в любом регионе России. Заказать диплом университета:
[url=http://topdubaijobs.ae/employer/ukrdiplom/]купить аттестат 11 классов тюмень[/url]
Diplomi_fiPn
10 Sep 25 at 7:07 pm
Inhoud voor volwassenen is beschikbaar op verschillende adult websites voor vermaak.
Kies altijd voor betrouwbare adult sites.
Feel free to visit my webpage :: pill enhancement
pill enhancement
10 Sep 25 at 7:07 pm
Hello, I believe your site could possibly be having web browser compatibility problems.
When I look at your blog in Safari, it looks fine however, when opening in I.E., it has
some overlapping issues. I simply wanted to give you a quick heads up!
Apart from that, fantastic site!
Snabb Fluxrad
10 Sep 25 at 7:08 pm
Привет всем!
Долго ломал голову как встать в топ поисковиков и узнал от гуру в seo,
отличных ребят, именно они разработали недорогой и главное продуктивный прогон Хрумером – https://imap33.site
Линкбилдинг через автоматические проги стал стандартом в SEO. Он упрощает задачу создания ссылок и экономит силы. Программы работают на форумах, блогах и других ресурсах. Такой метод дает быстрые результаты. Линкбилдинг через автоматические проги – оптимальное решение.
seo ключи сайта, что значит seo сайта, линкбилдинг отзывы
Программы для автоматического постинга, seo сайт анализ, seo средняя цена
!!Удачи и роста в топах!!
JeromeNow
10 Sep 25 at 7:11 pm
I think the admin of this website is genuinely working hard for his web
site, as here every material is quality based information.
Feel free to surf to my site Tours from Toronto Tours Canada
Tours from Toronto Tours Canada
10 Sep 25 at 7:12 pm
20
Углубиться в тему – [url=https://kapelnica-ot-zapoya-lyubercy11.ru/]капельница от запоя город. московская область[/url]
Charlescerty
10 Sep 25 at 7:12 pm
играть авиатор [url=https://aviator-igra-5.ru/]играть авиатор[/url] .
aviator igra_aaKt
10 Sep 25 at 7:12 pm