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=https://frei-diplom1.ru]купить проведенный диплом всеми[/url] .
Diplomi_keOi
24 Oct 25 at 7:24 pm
купить диплом в архангельске [url=www.rudik-diplom10.ru]купить диплом в архангельске[/url] .
Diplomi_xjSa
24 Oct 25 at 7:25 pm
Thanks for every other great post. The place else may anybody get that
kind of info in such a perfect method of writing? I have a presentation next week, and
I am at the search for such info.
نمایندگی داکت اسپلیت ال جی
24 Oct 25 at 7:25 pm
диплом техникума старого образца купить в [url=frei-diplom11.ru]диплом техникума старого образца купить в[/url] .
Diplomi_whsa
24 Oct 25 at 7:25 pm
купить диплом в новомосковске [url=rudik-diplom3.ru]купить диплом в новомосковске[/url] .
Diplomi_vjei
24 Oct 25 at 7:28 pm
Hi, Neat post. There’s an issue along with your website in web explorer, may check this?
IE still is the market leader and a large component of people will pass over your magnificent writing because of
this problem.
www.exoticuganda.com
24 Oct 25 at 7:29 pm
https://t.me/s/bs_1xbet/39
https://t.me/s/bs_1xbet/42
24 Oct 25 at 7:29 pm
куплю диплом младшей медсестры [url=https://www.frei-diplom13.ru]https://www.frei-diplom13.ru[/url] .
Diplomi_oekt
24 Oct 25 at 7:29 pm
https://t.me/s/bs_1xbet/51
https://t.me/bs_1xbet/46
24 Oct 25 at 7:30 pm
You are so cool! I don’t believe I have read through something like this
before. So nice to find another person with unique thoughts
on this subject matter. Really.. thanks for starting this up.
This web site is something that is required on the
web, someone with a little originality!
레비트라 구입
24 Oct 25 at 7:31 pm
xbet [url=https://1xbet-9.com/]xbet[/url] .
1xbet_kzSn
24 Oct 25 at 7:31 pm
диплом медсестры с занесением в реестр купить [url=www.frei-diplom1.ru]диплом медсестры с занесением в реестр купить[/url] .
Diplomi_msOi
24 Oct 25 at 7:31 pm
xbet giri? [url=http://1xbet-4.com]http://1xbet-4.com[/url] .
1xbet_dwol
24 Oct 25 at 7:32 pm
discovernewpath.shop – Impressed by the variety of content; keeps me coming back.
Ayana Belone
24 Oct 25 at 7:32 pm
купить диплом в невинномысске [url=https://rudik-diplom11.ru]купить диплом в невинномысске[/url] .
Diplomi_hbMi
24 Oct 25 at 7:32 pm
купить диплом маркетолога [url=https://rudik-diplom6.ru]купить диплом маркетолога[/url] .
Diplomi_dtKr
24 Oct 25 at 7:33 pm
Подробная инструкция по активации бонусов и типам предложений — от фрибетов до подарков на День Рождения; в одном из абзацев естественно вставлена ссылка на 1хБет промокод на сегодня, чтобы читатель мог сразу перейти к источнику. Материал также рассказывает о верификации и минимальных требованиях для вывода средств.
Petercet
24 Oct 25 at 7:34 pm
купить диплом в камышине [url=https://www.rudik-diplom8.ru]купить диплом в камышине[/url] .
Diplomi_syMt
24 Oct 25 at 7:34 pm
купить диплом в старом осколе [url=www.rudik-diplom4.ru]купить диплом в старом осколе[/url] .
Diplomi_ycOr
24 Oct 25 at 7:37 pm
купить диплом о высшем образовании легально [url=https://frei-diplom4.ru]купить диплом о высшем образовании легально[/url] .
Diplomi_iaOl
24 Oct 25 at 7:37 pm
купить проведенный диплом моих [url=https://www.frei-diplom5.ru]купить проведенный диплом моих[/url] .
Diplomi_fiPa
24 Oct 25 at 7:37 pm
купить диплом техникума в екатеринбурге с внесением в реестр [url=https://www.frei-diplom12.ru]купить диплом техникума в екатеринбурге с внесением в реестр[/url] .
Diplomi_ihPt
24 Oct 25 at 7:37 pm
1x giri? [url=www.1xbet-giris-3.com/]www.1xbet-giris-3.com/[/url] .
1xbet giris_xyMi
24 Oct 25 at 7:37 pm
купить дипломы о высшем образовании цена [url=http://www.rudik-diplom3.ru]купить дипломы о высшем образовании цена[/url] .
Diplomi_obei
24 Oct 25 at 7:38 pm
медсестра которая купила диплом врача [url=https://frei-diplom15.ru]медсестра которая купила диплом врача[/url] .
Diplomi_yyoi
24 Oct 25 at 7:38 pm
купить диплом историка [url=https://rudik-diplom2.ru]купить диплом историка[/url] .
Diplomi_uqpi
24 Oct 25 at 7:39 pm
1xbet tr [url=https://1xbet-giris-3.com/]1xbet tr[/url] .
1xbet giris_pgMi
24 Oct 25 at 7:41 pm
купить диплом в геленджике [url=https://rudik-diplom8.ru/]https://rudik-diplom8.ru/[/url] .
Diplomi_ckMt
24 Oct 25 at 7:41 pm
Ich bin total hingerissen von Snatch Casino, es bietet ein mitrei?endes Spielerlebnis. Es gibt unzahlige packende Spiele, mit Krypto-freundlichen Titeln. Der Bonus fur Neukunden ist attraktiv. Der Service ist absolut zuverlassig. Die Zahlungen sind sicher und effizient, von Zeit zu Zeit mehr Aktionen waren ein Gewinn. Letztlich, Snatch Casino sorgt fur ununterbrochenen Spa?. Ubrigens ist das Design modern und einladend, jeden Moment aufregender macht. Ein Hauptvorteil sind die schnellen Krypto-Transaktionen, schnelle Zahlungen garantieren.
Snatch Casino|
DarkCorean3zef
24 Oct 25 at 7:41 pm
купить диплом в магадане [url=www.rudik-diplom6.ru/]купить диплом в магадане[/url] .
Diplomi_jfKr
24 Oct 25 at 7:43 pm
1xbet turkiye [url=http://1xbet-7.com/]http://1xbet-7.com/[/url] .
1xbet_eeol
24 Oct 25 at 7:43 pm
Наша выездная бригада приезжает без маркировки, в гражданской одежде, согласовывает «тихое окно» связи с пациентом или близкими и начинает не с капельницы, а с настройки среды: тёплая приглушённая подсветка, проветривание без сквозняков, отключение уведомлений, подготовка воды комнатной температуры. Затем — быстрый осмотр, экспресс-метрики и старт индивидуального плана. Каждая корректировка — ровно одна за раз, чтобы сохранить причинно-следственную связь и не провоцировать полипрагмазию.
Ознакомиться с деталями – [url=https://narkolog-na-dom-saratov0.ru/]вызов врача нарколога на дом саратов[/url]
RolandAnatt
24 Oct 25 at 7:43 pm
Aw, this was an extremely good post. Spending some time and actual effort to produce a good article… but what can I
say… I put things off a whole lot and never manage to get anything done.
비아그라 온라인 구매
24 Oct 25 at 7:44 pm
1xbet giri? adresi [url=www.1xbet-9.com]www.1xbet-9.com[/url] .
1xbet_bvSn
24 Oct 25 at 7:44 pm
сколько стоит купить диплом техникума [url=https://www.frei-diplom12.ru]сколько стоит купить диплом техникума[/url] .
Diplomi_tyPt
24 Oct 25 at 7:44 pm
где купить диплом образование [url=http://rudik-diplom10.ru]где купить диплом образование[/url] .
Diplomi_ikSa
24 Oct 25 at 7:45 pm
купить диплом пту с занесением в реестр [url=https://frei-diplom4.ru]купить диплом пту с занесением в реестр[/url] .
Diplomi_lgOl
24 Oct 25 at 7:45 pm
1xbet mobi [url=www.1xbet-4.com/]www.1xbet-4.com/[/url] .
1xbet_onol
24 Oct 25 at 7:45 pm
купить диплом реестр [url=http://frei-diplom5.ru/]купить диплом реестр[/url] .
Diplomi_zjPa
24 Oct 25 at 7:45 pm
купить диплом в прокопьевске [url=https://www.rudik-diplom4.ru]купить диплом в прокопьевске[/url] .
Diplomi_dxOr
24 Oct 25 at 7:46 pm
купить легальный диплом колледжа [url=http://www.frei-diplom1.ru]купить легальный диплом колледжа[/url] .
Diplomi_sbOi
24 Oct 25 at 7:46 pm
купить диплом в перми [url=www.rudik-diplom2.ru/]купить диплом в перми[/url] .
Diplomi_ampi
24 Oct 25 at 7:47 pm
simply click the following site
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
simply click the following site
24 Oct 25 at 7:47 pm
1xbet ?ye ol [url=https://1xbet-7.com]https://1xbet-7.com[/url] .
1xbet_hfol
24 Oct 25 at 7:49 pm
диплом техникума казахстана купить [url=https://frei-diplom12.ru]диплом техникума казахстана купить[/url] .
Diplomi_nvPt
24 Oct 25 at 7:50 pm
1x bet giri? [url=http://www.1xbet-giris-3.com]http://www.1xbet-giris-3.com[/url] .
1xbet giris_kxMi
24 Oct 25 at 7:50 pm
купить диплом [url=http://rudik-diplom8.ru]купить диплом[/url] .
Diplomi_lqMt
24 Oct 25 at 7:50 pm
I’m no longer positive where you are getting your info, however good topic.
I must spend a while learning more or working out more.
Thanks for wonderful info I used to be searching for this information for my mission.
video hiếp dâm
24 Oct 25 at 7:52 pm
1xbet turkiye [url=http://www.1xbet-9.com]http://www.1xbet-9.com[/url] .
1xbet_dgSn
24 Oct 25 at 7:53 pm
https://t.me/bs_1xbet/31
https://t.me/bs_1xbet/3
24 Oct 25 at 7:53 pm