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!
http://herengezondheid.com/# Viagra online kopen Nederland
JamesSlilk
23 Oct 25 at 4:12 pm
1xbetgiri? [url=https://www.1xbet-giris-2.com]https://www.1xbet-giris-2.com[/url] .
1xbet giris_ajPt
23 Oct 25 at 4:13 pm
1xbet giris [url=www.1xbet-giris-3.com]1xbet giris[/url] .
1xbet giris_ovMi
23 Oct 25 at 4:13 pm
1xbet ?ye ol [url=https://1xbet-giris-9.com/]1xbet-giris-9.com[/url] .
1xbet giris_rzon
23 Oct 25 at 4:15 pm
1xbet lite [url=https://1xbet-giris-5.com/]1xbet-giris-5.com[/url] .
1xbet giris_qzSa
23 Oct 25 at 4:17 pm
займ без переплат https://zaimy-67.ru
vzyat-zaym-894
23 Oct 25 at 4:20 pm
займы без отказа https://zaimy-69.ru
vse-zaymy-177
23 Oct 25 at 4:20 pm
Вызов врача-нарколога на дом в Санкт-Петербурге начинается с детального осмотра и оценки состояния пациента. Врач измеряет давление, пульс, уровень кислорода в крови и определяет степень интоксикации.
Выяснить больше – [url=https://narcolog-na-dom-sankt-peterburg00.ru/]narcolog-na-dom-sankt-peterburg00.ru/[/url]
JohnnyBloon
23 Oct 25 at 4:21 pm
1xbet yeni adresi [url=https://www.1xbet-giris-2.com]https://www.1xbet-giris-2.com[/url] .
1xbet giris_gtPt
23 Oct 25 at 4:23 pm
лучшие seo компании [url=http://reiting-seo-kompaniy.ru/]http://reiting-seo-kompaniy.ru/[/url] .
reiting seo kompanii_zton
23 Oct 25 at 4:23 pm
1xbet resmi giri? [url=https://www.1xbet-giris-6.com]https://www.1xbet-giris-6.com[/url] .
1xbet giris_imsl
23 Oct 25 at 4:24 pm
срочные займы без истории взять займ без проверки кредитной истории
zaym-vsem-710
23 Oct 25 at 4:24 pm
ConfiaFarmacia: Confia Farmacia – farmacia online para hombres
RandySkync
23 Oct 25 at 4:26 pm
1вин мобильная версия [url=https://www.1win5518.ru]https://www.1win5518.ru[/url]
1win_kg_wfkl
23 Oct 25 at 4:27 pm
услуга займа займы все онлайн
vzyat-zaym-99
23 Oct 25 at 4:28 pm
денежный кредит займ https://zaimy-69.ru
vse-zaymy-688
23 Oct 25 at 4:29 pm
рейтинг сео [url=reiting-seo-kompaniy.ru]рейтинг сео[/url] .
reiting seo kompanii_pxon
23 Oct 25 at 4:29 pm
bahis sitesi 1xbet [url=1xbet-giris-8.com]bahis sitesi 1xbet[/url] .
1xbet giris_cnPn
23 Oct 25 at 4:29 pm
Article writing is also a excitement, if you be acquainted with after
that you can write or else it is difficult to write.
Call Girls in Hotels Karachi
23 Oct 25 at 4:29 pm
1xbet mobil giri? [url=https://www.1xbet-giris-5.com]https://www.1xbet-giris-5.com[/url] .
1xbet giris_yvSa
23 Oct 25 at 4:30 pm
кредитный займ https://zaimy-67.ru
vzyat-zaym-263
23 Oct 25 at 4:31 pm
займ срочно без проверок лучшие займы онлайн
vse-zaymy-414
23 Oct 25 at 4:31 pm
I think everything posted made a ton of sense. However, what about this?
suppose you added a little content? I ain’t saying
your content isn’t solid., however suppose you added something that makes
people desire more? I mean PHP hook, building hooks
in your application – Sjoerd Maessen blog at Sjoerd Maessen blog is kinda vanilla.
You ought to look at Yahoo’s home page and note how they write post headlines to grab people
interested. You might add a video or a pic or two to get people excited about what you’ve written.
In my opinion, it would bring your blog a little
livelier.
water mitigation near me
23 Oct 25 at 4:31 pm
Ahaa, its nice dialogue on the topic of this article at
this place at this webpage, I have read all that, so at this time me
also commenting here.
seo class singapore
23 Oct 25 at 4:31 pm
1xbwt giri? [url=https://www.1xbet-giris-2.com]https://www.1xbet-giris-2.com[/url] .
1xbet giris_hxPt
23 Oct 25 at 4:33 pm
кредитная карта займ https://zaimy-71.ru
zaym-vsem-660
23 Oct 25 at 4:33 pm
займ без проверок https://zaimy-71.ru
zaym-vsem-443
23 Oct 25 at 4:35 pm
купить диплом товароведа [url=www.rudik-diplom7.ru]купить диплом товароведа[/url] .
Diplomi_zjPl
23 Oct 25 at 4:35 pm
1xbet yeni giri? adresi [url=https://1xbet-giris-6.com/]1xbet yeni giri? adresi[/url] .
1xbet giris_mksl
23 Oct 25 at 4:35 pm
1xbet t?rkiye giri? [url=http://1xbet-giris-3.com/]http://1xbet-giris-3.com/[/url] .
1xbet giris_qoMi
23 Oct 25 at 4:37 pm
взять займ онлайн https://zaimy-69.ru
vse-zaymy-603
23 Oct 25 at 4:37 pm
срочные займы без истории https://zaimy-67.ru
vzyat-zaym-873
23 Oct 25 at 4:37 pm
birxbet giri? [url=http://1xbet-giris-5.com/]http://1xbet-giris-5.com/[/url] .
1xbet giris_hwSa
23 Oct 25 at 4:39 pm
1 win bet [url=1win5519.ru]1 win bet[/url]
1win_kg_plEr
23 Oct 25 at 4:41 pm
купить диплом в невинномысске [url=https://rudik-diplom9.ru]купить диплом в невинномысске[/url] .
Diplomi_gbei
23 Oct 25 at 4:41 pm
денежный кредит займ https://zaimy-71.ru
zaym-vsem-207
23 Oct 25 at 4:42 pm
Je suis charme par Impressario Casino, c’est une plateforme qui evoque le raffinement. La selection de jeux est somptueuse, proposant des jeux de table raffines. Renforcant votre capital initial. Le support client est impeccable, garantissant un support de qualite. Le processus est simple et elegant, neanmoins des recompenses additionnelles seraient royales. Pour conclure, Impressario Casino offre une experience memorable pour les passionnes de jeux modernes ! A noter l’interface est fluide comme un banquet, amplifie le plaisir de jouer. A souligner les evenements communautaires engageants, propose des avantages personnalises.
Cliquer pour voir|
ToulouseTwistY9zef
23 Oct 25 at 4:44 pm
1xbet ?yelik [url=https://1xbet-giris-7.com/]1xbet ?yelik[/url] .
1xbet giris_olKn
23 Oct 25 at 4:44 pm
https://omaranhense.com/codigo-promocional-1xbet-bonus-vip-130-eur/
ferehpr
23 Oct 25 at 4:45 pm
Экстренный вывод из запоя в домашних условиях – это комплекс мер, направленный на быструю детоксикацию организма и восстановление нормального обмена веществ. В Волгограде квалифицированные специалисты готовы выехать к пациенту круглосуточно, чтобы оперативно оценить его состояние и начать терапию. Такой подход позволяет минимизировать негативное воздействие алкоголя и снизить риск развития осложнений.
Получить дополнительные сведения – https://vyvod-iz-zapoya-volgograd00.ru/vyvod-iz-zapoya-na-domu-volgograd/
WilliamHause
23 Oct 25 at 4:45 pm
Каждый из перечисленных факторов — веская причина для вызова врача, который может оказать помощь профессионально и безопасно.
Получить больше информации – [url=https://narcolog-na-dom-ryazan0.ru/]narcolog-na-dom-ryazan0.ru/[/url]
Richardshado
23 Oct 25 at 4:45 pm
1xbet [url=http://1xbet-giris-3.com]1xbet[/url] .
1xbet giris_skMi
23 Oct 25 at 4:46 pm
1x giri? [url=https://1xbet-giris-8.com/]1xbet-giris-8.com[/url] .
1xbet giris_qwPn
23 Oct 25 at 4:48 pm
топ компаний по продвижению сайтов [url=https://reiting-seo-kompaniy.ru]топ компаний по продвижению сайтов[/url] .
reiting seo kompanii_xqon
23 Oct 25 at 4:49 pm
1x bet giri? [url=https://1xbet-giris-6.com/]https://1xbet-giris-6.com/[/url] .
1xbet giris_hesl
23 Oct 25 at 4:49 pm
Je suis ebloui par Monte Cryptos Casino, il propose une odyssee chiffree. Le catalogue est opulent et divers, proposant des tables sophistiquees. Le bonus d’entree est scintillant. Le suivi est d’une efficacite absolue, avec une aide rapide et fiable. Le processus est fluide comme un smart contract, parfois des offres plus genereuses ajouteraient du charme. En resume, Monte Cryptos Casino offre une experience inoubliable pour les joueurs en quete d’innovation ! A noter la plateforme est visuellement eblouissante, donne envie de prolonger l’aventure. Un atout cle le programme VIP avec des niveaux exclusifs, offre des recompenses continues.
Explorer les dГ©tails|
CryptoPulseW7zef
23 Oct 25 at 4:50 pm
1xbet yeni giri? [url=https://1xbet-giris-2.com/]https://1xbet-giris-2.com/[/url] .
1xbet giris_rhPt
23 Oct 25 at 4:52 pm
1xbet resmi sitesi [url=http://1xbet-giris-9.com/]http://1xbet-giris-9.com/[/url] .
1xbet giris_cion
23 Oct 25 at 4:52 pm
hyrdaruzxpnev4of.online – Really useful articles here, bookmarked it for my afternoon reading.
Meagan Reitmeyer
23 Oct 25 at 4:54 pm
1xbet spor bahislerinin adresi [url=https://www.1xbet-giris-5.com]1xbet spor bahislerinin adresi[/url] .
1xbet giris_elSa
23 Oct 25 at 4:54 pm