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-diplom4.ru/]https://frei-diplom4.ru/[/url] .
Diplomi_cwOl
1 Nov 25 at 9:50 am
скачать mostbet [url=https://mostbet12033.ru/]https://mostbet12033.ru/[/url]
mostbet_kg_wmpa
1 Nov 25 at 9:51 am
купить диплом в ельце [url=www.rudik-diplom7.ru]www.rudik-diplom7.ru[/url] .
Diplomi_hlPl
1 Nov 25 at 9:51 am
This design is spectacular! You most certainly know
how to keep a reader entertained. Between your wit and your videos,
I was almost moved to start my own blog (well, almost…HaHa!)
Wonderful job. I really loved what you had to say, and more than that, how you presented it.
Too cool!
lk21
1 Nov 25 at 9:51 am
купить диплом хореографа [url=rudik-diplom3.ru]купить диплом хореографа[/url] .
Diplomi_qmei
1 Nov 25 at 9:51 am
купить диплом врача [url=http://rudik-diplom11.ru]купить диплом врача[/url] .
Diplomi_hmMi
1 Nov 25 at 9:51 am
купить диплом в старом осколе [url=https://www.rudik-diplom4.ru]купить диплом в старом осколе[/url] .
Diplomi_hrOr
1 Nov 25 at 9:51 am
купить диплом старого образца [url=http://rudik-diplom12.ru]купить диплом старого образца[/url] .
Diplomi_yjPi
1 Nov 25 at 9:52 am
I believe everything posted was very logical. However, what about this?
what if you were to write a killer title? I mean, I don’t wish to tell you how to run your blog, but what if
you added a title that grabbed people’s attention? I
mean PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog is kinda
vanilla. You ought to glance at Yahoo’s home
page and watch how they create post titles to grab people to
click. You might try adding a video or a related picture or two to get people
excited about what you’ve got to say. In my opinion, it would make your website a little bit more interesting.
do australians need visa for turkey
1 Nov 25 at 9:53 am
купить диплом в сыктывкаре [url=http://rudik-diplom7.ru]купить диплом в сыктывкаре[/url] .
Diplomi_pcPl
1 Nov 25 at 9:55 am
купить диплом в нижнекамске [url=https://www.rudik-diplom5.ru]https://www.rudik-diplom5.ru[/url] .
Diplomi_ivma
1 Nov 25 at 9:55 am
купить диплом бухгалтера [url=rudik-diplom3.ru]купить диплом бухгалтера[/url] .
Diplomi_dgei
1 Nov 25 at 9:57 am
купить диплом в кинешме [url=rudik-diplom11.ru]купить диплом в кинешме[/url] .
Diplomi_jjMi
1 Nov 25 at 9:57 am
купить диплом в новокуйбышевске [url=https://www.rudik-diplom9.ru]купить диплом в новокуйбышевске[/url] .
Diplomi_kxei
1 Nov 25 at 9:57 am
В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
Изучить материалы по теме – https://supermarcoplumbing.com/2023/01/13/hello-world
Williamsaw
1 Nov 25 at 9:57 am
купить диплом о высшем образовании легально [url=https://frei-diplom4.ru]купить диплом о высшем образовании легально[/url] .
Diplomi_mmOl
1 Nov 25 at 9:57 am
купить диплом в серове [url=rudik-diplom4.ru]купить диплом в серове[/url] .
Diplomi_bxOr
1 Nov 25 at 9:59 am
купить диплом о техническом образовании с занесением в реестр [url=http://frei-diplom3.ru]купить диплом о техническом образовании с занесением в реестр[/url] .
Diplomi_yvKt
1 Nov 25 at 9:59 am
https://t.me/ud_Flagman/60
MichaelPione
1 Nov 25 at 10:00 am
купить диплом дизайнера [url=http://rudik-diplom5.ru/]купить диплом дизайнера[/url] .
Diplomi_wjma
1 Nov 25 at 10:01 am
best Australian pharmacies: pharmacy discount codes AU – verified online chemists in Australia
HaroldSHems
1 Nov 25 at 10:01 am
диплом техникума купить с проводкой [url=https://www.frei-diplom11.ru]диплом техникума купить с проводкой[/url] .
Diplomi_dpsa
1 Nov 25 at 10:04 am
купить диплом образцы [url=rudik-diplom12.ru]купить диплом образцы[/url] .
Diplomi_tzPi
1 Nov 25 at 10:04 am
Exceptional post however , I was wanting to know if you could write a litte
more on this subject? I’d be very thankful if
you could elaborate a little bit more. Many thanks!
اعلام برنامه امتحانات نهایی دانشآموزان ۱۴۰۵
1 Nov 25 at 10:05 am
купить диплом в саранске [url=www.rudik-diplom3.ru/]купить диплом в саранске[/url] .
Diplomi_kmei
1 Nov 25 at 10:05 am
купить диплом в новочебоксарске [url=www.rudik-diplom11.ru/]www.rudik-diplom11.ru/[/url] .
Diplomi_tyMi
1 Nov 25 at 10:05 am
Magnificent web site. Lots of useful information here.
I am sending it to some friends ans also sharing in delicious.
And certainly, thanks in your sweat!
vajina dış dudak estetiği
1 Nov 25 at 10:08 am
купить диплом в сосновом бору [url=http://rudik-diplom5.ru]http://rudik-diplom5.ru[/url] .
Diplomi_odma
1 Nov 25 at 10:09 am
купить диплом в черкесске [url=https://www.rudik-diplom9.ru]купить диплом в черкесске[/url] .
Diplomi_xnei
1 Nov 25 at 10:10 am
verified pharmacy coupon sites Australia: Australian pharmacy reviews – Australian pharmacy reviews
HaroldSHems
1 Nov 25 at 10:10 am
кто купил диплом с занесением в реестр [url=http://frei-diplom3.ru]кто купил диплом с занесением в реестр[/url] .
Diplomi_umKt
1 Nov 25 at 10:10 am
Wow, incredible blog layout! How lengthy have you been blogging for?
you make running a blog look easy. The whole glance
of your web site is wonderful, let alone the content material!
Visit site
1 Nov 25 at 10:11 am
sdzmbz.com – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
Dorsey Blackshire
1 Nov 25 at 10:11 am
купить диплом в октябрьском [url=rudik-diplom12.ru]купить диплом в октябрьском[/url] .
Diplomi_gjPi
1 Nov 25 at 10:11 am
купить дипломы о высшем [url=https://rudik-diplom2.ru/]купить дипломы о высшем[/url] .
Diplomi_mrpi
1 Nov 25 at 10:12 am
mostbet kg [url=http://mostbet12034.ru]mostbet kg[/url]
mostbet_kg_chPr
1 Nov 25 at 10:14 am
купить диплом переводчика [url=http://www.rudik-diplom7.ru]купить диплом переводчика[/url] .
Diplomi_rgPl
1 Nov 25 at 10:14 am
90’lar modas?n?n guzellik s?rlar?yla gunumuzun trendlerine meydan okumaya ne dersiniz?
Для тех, кто ищет информацию по теме “Guzellik ve Kozmetik: 90’lar Modas?ndan Ipuclar?”, есть отличная статья.
Ссылка ниже:
[url=https://aynakirildi.com]https://aynakirildi.com[/url]
90’lar?n buyusunu modern dunyaya tas?mak hic bu kadar kolay olmam?st?. Unutulmayan bu donemin guzellik s?rlar?n? unutmay?n!
Josephassof
1 Nov 25 at 10:14 am
купить диплом о высшем образовании легально [url=https://frei-diplom1.ru/]купить диплом о высшем образовании легально[/url] .
Diplomi_nmOi
1 Nov 25 at 10:15 am
Эта статья сочетает в себе как полезные, так и интересные сведения, которые обогатят ваше понимание насущных тем. Мы предлагаем практические советы и рекомендации, которые легко внедрить в повседневную жизнь. Узнайте, как улучшить свои навыки и обогатить свой опыт с помощью простых, но эффективных решений.
Узнать больше – https://evarodriguez.fr/bonjour-tout-le-monde
Victoreluts
1 Nov 25 at 10:15 am
mostbet kg [url=http://mostbet12033.ru]http://mostbet12033.ru[/url]
mostbet_kg_dupa
1 Nov 25 at 10:17 am
купить диплом в набережных челнах [url=https://www.rudik-diplom9.ru]купить диплом в набережных челнах[/url] .
Diplomi_orei
1 Nov 25 at 10:17 am
где купить диплом техникума старого образца [url=http://www.frei-diplom12.ru]где купить диплом техникума старого образца[/url] .
Diplomi_wcPt
1 Nov 25 at 10:17 am
best Irish pharmacy websites
Edmundexpon
1 Nov 25 at 10:18 am
купить диплом в новоуральске [url=http://rudik-diplom2.ru/]http://rudik-diplom2.ru/[/url] .
Diplomi_uapi
1 Nov 25 at 10:18 am
Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
Открой скрытое – https://redols.caib.es/c07006299/2021/04/19/calendari-escolar-2021-22
BrianBeise
1 Nov 25 at 10:20 am
купить диплом в губкине [url=http://rudik-diplom2.ru]http://rudik-diplom2.ru[/url] .
Diplomi_jtpi
1 Nov 25 at 10:22 am
safe place to order meds UK: Uk Meds Guide – legitimate pharmacy sites UK
Johnnyfuede
1 Nov 25 at 10:24 am
online pharmacy ireland: trusted online pharmacy Ireland – best Irish pharmacy websites
Johnnyfuede
1 Nov 25 at 10:25 am
mostbet лицензия [url=https://mostbet12033.ru/]mostbet лицензия[/url]
mostbet_kg_fjpa
1 Nov 25 at 10:26 am