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.rudik-diplom3.ru]купить диплом кандидата наук[/url] .
Diplomi_doei
2 Nov 25 at 12:59 pm
ラブドール 激安He glancedtimidly at but her proud countenance wore at thatmoment an expression of such gratitude and friendlines suchcomplete and unlooked-for respect (in place of the sneering looks andill-disguised contempt he had expected),that it threw him into greaterconfusion than if he had been met with abuse.
ロボット セックス
2 Nov 25 at 12:59 pm
classytrendcollection – This store has a premium look and feel—makes me excited to explore further.
Darius Boldery
2 Nov 25 at 1:01 pm
купить диплом нового образца [url=www.rudik-diplom4.ru]купить диплом нового образца[/url] .
Diplomi_ikOr
2 Nov 25 at 1:01 pm
купить диплом в дербенте [url=https://rudik-diplom14.ru]купить диплом в дербенте[/url] .
Diplomi_epea
2 Nov 25 at 1:01 pm
диплом медсестры с аккредитацией купить [url=www.frei-diplom13.ru/]диплом медсестры с аккредитацией купить[/url] .
Diplomi_urkt
2 Nov 25 at 1:02 pm
https://brockhamptonband.com
Richardlealt
2 Nov 25 at 1:02 pm
легально купить диплом о [url=https://frei-diplom6.ru/]легально купить диплом о[/url] .
Diplomi_mzOl
2 Nov 25 at 1:02 pm
If some one desires expert view regarding blogging and site-building afterward i suggest him/her to pay a quick visit this webpage,
Keep up the fastidious work.
jalalive gratis
2 Nov 25 at 1:03 pm
купить проведенный диплом кого [url=https://frei-diplom5.ru]купить проведенный диплом кого[/url] .
Diplomi_gnPa
2 Nov 25 at 1:03 pm
without my friend… And he expects me not tobe afraid. ?Her tone was now querulous and her lip drawn up,セックス ロボット
セックス ドール
2 Nov 25 at 1:04 pm
Je suis completement seduit par Cheri Casino, il cree une experience captivante. Les options de jeu sont incroyablement variees, avec des machines a sous visuellement superbes. Le bonus de depart est top. Le suivi est toujours au top. Les paiements sont surs et efficaces, cependant des bonus plus varies seraient un plus. Pour conclure, Cheri Casino est un endroit qui electrise. Pour couronner le tout la plateforme est visuellement captivante, booste le fun du jeu. Egalement genial les competitions regulieres pour plus de fun, qui dynamise l’engagement.
Naviguer sur le site|
wildmindok4zef
2 Nov 25 at 1:04 pm
топ компаний по продвижению сайтов [url=http://reiting-seo-kompaniy.ru]топ компаний по продвижению сайтов[/url] .
reiting seo kompanii_efon
2 Nov 25 at 1:04 pm
купить диплом в люберцах [url=rudik-diplom5.ru]купить диплом в люберцах[/url] .
Diplomi_akma
2 Nov 25 at 1:06 pm
1xbet giri?i [url=1xbet-giris-5.com]1xbet giri?i[/url] .
1xbet giris_ygSa
2 Nov 25 at 1:06 pm
top-rated pharmacies in Ireland: online pharmacy ireland – discount pharmacies in Ireland
Johnnyfuede
2 Nov 25 at 1:06 pm
J’ai un faible pour Cheri Casino, ca transporte dans un monde d’excitation. La bibliotheque est pleine de surprises, proposant des jeux de casino traditionnels. Il rend le debut de l’aventure palpitant. Le suivi est d’une precision remarquable. Les gains sont verses sans attendre, neanmoins des bonus diversifies seraient un atout. En fin de compte, Cheri Casino assure un divertissement non-stop. Notons egalement le site est rapide et engageant, apporte une touche d’excitation. Un bonus les evenements communautaires engageants, assure des transactions fiables.
Explorer le site web|
CityLogicar8zef
2 Nov 25 at 1:06 pm
как купить диплом с занесением в реестр в екатеринбурге [url=https://frei-diplom4.ru/]https://frei-diplom4.ru/[/url] .
Diplomi_fxOl
2 Nov 25 at 1:07 pm
можно ли купить диплом [url=http://rudik-diplom8.ru]можно ли купить диплом[/url] .
Diplomi_eqMt
2 Nov 25 at 1:07 pm
купить диплом в заречном [url=http://rudik-diplom4.ru]купить диплом в заречном[/url] .
Diplomi_fwOr
2 Nov 25 at 1:07 pm
купить диплом с занесением в реестр новокузнецке [url=http://frei-diplom6.ru/]купить диплом с занесением в реестр новокузнецке[/url] .
Diplomi_wnOl
2 Nov 25 at 1:08 pm
cheapest pharmacies in the USA [url=https://safemedsguide.com/#]compare online pharmacy prices[/url] trusted online pharmacy USA
Hermanengam
2 Nov 25 at 1:08 pm
1xbet lite [url=www.1xbet-giris-2.com]www.1xbet-giris-2.com[/url] .
1xbet giris_okPt
2 Nov 25 at 1:08 pm
In that way only it seemed to me I could keep my hold on theredeeming facts of life.Still,ラブドール えろ
えろ 人形
2 Nov 25 at 1:09 pm
pharmacy delivery Ireland [url=https://irishpharmafinder.com/#]Irish Pharma Finder[/url] Irish Pharma Finder
Hermanengam
2 Nov 25 at 1:09 pm
купить диплом техникума настоящий [url=https://www.frei-diplom8.ru]купить диплом техникума настоящий[/url] .
Diplomi_pxsr
2 Nov 25 at 1:10 pm
купить диплом техникума проведенный [url=frei-diplom10.ru]купить диплом техникума проведенный[/url] .
Diplomi_scEa
2 Nov 25 at 1:10 pm
можно ли купить диплом медсестры [url=https://www.frei-diplom14.ru]можно ли купить диплом медсестры[/url] .
Diplomi_aqoi
2 Nov 25 at 1:10 pm
agency seo [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]agency seo[/url] .
agentstvo poiskovogo prodvijeniya_teKt
2 Nov 25 at 1:11 pm
This website really has all of the information I wanted about this
subject and didn’t know who to ask.
Carwash Indonesia
2 Nov 25 at 1:13 pm
セックス ロボット.. ?and he waved his arm.Pierre took off his spectacle which made his face seem different andthe good-natured expression still more apparent,and gazed at his friendin amazement.
セックス ドール
2 Nov 25 at 1:13 pm
Hey hey, steady pom ρi pі, maths іs part in the leading disciplines Ԁuring
Junior College, biilding foundation fօr А-Level
advanced math.
Ιn additіon to school facilities, emphasize on math for prevent common mistakes ѕuch as sloppy
blunders at assessments.
Folks, kiasu approach on lah, robust primary math leads tօ superior STEM grasp ɑѕ well as construction aspirations.
Hwa Chong Institution Junior College іs renowned fοr itѕ integrated program tһat effortlessly combines academic
rigor ԝith character development, producing worldwide scholars ɑnd leaders.
World-class centers and skilled professors assistance quality іn research study, entrepreneurship, аnd bilingualism.
Trainees benefit from extensive international exchanges ɑnd competitions, widening рoint of views and developing skills.
Thе organization’ѕ focus on development ɑnd service cultivates durability ɑnd ethical worths.
Alumni networks ⲟpen doors to top universities ɑnd prominent professions worldwide.
Singapore Sports School masterfully balances
fіrst-rate athletic training wіtһ a extensive academic curriculum, committed tߋ nurturing elite athletes ѡho stand out not օnly
in sports bᥙt allso in individual аnd expert life domains.
Thе school’s tailored academic pathways սse versatile
scheduling tо acommodate intensive training and competitions, ensuring trainees preserve һigh scholastic
requirements ԝhile pursuing tһeir sporting passions
ᴡith steady focus. Boasting t᧐ρ-tier centers like Olympic-standard training arenas, sports
science labs, ɑnd recovery centers, tօgether ᴡith expert training
from prominent specialists, thе institution supports peak physical performance and holistic
professional athlete development. International direct exposures tһrough
international competitions, exchange programs ԝith overseas
sports academies, ɑnd leadership workshops build durability, strategic thinking, ɑnd
comprehensive networks thаt extend beyond the playing field.
Trainees graduate аs disciplined, goal-oriented leaders, ԝell-prepared for professions іn professional sports,
sports management, оr ɡreater education, highlighting Singapore Sports School’ѕ extraordinary
function іn fostering champs οf character and achievement.
Wow, mathematics serves аs thе groundwork pillar оf primary learning, helping youngsters ѡith
geometric reasoning t᧐ architecture careers.
Alas, ᴡithout solid mathematics іn Junior College,
еven top establishment kids mіght stumble аt higһ school algebra, ѕo develop this promρtly leh.
Aiyo, mіnus solid maths during Junior College, eᴠen top institution youngsters ϲould struggle
at һigh school algebra, tһսѕ build this prоmptly leh.
Ӏn aⅾdition bеyond institution amenities, concentrate on maths in ⲟrder to stop common pitfalls
like inattentive mistakes іn tests.
High A-level grades reflect ʏоur һard work and open uр global study
abroad programs.
Hey hey, Singapore parents, maths proves ⅼikely the highly
crucial primary subject, fostering imagination tһrough challenge-tackling to innovative
jobs.
Ꭰоn’t mess around lah, combine а good Junior College ѡith mathematics superiority іn order to
ensure elevated Α Levels scores аs weⅼl as smooth changes.
My web pаge :: Damai Secondary School
Damai Secondary School
2 Nov 25 at 1:13 pm
купить диплом в брянске [url=www.rudik-diplom14.ru/]купить диплом в брянске[/url] .
Diplomi_bdea
2 Nov 25 at 1:14 pm
compare online pharmacy prices: trusted online pharmacy USA – online pharmacy
Johnnyfuede
2 Nov 25 at 1:14 pm
топ сео компаний [url=http://reiting-seo-kompaniy.ru]топ сео компаний[/url] .
reiting seo kompanii_mmon
2 Nov 25 at 1:14 pm
Increíble artículo sobre los juegos más populares de Pin-Up Casino en México.
Increíble ver cómo Pragmatic Play y Play’n GO siguen liderando con sus slots más reconocidas.
La información sobre los multiplicadores, rondas de bonificación y
pagos en cascada fue muy útil.
Recomiendo leer el artículo completo si quieres descubrir qué juegos están marcando tendencia en Pin Up Casino.
Además, me encantó que también mencionaran títulos
como Plinko y Fruit Cocktail, que ofrecen algo diferente al
jugador tradicional.
Puedes leer el artículo completo aquí y descubrir todos
los detalles sobre los juegos más jugados en Pin Up México.
opinion
2 Nov 25 at 1:14 pm
Je suis bluffe par Instant Casino, ca pulse comme une soiree animee. La selection de jeux est impressionnante, incluant des paris sportifs en direct. Le bonus d’inscription est attrayant. Disponible 24/7 pour toute question. Les paiements sont surs et fluides, en revanche des offres plus genereuses seraient top. Pour finir, Instant Casino garantit un plaisir constant. D’ailleurs le site est rapide et immersif, booste l’excitation du jeu. Un bonus les paiements securises en crypto, qui dynamise l’engagement.
Cliquez ici|
swiftpulseos5zef
2 Nov 25 at 1:14 pm
trusted online pharmacy USA [url=https://safemedsguide.shop/#]cheapest pharmacies in the USA[/url] best online pharmacy
Hermanengam
2 Nov 25 at 1:15 pm
Increíble artículo sobre los juegos más populares de Pin-Up Casino en México.
Es impresionante cómo juegos como Gates of Olympus, Sweet Bonanza y Book of Dead continúan siendo
los preferidos. Me gustó mucho cómo detallaron las mecánicas
de cada juego y sus bonificaciones.
No te pierdas la oportunidad de leer el artículo y descubrir por qué estos slots son los
favoritos entre los jugadores mexicanos.
Muy completo, ideal para quienes quieren probar tanto slots clásicos como
opciones innovadoras.
Puedes leer el artículo completo aquí y descubrir todos los detalles sobre los juegos más jugados
en Pin Up México.
press release
2 Nov 25 at 1:15 pm
диплом медсестры с аккредитацией купить [url=www.frei-diplom13.ru]диплом медсестры с аккредитацией купить[/url] .
Diplomi_nokt
2 Nov 25 at 1:16 pm
диплом техникума купить в [url=www.frei-diplom10.ru/]диплом техникума купить в[/url] .
Diplomi_zdEa
2 Nov 25 at 1:17 pm
Eh eh, calm pom pi pi hor, reputable school ᧐ffers tech groups, readying foг
tech-savvy upcoming jobs.
Eh eh, calm pom ρi ρi hor, gоod establishment οffers tech ϲlubs, prepping for IƬ-proficient upcoming roles.
Αpart fгom institution resources, concentrate on math fߋr
avoid typical mistakes ⅼike careless mistakes аt assessments.
Wah lao, no matter if establishment іs fancy,
mathematics acts ⅼike the decisive discipline fօr developing
assurance ѡith figures.
Oһ no, primary math educates real-w᧐rld applications like budgeting, sⲟ guarantee your child grasps
tһis rіght beginning eаrly.
Wah, arithmetic іs the base block оf primary learning, assisting kids fоr spatial thinking to
building careers.
Parents, dread tһe gap hor, arithmetic groundwork proves critical ԁuring primary school іn grasping figures,
vital fоr current online sуstem.
Yangzheng Primary School cultivates ɑ positive community concentrated օn extensive progress.
The school motivates achievement tһrough quality education.
Zhenghua Primary School ⲣrovides nature-inspired education.
Ꭲhe school promotes environmental awareness.
Parents ѵalue itѕ green initiatives.
my blog :: North Spring Primary School (Latasha)
Latasha
2 Nov 25 at 1:18 pm
куплю диплом младшей медсестры [url=http://frei-diplom14.ru]http://frei-diplom14.ru[/url] .
Diplomi_yyoi
2 Nov 25 at 1:18 pm
birxbet [url=1xbet-giris-4.com]1xbet-giris-4.com[/url] .
1xbet giris_wjSa
2 Nov 25 at 1:18 pm
I’m really loving the theme/design of your website. Do you ever
run into any web browser compatibility issues?
A few of my blog visitors have complained about my
site not operating correctly in Explorer but looks great in Safari.
Do you have any ideas to help fix this problem?
BET88.COM
2 Nov 25 at 1:18 pm
купить диплом с занесением в реестр отзывы [url=http://www.frei-diplom5.ru]купить диплом с занесением в реестр отзывы[/url] .
Diplomi_hvPa
2 Nov 25 at 1:18 pm
https://t.me/s/tf_1win
TracyFat
2 Nov 25 at 1:19 pm
ll think m holding on,?saidDólokhov.セックス ロボット
えろ 人形
2 Nov 25 at 1:19 pm
https://t.me/s/Top_bk_ru
TracyFat
2 Nov 25 at 1:21 pm
как купить легальный диплом [url=www.frei-diplom4.ru]www.frei-diplom4.ru[/url] .
Diplomi_ncOl
2 Nov 25 at 1:22 pm