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=www.natyazhnye-potolki-nizhniy-novgorod-1.ru]потолочкин натяжные потолки нижний новгород[/url] .
natyajnie potolki nijnii novgorod_nlma
2 Nov 25 at 11:57 pm
1xbet giri? adresi [url=http://1xbet-giris-5.com]1xbet giri? adresi[/url] .
1xbet giris_oySa
2 Nov 25 at 11:57 pm
Alas, lacking strong maths іn Junior College, even leading institution youngsters сould stumble in next-level equations, tһus build tһis immediɑtely
leh.
Nanyang Junior College champions multilingual quality, blending cultural heritage ѡith modern education tⲟ support confident international citizens.
Advanced facilities support strong programs іn STEM, arts,
and liberal arts, promoting innovation аnd creativity.
Students prosper іn a dynamic neighborhood ԝith opportunities fоr leadership and global exchanges.
Τһe college’semphasis оn values аnd durability develops character
alongside scholastic expertise. Graduates master leading
organizations, carrying forward а tradition of achievement аnd cultural appreciation.
Jurong Pioneer Junior College, developed tһrough the thoughtful merger ߋf Jurong Junior College ɑnd Pioneer Junior College,
рrovides a progressive аnd future-oriented education tһat
plaϲеs a special focus ᧐n China readiness, worldwide business
acumen, and cross-cultural engagement tο prepare trainees fⲟr thriving іn Asia’s vibrant financial
landscape. Ꭲhe college’ѕ dual campuses аrе equipped ԝith modern-dаy, versatile centers including
specialized commerce simulation spaces, science innovation laboratories,
annd arts ateliers, аll designed tо promote practical skills, creativity,
аnd interdisciplinary knowing. Improving academic programs аre
matched bу global cooperations, such as joint jobs with Chinese universities аnd cultural immersion trips, ѡhich boost students’ linguistic efficiency аnd global outlook.
Ꭺ helpful ɑnd inclusive community atmosphere encourages durability
аnd management development tһrough а vast array of cⲟ-curricular activities, fгom entrepreneurship
clubѕ to sports teams tһat promote team effort
ɑnd perseverance. Graduates ߋf Jurong Pioneer Junior College агe incredibly well-prepared for competitive professions, embodying tһe values of care, constant improvement, and development tһat define the institution’ѕ positive values.
Oi oi, Singapore moms аnd dads, math proves ρrobably the most crucial primary discipline,
promoting imagination іn issue-resolving fоr creative careers.
Don’t play play lah, combine ɑ good Junior College ᴡith mathematics superiority
to guarantee high A Levels scores aѕ welⅼ аs seamless shifts.
Parents, competitive style engaged lah, strong primary
mathematics guides tо better science comprehension ɑnd construction dreams.
Wow, math is the foundation block іn primary learning, helping children іn dimensional reasoning to architecture paths.
Ꭺ-level distinctions in core subjects lіke Math sеt you
apart from the crowd.
Don’t take lightly lah, combine ɑ excellent Junior College plkus math excellence
іn order to ensure superior A Levels marks ɑѕ ѡell as effortless shifts.
Αlso visit my website Spectra Secondary
Spectra Secondary
3 Nov 25 at 12:03 am
потолочкин ру нижний новгород [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru]https://natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_jkma
3 Nov 25 at 12:03 am
1xbet guncel [url=https://1xbet-giris-6.com/]1xbet guncel[/url] .
1xbet giris_rbsl
3 Nov 25 at 12:05 am
1xbet com giri? [url=1xbet-giris-5.com]1xbet-giris-5.com[/url] .
1xbet giris_znSa
3 Nov 25 at 12:06 am
купить свидетельство о рождении ссср [url=www.rudik-diplom1.ru/]купить свидетельство о рождении ссср[/url] .
Diplomi_aler
3 Nov 25 at 12:08 am
натяжные потолки сайт [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru/]натяжные потолки сайт[/url] .
natyajnie potolki nijnii novgorod_otma
3 Nov 25 at 12:10 am
buy medications online safely [url=https://safemedsguide.shop/#]promo codes for online drugstores[/url] compare online pharmacy prices
Hermanengam
3 Nov 25 at 12:11 am
I am extremely impressed with your writing skills as well
as with the layout on your weblog. Is this a paid theme
or did you modify it yourself? Either way keep up the excellent quality writing,
it is rare to see a nice blog like this one nowadays.
daga
3 Nov 25 at 12:12 am
https://nevainstrument.ru/
WillieNok
3 Nov 25 at 12:13 am
натяжные потолки официальный [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru/]натяжные потолки официальный[/url] .
natyajnie potolki nijnii novgorod_ajma
3 Nov 25 at 12:14 am
купить диплом журналиста [url=http://rudik-diplom1.ru]купить диплом журналиста[/url] .
Diplomi_gjer
3 Nov 25 at 12:14 am
1xbet lite [url=https://www.1xbet-giris-5.com]https://www.1xbet-giris-5.com[/url] .
1xbet giris_glSa
3 Nov 25 at 12:14 am
1xbet mobil giri? [url=1xbet-giris-5.com]1xbet-giris-5.com[/url] .
1xbet giris_zcSa
3 Nov 25 at 12:16 am
best Irish pharmacy websites [url=https://irishpharmafinder.shop/#]Irish Pharma Finder[/url] best Irish pharmacy websites
Hermanengam
3 Nov 25 at 12:17 am
купить диплом в нижнем новгороде [url=https://www.rudik-diplom1.ru]купить диплом в нижнем новгороде[/url] .
Diplomi_zjer
3 Nov 25 at 12:19 am
рейтинг seo агентств [url=www.luchshie-digital-agencstva.ru]рейтинг seo агентств[/url] .
lychshie digital agentstva_uioi
3 Nov 25 at 12:20 am
1xbet giri?i [url=https://1xbet-giris-6.com]1xbet giri?i[/url] .
1xbet giris_qisl
3 Nov 25 at 12:21 am
потолки [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru]потолки[/url] .
natyajnie potolki nijnii novgorod_nlma
3 Nov 25 at 12:22 am
1xbet resmi sitesi [url=www.1xbet-giris-5.com/]www.1xbet-giris-5.com/[/url] .
1xbet giris_oaSa
3 Nov 25 at 12:22 am
There is certainly a lot to find out about this topic.
I really like all the points you made.
수원출장마사지
3 Nov 25 at 12:24 am
Кто делал дератизация цена холодным туманом? Эффективно ли?
уничтожение блох
KennethceM
3 Nov 25 at 12:24 am
https://t.me/s/UD_VODKA
AlbertTeery
3 Nov 25 at 12:24 am
irishpharmafinder: trusted online pharmacy Ireland – discount pharmacies in Ireland
Johnnyfuede
3 Nov 25 at 12:25 am
ANAK JEMBOT
ANAK JEMBOT
3 Nov 25 at 12:25 am
потолочник натяжные потолки отзывы [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru]потолочник натяжные потолки отзывы[/url] .
natyajnie potolki nijnii novgorod_lkma
3 Nov 25 at 12:28 am
1xbet tr [url=https://1xbet-giris-2.com/]1xbet tr[/url] .
1xbet giris_nvPt
3 Nov 25 at 12:28 am
1xbet mobil giri? [url=http://1xbet-giris-2.com]http://1xbet-giris-2.com[/url] .
1xbet giris_udPt
3 Nov 25 at 12:32 am
рейтинг сео компаний [url=www.reiting-seo-kompanii.ru/]рейтинг сео компаний[/url] .
reiting seo kompanii_qcsn
3 Nov 25 at 12:33 am
1xbet com giri? [url=http://1xbet-giris-5.com]http://1xbet-giris-5.com[/url] .
1xbet giris_rfSa
3 Nov 25 at 12:35 am
thinkbigmovefast – Loving the bold approach and clean design, feels refreshing.
Blondell Minteer
3 Nov 25 at 12:36 am
bahis sitesi 1xbet [url=https://1xbet-giris-5.com/]bahis sitesi 1xbet[/url] .
1xbet giris_nzSa
3 Nov 25 at 12:37 am
потолочкин натяжные потолки нижний новгород [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru]потолочкин натяжные потолки нижний новгород[/url] .
natyajnie potolki nijnii novgorod_pkma
3 Nov 25 at 12:38 am
UkMedsGuide: affordable medications UK – affordable medications UK
HaroldSHems
3 Nov 25 at 12:38 am
https://t.me/s/UD_DriP
AlbertTeery
3 Nov 25 at 12:38 am
https://t.me/s/ud_monro
AlbertTeery
3 Nov 25 at 12:39 am
купить диплом в ессентуках [url=http://rudik-diplom1.ru]купить диплом в ессентуках[/url] .
Diplomi_vier
3 Nov 25 at 12:39 am
cheap medicines online UK: legitimate pharmacy sites UK – UkMedsGuide
Johnnyfuede
3 Nov 25 at 12:42 am
1xbet giri? linki [url=www.1xbet-giris-6.com/]1xbet giri? linki[/url] .
1xbet giris_oosl
3 Nov 25 at 12:42 am
1xbet mobi [url=http://1xbet-giris-5.com]http://1xbet-giris-5.com[/url] .
1xbet giris_roSa
3 Nov 25 at 12:42 am
1xbet tr [url=https://1xbet-giris-2.com/]1xbet tr[/url] .
1xbet giris_yqPt
3 Nov 25 at 12:43 am
1xbet resmi giri? [url=https://1xbet-giris-5.com/]https://1xbet-giris-5.com/[/url] .
1xbet giris_bbSa
3 Nov 25 at 12:45 am
J’ai une passion debordante pour Frumzi Casino, il cree une experience captivante. On trouve une gamme de jeux eblouissante, comprenant des titres adaptes aux cryptomonnaies. Le bonus de bienvenue est genereux. Le suivi est d’une fiabilite exemplaire. Les transactions sont d’une fiabilite absolue, occasionnellement des bonus plus frequents seraient un hit. Pour faire court, Frumzi Casino offre une experience hors du commun. Pour couronner le tout la plateforme est visuellement electrisante, permet une plongee totale dans le jeu. A souligner les paiements securises en crypto, renforce la communaute.
Voir les dГ©tails|
starwaveik9zef
3 Nov 25 at 12:46 am
cheap medicines online Australia: AussieMedsHubAu – pharmacy discount codes AU
HaroldSHems
3 Nov 25 at 12:47 am
Je suis accro a Cheri Casino, ca invite a l’aventure. La bibliotheque est pleine de surprises, avec des slots aux designs captivants. Il rend le debut de l’aventure palpitant. Les agents sont rapides et pros. Les paiements sont securises et rapides, mais encore des offres plus genereuses rendraient l’experience meilleure. Dans l’ensemble, Cheri Casino offre une aventure memorable. Notons aussi la plateforme est visuellement vibrante, facilite une experience immersive. Egalement top le programme VIP avec des avantages uniques, renforce la communaute.
Aller sur le site|
wildmindok4zef
3 Nov 25 at 12:47 am
Je suis totalement conquis par Wild Robin Casino, c’est une plateforme qui pulse avec energie. Le choix de jeux est tout simplement enorme, comprenant des titres adaptes aux cryptomonnaies. Il rend le debut de l’aventure palpitant. Le support est fiable et reactif. Le processus est fluide et intuitif, cependant des bonus plus varies seraient un plus. Globalement, Wild Robin Casino est un choix parfait pour les joueurs. En extra le design est tendance et accrocheur, facilite une immersion totale. Un point fort les evenements communautaires vibrants, propose des privileges sur mesure.
Wild Robin|
globalflowis1zef
3 Nov 25 at 12:48 am
Je suis completement seduit par Instant Casino, il procure une sensation de frisson. Le catalogue est un tresor de divertissements, offrant des sessions live palpitantes. Il donne un elan excitant. Les agents sont rapides et pros. Les gains arrivent sans delai, mais des recompenses additionnelles seraient ideales. Pour finir, Instant Casino assure un fun constant. Pour couronner le tout le design est tendance et accrocheur, amplifie l’adrenaline du jeu. A mettre en avant les paiements securises en crypto, offre des bonus exclusifs.
http://www.instantcasino366fr.com|
Swiftforceor8zef
3 Nov 25 at 12:48 am
UK online pharmacies list: best UK pharmacy websites – affordable medications UK
Johnnyfuede
3 Nov 25 at 12:50 am
потолочкин потолки натяжные [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru/]http://natyazhnye-potolki-nizhniy-novgorod-1.ru/[/url] .
natyajnie potolki nijnii novgorod_nmma
3 Nov 25 at 12:50 am