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!
онлайн-казино с лицензией Curacao. Предлагает щедрые бонусы, топовые игры от ведущих провайдеров, быстрые выплаты и круглосуточную поддержку
dragon money официальный сайт
BrittGor
3 Oct 25 at 7:56 pm
купить диплом о высшем образовании [url=https://rudik-diplom1.ru]купить диплом о высшем образовании[/url] .
Diplomi_poer
3 Oct 25 at 7:57 pm
wcbxhmsdo8nr – Navigation is straightforward, I didn’t run into any confusion.
Jeromy Burgher
3 Oct 25 at 7:57 pm
Hello to every one, the contents present at this web page are in fact awesome for people experience, well, keep up the good work
fellows.
Le Labo Santal 33 dupe
3 Oct 25 at 7:58 pm
I simply couldn’t leave your site prior to suggesting
that I actually loved the standard information a person supply for your guests?
Is gonna be again regularly to check out new posts
beste casino i norge
3 Oct 25 at 7:58 pm
flmo1xt – The pages load quickly, giving a seamless experience all the way.
Jeanett Keleman
3 Oct 25 at 7:58 pm
купить диплом в кургане [url=http://www.rudik-diplom14.ru]купить диплом в кургане[/url] .
Diplomi_saea
3 Oct 25 at 7:58 pm
The Minotaurus presale is a gateway to fun DeFi gaming. $MTAUR’s low presale price sets up for gains. Referral program’s virality is key.
mtaur coin
WilliamPargy
3 Oct 25 at 7:58 pm
купить диплом в самаре [url=https://www.rudik-diplom2.ru]купить диплом в самаре[/url] .
Diplomi_uspi
3 Oct 25 at 7:59 pm
прогноз футбол [url=http://prognozy-na-futbol-10.ru/]прогноз футбол[/url] .
prognozi na fytbol_ttOi
3 Oct 25 at 8:00 pm
купить диплом в губкине [url=https://rudik-diplom7.ru/]https://rudik-diplom7.ru/[/url] .
Diplomi_stPl
3 Oct 25 at 8:00 pm
купить диплом в кирове [url=https://rudik-diplom3.ru]купить диплом в кирове[/url] .
Diplomi_peei
3 Oct 25 at 8:01 pm
диплом техникума купить киев [url=frei-diplom9.ru]диплом техникума купить киев[/url] .
Diplomi_qzea
3 Oct 25 at 8:02 pm
диплом с проводкой купить [url=http://www.frei-diplom2.ru]диплом с проводкой купить[/url] .
Diplomi_udEa
3 Oct 25 at 8:02 pm
Hi my loved one! I wish to say that this article is amazing, great written and come with approximately all significant infos.
I would like to look more posts like this .
gay
3 Oct 25 at 8:02 pm
Just swapped some ETH for $MTAUR in the presale; the process was seamless on multiple chains. The in-game currency conversion gives real edge in play. This could rival Subway Surfers with crypto flair.
mtaur coin
WilliamPargy
3 Oct 25 at 8:03 pm
https://antei-auto.ru
PatrickGop
3 Oct 25 at 8:03 pm
купить диплом в керчи [url=https://www.rudik-diplom5.ru]https://www.rudik-diplom5.ru[/url] .
Diplomi_nsma
3 Oct 25 at 8:04 pm
https://jasa-seo.mn.co/members/36190317
https://jasa-seo.mn.co/members/36190317
3 Oct 25 at 8:04 pm
Если активировать бустер, то в течение ближайших 1-12 часов
игрок будет получать больше ХР за ставки.
казино 7к
3 Oct 25 at 8:05 pm
купить диплом в железногорске [url=https://rudik-diplom4.ru/]https://rudik-diplom4.ru/[/url] .
Diplomi_cvOr
3 Oct 25 at 8:05 pm
После стабилизации состояния назначаются препараты, укрепляющие печень, сердце и нервную систему. Обязателен контроль за самочувствием пациента в течение суток и более.
Разобраться лучше – [url=https://narkologicheskaya-klinika-voronezh9.ru/]наркологическая клиника цены воронеж[/url]
JesusRal
3 Oct 25 at 8:06 pm
Необходимо, чтобы до наступления этой
даты были выполнены все специальные условия, установленные для данного вида НПА.
www.pocketrocket.kiscreative.dev/fhrende-bitcoin-casinos-einzahlungen-und-61/
3 Oct 25 at 8:07 pm
прогноз футбол [url=https://prognozy-na-futbol-10.ru/]прогноз футбол[/url] .
prognozi na fytbol_iuOi
3 Oct 25 at 8:07 pm
купить диплом в волгограде [url=www.rudik-diplom5.ru/]купить диплом в волгограде[/url] .
Diplomi_xtma
3 Oct 25 at 8:08 pm
хоккей прогнозы на сегодня [url=prognozy-na-khokkej5.ru]хоккей прогнозы на сегодня[/url] .
prognozi na hokkei_siEa
3 Oct 25 at 8:09 pm
купить диплом с занесением в реестр украина [url=frei-diplom5.ru]frei-diplom5.ru[/url] .
Diplomi_ebPa
3 Oct 25 at 8:09 pm
купить диплом моториста [url=https://rudik-diplom2.ru]купить диплом моториста[/url] .
Diplomi_rmpi
3 Oct 25 at 8:10 pm
Hello i am kavin, its my first occasion to commenting anywhere, when i read this post i thought i could also make comment due to this brilliant piece of writing.
http://www.meijyukan.co.uk/sample-page/
Dichaelwaw
3 Oct 25 at 8:10 pm
купить диплом в ачинске [url=rudik-diplom14.ru]купить диплом в ачинске[/url] .
Diplomi_qmea
3 Oct 25 at 8:10 pm
1хБет официальный сайт Ищете 1xBet официальный сайт? Он может быть заблокирован, но у 1хБет есть решения. 1xbet зеркало на сегодня — ваш главный инструмент. Это 1xbet зеркало рабочее всегда актуально. Также вы можете скачать 1xbet приложение для iOS и Android — это надежная альтернатива. Неважно, используете ли вы 1xbet сайт или 1хБет зеркало, вас ждет полный функционал: ставки на спорт и захватывающее 1xbet casino. 1хБет сегодня — это тысячи возможностей. Начните прямо сейчас!
MatthewBoymn
3 Oct 25 at 8:10 pm
I absolutely love your blog and find a lot of your post’s to be
what precisely I’m looking for. Would you offer guest writers to write content for you?
I wouldn’t mind producing a post or elaborating on many of the subjects you write regarding here.
Again, awesome website!
유흥알바
3 Oct 25 at 8:11 pm
купить диплом в оренбурге [url=http://www.rudik-diplom3.ru]купить диплом в оренбурге[/url] .
Diplomi_meei
3 Oct 25 at 8:11 pm
купить диплом в кургане занесением в реестр [url=https://frei-diplom6.ru]купить диплом в кургане занесением в реестр[/url] .
Diplomi_hvOl
3 Oct 25 at 8:11 pm
экспресс на футбол сегодня [url=http://prognozy-na-futbol-10.ru/]http://prognozy-na-futbol-10.ru/[/url] .
prognozi na fytbol_gqOi
3 Oct 25 at 8:12 pm
купить диплом в соликамске [url=http://rudik-diplom4.ru/]купить диплом в соликамске[/url] .
Diplomi_qjOr
3 Oct 25 at 8:13 pm
Book of Midas
Michaelrow
3 Oct 25 at 8:13 pm
где купить диплом с занесением реестр [url=https://www.frei-diplom1.ru]где купить диплом с занесением реестр[/url] .
Diplomi_rfOi
3 Oct 25 at 8:13 pm
где купить диплом техникума в ижевске [url=www.frei-diplom12.ru/]где купить диплом техникума в ижевске[/url] .
Diplomi_zaPt
3 Oct 25 at 8:13 pm
I think everything said was actually very logical.
But, think about this, what if you added a little information? I am
not suggesting your content is not solid., however suppose you added a title that grabbed folk’s attention? I mean PHP
hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog is a
little plain. You could glance at Yahoo’s home page and watch how they create post headlines
to grab people to click. You might add a related video or a
picture or two to get readers excited about everything’ve written. In my opinion, it could bring your blog a little bit more interesting.
best online casino australia
3 Oct 25 at 8:13 pm
купить диплом с регистрацией [url=https://www.frei-diplom3.ru]купить диплом с регистрацией[/url] .
Diplomi_boKt
3 Oct 25 at 8:14 pm
купить диплом электромонтера [url=rudik-diplom1.ru]купить диплом электромонтера[/url] .
Diplomi_sder
3 Oct 25 at 8:14 pm
It is appropriate time to make some plans for the future and it’s time to
be happy. I’ve read this post and if I could
I desire to suggest you some interesting
things or suggestions. Maybe you could write next articles referring to this article.
I wish to read more things about it!
C4C file unknown format
3 Oct 25 at 8:14 pm
Discover tһe bеѕt of Singapore’ѕ shopping scene аt
Kaizenaire.com, wheгe top promotions fгom favored brand names аre curated simply for you.
In Singapore, the shopping paradise, citizens’ love f᧐r promotions tսrns eveгy outing into a search.
Attending health resorts rejuvenates weary Singaporeans, ɑnd keеp in mind
to remaіn upgraded on Singapore’ѕ neweѕt promotions аnd shopping deals.
Guocoland develops property ɑnd business homes, valued ƅy Singaporeans fօr theіr lavish developments
and city living options.
Tiger Beer, ɑ famous regional brew mah,
provideѕ refreshing brews tһat Singaporeans love for tһeir crisp preference ɗuring celebrations ɑnd celebrations sіa.
Creator Bak Kut Teh boils sharp bak kut teh, loved ƅy residents for tender ribs and refillable soup customs.
Singaporeans love worth leh, ѕo makе Kaizenaire.сom your ցo-tо for m᧐st current deals ߋne.
Aⅼso visit my blog – it recruitment agencies in singapore for foreigners
it recruitment agencies in singapore for foreigners
3 Oct 25 at 8:14 pm
Купить диплом техникума в Киев [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_vpea
3 Oct 25 at 8:14 pm
купить проведенный диплом весь [url=http://frei-diplom2.ru]купить проведенный диплом весь[/url] .
Diplomi_zaEa
3 Oct 25 at 8:15 pm
очистка засоров канализации [url=www.chistka-zasorov-kanalizatsii.kz]очистка засоров канализации[/url] .
prochistka kanalizacii_qpkt
3 Oct 25 at 8:15 pm
прогноз футбол сегодня [url=www.prognozy-na-futbol-10.ru]прогноз футбол сегодня[/url] .
prognozi na fytbol_loOi
3 Oct 25 at 8:16 pm
купить диплом машиниста [url=https://www.rudik-diplom4.ru]купить диплом машиниста[/url] .
Diplomi_dcOr
3 Oct 25 at 8:17 pm
купить диплом в обнинске [url=rudik-diplom7.ru]rudik-diplom7.ru[/url] .
Diplomi_goPl
3 Oct 25 at 8:18 pm