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://www.rudik-diplom2.ru]https://www.rudik-diplom2.ru[/url] .
Diplomi_brpi
15 Oct 25 at 6:55 am
купить диплом в краснодаре [url=http://rudik-diplom7.ru]купить диплом в краснодаре[/url] .
Diplomi_gsPl
15 Oct 25 at 6:55 am
купить диплом техникума дешево [url=frei-diplom9.ru]купить диплом техникума дешево[/url] .
Diplomi_sjea
15 Oct 25 at 6:56 am
купить диплом техникума 1997 [url=http://frei-diplom7.ru/]купить диплом техникума 1997[/url] .
Diplomi_sbei
15 Oct 25 at 6:56 am
Как быстро запускается
Подробнее тут – [url=https://narkologicheskaya-pomoshch-orekhovo-zuevo7.ru/]наркологическая помощь[/url]
Jeremyovepe
15 Oct 25 at 6:57 am
купить диплом агронома [url=https://rudik-diplom6.ru/]купить диплом агронома[/url] .
Diplomi_xgKr
15 Oct 25 at 6:57 am
купить диплом в кирово-чепецке [url=https://rudik-diplom9.ru/]https://rudik-diplom9.ru/[/url] .
Diplomi_knei
15 Oct 25 at 6:58 am
By connecting mathematics tⲟ imaginative jobs, OMT stirs
up ɑ passion in pupils, encouraging thеm to
accept the subject and strive fߋr test proficiency.
Register todaү in OMT’ѕ standalone e-learning programs ɑnd
watch үоur grades skyrocket tһrough unlimited access
to premium, syllabus-aligned сontent.
Thе holistic Singapore Math approach, ԝhich develops multilayered analytical capabilities, underscores ᴡhy math tuition іѕ
essential for mastering tһe curriculum аnd ցetting ready for future careers.
Ƭhrough math tuition, trainees practice PSLE-style concerns սsually
ɑnd graphs, enhancing accuracy and speed undeг
exam conditions.
Routine mock O Level tests іn tuition settings imitate genuine problemѕ, enabling
students tο fine-tune thеir approach ɑnd decrease mistakes.
Ꮤith A Levels demanding proficiency іn vectors and complex numbeгs, math tuition ցives targeted practice to deal ѡith these abstract principles efficiently.
OMT’ѕ special curriculum, crafted t᧐ sustain tһe MOE
syllabus, consists ⲟf customized components tһat adapt
to specific knowing designs fοr more reliable math mastery.
OMT’ѕ online tuition saves cash on transport lah, permitting еven moгe
focus on гesearch studies ɑnd enhanced math гesults.
Math tuition aids Singapore students conquer typical risks іn calculations, causing
ⅼess careless errors іn exams.
my web page :: ib math tutor
ib math tutor
15 Oct 25 at 6:59 am
https://telegra.ph/Kupit-fpv-dron-bu-10-12-3
RonaldZer
15 Oct 25 at 7:00 am
купить диплом дорожного техникума [url=http://frei-diplom8.ru/]купить диплом дорожного техникума[/url] .
Diplomi_jksr
15 Oct 25 at 7:00 am
https://www.wowonder.xyz/read-blog/330125
eoqjyik
15 Oct 25 at 7:00 am
купить диплом с занесением в реестр вуза [url=https://frei-diplom1.ru]купить диплом с занесением в реестр вуза[/url] .
Diplomi_exOi
15 Oct 25 at 7:00 am
куплю диплом младшей медсестры [url=www.frei-diplom13.ru]www.frei-diplom13.ru[/url] .
Diplomi_pakt
15 Oct 25 at 7:01 am
купить диплом в выборге [url=www.rudik-diplom2.ru/]www.rudik-diplom2.ru/[/url] .
Diplomi_lypi
15 Oct 25 at 7:01 am
купить диплом в кургане [url=http://rudik-diplom10.ru]купить диплом в кургане[/url] .
Diplomi_tpSa
15 Oct 25 at 7:02 am
купить речной диплом [url=https://rudik-diplom7.ru]купить речной диплом[/url] .
Diplomi_foPl
15 Oct 25 at 7:02 am
купить диплом с техникума [url=http://frei-diplom9.ru/]купить диплом с техникума[/url] .
Diplomi_jaea
15 Oct 25 at 7:03 am
купить диплом в муроме [url=https://rudik-diplom13.ru]купить диплом в муроме[/url] .
Diplomi_apon
15 Oct 25 at 7:03 am
купить диплом в братске [url=https://rudik-diplom6.ru/]купить диплом в братске[/url] .
Diplomi_tfKr
15 Oct 25 at 7:05 am
купить диплом с проводкой моих [url=http://www.frei-diplom2.ru]купить диплом с проводкой моих[/url] .
Diplomi_fxEa
15 Oct 25 at 7:06 am
купить диплом с занесением в реестр в архангельске [url=https://frei-diplom3.ru]купить диплом с занесением в реестр в архангельске[/url] .
Diplomi_ruKt
15 Oct 25 at 7:06 am
диплом медсестры с аккредитацией купить [url=www.frei-diplom13.ru/]диплом медсестры с аккредитацией купить[/url] .
Diplomi_wgkt
15 Oct 25 at 7:06 am
Small-grоup on-site cllasses at OMT ⅽreate ɑ supportive neighborhood where students share mathematics discoveries, firing ᥙp
a love for the topic that drives them t᧐ward test
success.
Established іn 2013 by Mr. Justin Tan, OMT Math
Tuition һаѕ actually assisted numerous trainees ace examinations ⅼike PSLE, O-Levels, and A-Levels with proven рroblem-solving methods.
Ρrovided tһаt mathematics plays an essential role іn Singapore’s financial advancement аnd
development, purchasing specialized math tuition equips
students ԝith tһe problem-solving abilities needed to flourish іn a
competitive landscape.
Math tuition helps primary sfhool trainees stand оut
іn PSLE by strengthening tһe Singapore Math curriculum’s bar modeling technique fоr visual
analytical.
Introducing heuristic methods еarly in secondary tuition prepares students fоr thе non-routine troubles tһat ߋften ѕhow up in O Level assessments.
Τhrough normal simulated examinations ɑnd comprehensive feedback, tuition assists junior university student recognize ɑnd fix weak poіnts prior to
tһe actual Α Levels.
OMT’s custom-designed curriculum uniquely enhances tһe MOE framework by ցiving
thematic units that connect math topics ɑcross primary to JC levels.
Personalized progression tracking іn OMT’s syѕtеm reveals your
weak areas ѕia, allowing targeted practice fօr grade improvement.
Customized math tuition addresses specific weak рoints, transforming typical performers гight into examination toppers
in Singapore’s merit-based ѕystem.
My web site; h2 math tuition
h2 math tuition
15 Oct 25 at 7:10 am
купить диплом в вольске [url=http://rudik-diplom10.ru]http://rudik-diplom10.ru[/url] .
Diplomi_kbSa
15 Oct 25 at 7:10 am
https://profile.hatena.ne.jp/Otello/profile
Nathanhip
15 Oct 25 at 7:14 am
купить диплом в новом уренгое [url=rudik-diplom9.ru]rudik-diplom9.ru[/url] .
Diplomi_gnei
15 Oct 25 at 7:15 am
купить диплом в кургане [url=rudik-diplom10.ru]купить диплом в кургане[/url] .
Diplomi_ucSa
15 Oct 25 at 7:16 am
https://parker8n30hpw6.wikicorrespondence.com/user
qbwsmdp
15 Oct 25 at 7:17 am
купить диплом украина с занесением в реестр [url=http://www.frei-diplom1.ru]http://www.frei-diplom1.ru[/url] .
Diplomi_tlOi
15 Oct 25 at 7:17 am
купить диплом в чебоксарах [url=https://rudik-diplom13.ru/]купить диплом в чебоксарах[/url] .
Diplomi_ivon
15 Oct 25 at 7:18 am
москва купить диплом о высшем образовании с занесением в реестр [url=http://frei-diplom3.ru/]москва купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_gjKt
15 Oct 25 at 7:19 am
купить диплом занесенный реестр [url=www.frei-diplom2.ru/]купить диплом занесенный реестр[/url] .
Diplomi_olEa
15 Oct 25 at 7:19 am
натяжные потолки в самаре [url=https://natyazhnye-potolki-samara-2.ru]натяжные потолки в самаре[/url] .
natyajnie potolki samara_cuPi
15 Oct 25 at 7:19 am
купить диплом охранника [url=http://www.rudik-diplom2.ru]купить диплом охранника[/url] .
Diplomi_ehpi
15 Oct 25 at 7:22 am
Формат
Получить дополнительные сведения – https://narkologicheskaya-pomoshch-orekhovo-zuevo7.ru/kruglosutochnaya-narkologicheskaya-pomoshch-v-orekhovo-zuevo/
Jeremyovepe
15 Oct 25 at 7:22 am
Hey, I think your website might be having browser compatibility issues.
When I look at your website in Ie, it looks fine but when opening in Internet Explorer,
it has some overlapping. I just wanted to give you a quick heads up!
Other then that, superb blog!
Måne Fundexis
15 Oct 25 at 7:22 am
купить диплом техникума легкой промышленности [url=http://www.frei-diplom12.ru]купить диплом техникума легкой промышленности[/url] .
Diplomi_lzPt
15 Oct 25 at 7:22 am
I was able to find good information from your content.
TV88
15 Oct 25 at 7:23 am
Как работает
Детальнее – [url=https://kodirovanie-ot-alkogolizma-vidnoe7.ru/]кодирование от алкоголизма на дому в видном[/url]
Georgepat
15 Oct 25 at 7:23 am
натяжные потолки дешево самара [url=http://natyazhnye-potolki-samara-2.ru/]натяжные потолки дешево самара[/url] .
natyajnie potolki samara_ylPi
15 Oct 25 at 7:23 am
купить легальный диплом колледжа [url=http://frei-diplom1.ru]купить легальный диплом колледжа[/url] .
Diplomi_gyOi
15 Oct 25 at 7:25 am
купить диплом железнодорожника [url=http://rudik-diplom7.ru/]купить диплом железнодорожника[/url] .
Diplomi_dwPl
15 Oct 25 at 7:27 am
купить диплом техникума с занесением в реестр форум [url=www.frei-diplom9.ru]купить диплом техникума с занесением в реестр форум[/url] .
Diplomi_jbea
15 Oct 25 at 7:28 am
https://telegra.ph/Dji-mini-3-pro-kupit-moskva-10-13-4
RonaldZer
15 Oct 25 at 7:31 am
купить диплом с занесением в реестр новокузнецке [url=https://frei-diplom2.ru/]купить диплом с занесением в реестр новокузнецке[/url] .
Diplomi_rjEa
15 Oct 25 at 7:31 am
купить диплом о среднем профессиональном образовании с занесением в реестр [url=https://www.frei-diplom3.ru]купить диплом о среднем профессиональном образовании с занесением в реестр[/url] .
Diplomi_yqKt
15 Oct 25 at 7:31 am
купить диплом медсестры [url=https://frei-diplom13.ru/]купить диплом медсестры[/url] .
Diplomi_mhkt
15 Oct 25 at 7:31 am
Refresh Renovation Southwest Charlotte
1251Arro Pine Ɗr c121,
Charlotte, NC 28273, United Տtates
+19803517882
Bookmarks
Bookmarks
15 Oct 25 at 7:32 am
Nice blog here! Also your site loads up fast! What web host are you
using? Can I get your affiliate link to your host?
I wish my web site loaded up as quickly as yours lol
Redford Bitspire Legit Or Not
15 Oct 25 at 7:35 am
Great article! This is the kind of info that should be shared across the net.
Shame on the search engines for not positioning this publish higher!
Come on over and visit my website . Thanks =)
Bitnex Crestfort
15 Oct 25 at 7:35 am