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://crossfire-megacheat.ru
HowardGoony
6 Oct 25 at 9:18 pm
купить диплом в новотроицке [url=http://www.rudik-diplom14.ru]купить диплом в новотроицке[/url] .
Diplomi_xwea
6 Oct 25 at 9:20 pm
купить диплом в томске [url=http://rudik-diplom5.ru/]http://rudik-diplom5.ru/[/url] .
Diplomi_igma
6 Oct 25 at 9:20 pm
bestchangeru.com — Надежный Обменник Валют Онлайн
¦ Что такое BestChange?
[url=https://bestchangeru.com/]bestchange обменник официальный[/url]
bestchangeru.com является одним из наиболее популярных сервисов мониторинга обменников электронных валют в русскоязычном сегменте сети Интернет. Платформа была создана для упрощения процесса выбора надежного онлайн-обмена валюты среди множества предложений.
¦ Основные преимущества BestChange:
https://bestchangeru.com/
мониторинг обменников криптовалюты
– Мониторинг лучших курсов: Лучшие курсы покупки и продажи криптовалют и электронных денег автоматически обновляются в режиме реального времени.
– Автоматическое сравнение: Удобный интерфейс позволяет мгновенно сравнить десятки предложений и выбрать оптимальное.
– Обзор отзывов пользователей: Пользователи оставляют отзывы и оценки, помогающие другим пользователям принять решение.
– Отсутствие скрытых комиссий: Информация о комиссиях отображается прозрачно и открыто.
¦ Как работает BestChange?
Пользователь вводит необходимые данные: валюту, которую хочет обменять, и желаемую сумму. После этого сервис генерирует список надежных обменных пунктов с лучшими условиями обмена.
Пример: Вы хотите обменять Bitcoin на рубли. Заходите на сайт bestchangeru.com, выбираете направление обмена («Bitcoin > Рубли»), вводите сумму и получаете таблицу проверенных обменных пунктов с наилучшими курсами.
¦ Почему выбирают BestChange?
1. Безопасность. Все обменники проходят строгую проверку перед добавлением в базу сервиса.
2. Удобство пользования. Простота интерфейса позволяет быстро находить нужную информацию даже новичкам.
3. Постоянное обновление базы данных. Курсы и условия регулярно проверяются и обновляются, обеспечивая актуальность информации.
4. Многоязычность. Помимо русского, доступна версия сайта на английском и украинском языках.
Таким образом, bestchangeru.com становится незаменимым помощником в мире цифровых финансов, позволяя легко и безопасно совершать операции обмена валют. Если вам нужен надежный и удобный способ обмена криптовалюты и электронных денег, обязательно обратите внимание на этот ресурс.
Johnnietub
6 Oct 25 at 9:21 pm
Клиника «Похмельная служба» в Нижнем Новгороде предлагает капельницу от запоя с выездом на дом. Наши специалисты обеспечат вам комфортное и безопасное лечение в привычной обстановке.
Разобраться лучше – [url=https://vyvod-iz-zapoya-nizhnij-novgorod13.ru/]анонимный вывод из запоя в нижний новгороде[/url]
Kennethwet
6 Oct 25 at 9:21 pm
av07.cc – The navigation feels intuitive, makes it easy to explore all sections.
Breanne Calhoun
6 Oct 25 at 9:26 pm
купить диплом воспитателя [url=http://rudik-diplom13.ru/]купить диплом воспитателя[/url] .
Diplomi_dcon
6 Oct 25 at 9:27 pm
купить диплом для техникума цена [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_jfea
6 Oct 25 at 9:29 pm
купить диплом в озёрске [url=http://www.rudik-diplom6.ru]http://www.rudik-diplom6.ru[/url] .
Diplomi_laKr
6 Oct 25 at 9:29 pm
Joined $MTAUR coin rush—bonuses galore. ICO’s whitepaper thorough. Endless fun ahead.
minotaurus coin
WilliamPargy
6 Oct 25 at 9:32 pm
Hello! This is my first comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading your
blog posts. Can you suggest any other blogs/websites/forums that deal with the same
topics? Thanks!
https://heyimalivemag.com/
Pengembangan Diri
6 Oct 25 at 9:32 pm
купить диплом в краснодаре [url=https://www.rudik-diplom3.ru]купить диплом в краснодаре[/url] .
Diplomi_snei
6 Oct 25 at 9:34 pm
купить диплом повара [url=www.rudik-diplom5.ru/]купить диплом повара[/url] .
Diplomi_gima
6 Oct 25 at 9:35 pm
RegrowRx Online: Best place to buy propecia – RegrowRx Online
Charleshaw
6 Oct 25 at 9:36 pm
I read this post fully on the topic of the resemblance of most recent and
preceding technologies, it’s awesome article.
Insightful information
6 Oct 25 at 9:36 pm
675kk.top – Looks promising — the posts I saw were engaging.
Grover Seefeldt
6 Oct 25 at 9:37 pm
ryla6760 – The site provides clear details about the event schedule and activities.
Tommye Earnest
6 Oct 25 at 9:37 pm
xxfq.xyz – I stumbled upon this site and it’s surprisingly clean and informative.
Derrick Guittar
6 Oct 25 at 9:38 pm
как купить диплом техникума в омске [url=https://frei-diplom10.ru]как купить диплом техникума в омске[/url] .
Diplomi_ibEa
6 Oct 25 at 9:39 pm
papamasque – I sensed strong identity here, visuals and vibe are uniquely compelling.
Porfirio Diblase
6 Oct 25 at 9:40 pm
купить диплом в сочи [url=rudik-diplom2.ru]купить диплом в сочи[/url] .
Diplomi_vspi
6 Oct 25 at 9:41 pm
купить диплом в ишиме [url=http://www.rudik-diplom7.ru]http://www.rudik-diplom7.ru[/url] .
Diplomi_fkPl
6 Oct 25 at 9:41 pm
I love your blog.. very nice colors & theme. Did you create this
website yourself or did you hire someone to do it for you?
Plz respond as I’m looking to design my own blog and
would like to find out where u got this from. appreciate it
Reddit + YouTube growth strategy
6 Oct 25 at 9:41 pm
Howdy! Do you use Twitter? I’d like to follow you if that would be okay.
I’m definitely enjoying your blog and look forward to new updates.
canadian pharmacies online
6 Oct 25 at 9:43 pm
Je suis integre a Mafia Casino, ca eleve le jeu a un niveau de boss legendaire. Le territoire est un domaine de diversite criminelle, proposant des crash pour des chutes de pouvoir. Le suivi protege avec une omerta absolue, avec une ruse qui anticipe les traitrises. Les retraits s’executent avec une furtivite remarquable, malgre cela des rackets de recompense additionnels scelleraient les pactes. Pour clore l’omerta, Mafia Casino forge une legende de jeu gangster pour les conspirateurs de victoires rusees ! En plus le graphisme est un complot dynamique et immersif, ce qui propulse chaque pari a un niveau de don.
mafia casino jeu|
Minimexer4zef
6 Oct 25 at 9:43 pm
https://derufa-crimea.ru
HowardGoony
6 Oct 25 at 9:44 pm
купить диплом в уфе [url=http://rudik-diplom13.ru/]купить диплом в уфе[/url] .
Diplomi_xfon
6 Oct 25 at 9:45 pm
bjwyipvw.xyz – I enjoy checking random posts here, always some surprise content.
Esteban Bakko
6 Oct 25 at 9:46 pm
купить диплом магистра [url=http://rudik-diplom9.ru/]купить диплом магистра[/url] .
Diplomi_bmei
6 Oct 25 at 9:46 pm
You can definitely see your expertise within the article
you write. The sector hopes for more passionate writers such as you who are not afraid to mention how they believe.
Always go after your heart.
real money online casino canada
6 Oct 25 at 9:48 pm
buy amoxil: Amoxicillin 500mg buy online – buy amoxicillin
Glennchilt
6 Oct 25 at 9:50 pm
Howdy! Do you know if they make any plugins to safeguard against hackers?
I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?
veterinarian services
6 Oct 25 at 9:51 pm
куплю диплом цена [url=http://www.rudik-diplom12.ru]куплю диплом цена[/url] .
Diplomi_laPi
6 Oct 25 at 9:51 pm
купить диплом техникума точно [url=http://frei-diplom10.ru]купить диплом техникума точно[/url] .
Diplomi_weEa
6 Oct 25 at 9:52 pm
Clomid for sale [url=https://clomicareusa.shop/#]Buy Clomid online[/url] where can i buy generic clomid pills
Davidbax
6 Oct 25 at 9:53 pm
Hello! I just wanted to ask if you ever have any trouble with hackers?
My last blog (wordpress) was hacked and I ended up losing many months of hard work
due to no data backup. Do you have any methods to protect
against hackers?
koh lim audit
6 Oct 25 at 9:54 pm
2021nikemenshoes.top – The product images are sharp, makes browsing very appealing.
Emmanuel Opdahl
6 Oct 25 at 9:55 pm
купить диплом в славянске-на-кубани [url=www.rudik-diplom6.ru]www.rudik-diplom6.ru[/url] .
Diplomi_rrKr
6 Oct 25 at 9:55 pm
купить диплом швеи [url=https://rudik-diplom14.ru]купить диплом швеи[/url] .
Diplomi_qsea
6 Oct 25 at 9:57 pm
We are a gaggle of volunteers and opening a brand new scheme
in our community. Your website provided us with valuable information to work on. You’ve done a formidable job and our whole group shall be
grateful to you.
YouTube unskippable ads revenue
6 Oct 25 at 9:57 pm
купить диплом в сургуте [url=www.rudik-diplom5.ru]купить диплом в сургуте[/url] .
Diplomi_lema
6 Oct 25 at 9:59 pm
Good blog you have got here.. It’s difficult to find high-quality writing like yours nowadays.
I really appreciate individuals like you! Take care!!
water damage cleanup near me
6 Oct 25 at 9:59 pm
купить диплом техникума образец в москве [url=http://frei-diplom10.ru]купить диплом техникума образец в москве[/url] .
Diplomi_doEa
6 Oct 25 at 10:00 pm
купить диплом о высшем образовании легально [url=https://www.frei-diplom4.ru]купить диплом о высшем образовании легально[/url] .
Diplomi_alOl
6 Oct 25 at 10:01 pm
My spouse and I absolutely love your blog and find many
of your post’s to be exactly I’m looking for. Would you offer guest writers
to write content for yourself? I wouldn’t mind composing
a post or elaborating on many of the subjects you write regarding here.
Again, awesome web site!
FenorixTrader 8.4 AI Avis
6 Oct 25 at 10:03 pm
675kk.top – The tone feels casual and approachable, I’m liking it so far.
Michel Helom
6 Oct 25 at 10:04 pm
купить диплом в назрани [url=https://rudik-diplom5.ru]купить диплом в назрани[/url] .
Diplomi_wjma
6 Oct 25 at 10:09 pm
купить диплом медицинского училища [url=http://www.rudik-diplom9.ru]купить диплом медицинского училища[/url] .
Diplomi_plei
6 Oct 25 at 10:09 pm
https://drnona-nn.ru
HowardGoony
6 Oct 25 at 10:10 pm
купить диплом техникума с реестром [url=http://frei-diplom1.ru/]купить диплом техникума с реестром[/url] .
Diplomi_tvOi
6 Oct 25 at 10:11 pm