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!
Have you ever considered about including a little bit more than just your articles?
I mean, what you say is valuable and everything.
Nevertheless just imagine if you added some great visuals or videos
to give your posts more, “pop”! Your content is excellent
but with images and clips, this blog could certainly be one of
the very best in its niche. Awesome blog!
hiếp dâm không bao
30 Oct 25 at 3:37 am
seo курсы [url=kursy-seo-11.ru]seo курсы[/url] .
kyrsi seo_avEl
30 Oct 25 at 3:37 am
купить диплом в оренбурге [url=rudik-diplom6.ru]купить диплом в оренбурге[/url] .
Diplomi_tyKr
30 Oct 25 at 3:37 am
купить вирт номер навсегда
купить вирт номер навсегда
30 Oct 25 at 3:38 am
It is not my first time to visit this site, i am browsing this site dailly and
take nice data from here daily.
florist bali
30 Oct 25 at 3:40 am
kamagra: Kamagra livraison rapide en France – Kamagra 100mg prix France
RobertJuike
30 Oct 25 at 3:41 am
seo бесплатно [url=http://kursy-seo-11.ru/]seo бесплатно[/url] .
kyrsi seo_gdEl
30 Oct 25 at 3:42 am
Hello everyone, it’s my first visit at this web site, and article is actually fruitful in support of me,
keep up posting these posts.
Elite Touch Mobile Detailing & Ceramic Coatings
30 Oct 25 at 3:43 am
Если нужен профессиональный вывод из запоя, обращайтесь в клинику «ЧСП№1» в Ростове-на-Дону. Врачи работают круглосуточно.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-rostov11.ru/]вывод из запоя на дому цена в ростове-на-дону[/url]
Elijahenuts
30 Oct 25 at 3:43 am
Kamagra Oral Jelly Deutschland: Potenzmittel ohne ärztliches Rezept – vitalpharma24
ThomasCep
30 Oct 25 at 3:45 am
Hello, all is going fine here and ofcourse every
one is sharing information, that’s in fact excellent, keep up writing.
mellstroy casino
30 Oct 25 at 3:45 am
localphlmarket.com – Looking forward to seeing what new products drop next — very impressed overall.
Violeta Seils
30 Oct 25 at 3:46 am
https://vitalpharma24.com/# vital pharma 24
Davidjealp
30 Oct 25 at 3:46 am
seo специалист [url=www.kursy-seo-11.ru/]seo специалист[/url] .
kyrsi seo_igEl
30 Oct 25 at 3:47 am
garymasino.com – I appreciate the clear presentation of his specialties and industry experience.
Rodrigo Salameh
30 Oct 25 at 3:49 am
купить диплом техникума ссср в кемерово [url=http://frei-diplom12.ru/]купить диплом техникума ссср в кемерово[/url] .
Diplomi_juPt
30 Oct 25 at 3:50 am
Besides to institution amenities, focus ԝith maths іn ordеr to
stoρ frequent pitfalls ⅼike careless blunders аt tests.
Mums and Dads, kiasu approach оn lah, robust primary mathematics leads іn improved science grasp
ɑs well as tech dreams.
Anglo-Chinese Junior College stands аs a beacon of balanced
education, blending extensive academics ѡith a nurturing Christian ethos tһat motivates ethical integrity ɑnd personal growth.
Тhe college’s state-օf-the-art centers and skilled faculty assistance outstanding performance іn botһ arts
and sciences, ᴡith students frequently attaining tߋp distinctions.
Througһ its focus on sports and performing arts, students establish discipline, friendship,
аnd an enthusiasm for quality bеyond the class. International partnerships аnd exchange opportunities improve the learning
experience, promoting international awareness and
cultural appreciation. Alumni prosper іn diverse fields, testimony tօ tһe
college’s function in forming principled leaders
аll set to contribute favorably to society.
Catholic Junior College ρrovides a transformative instructional experience fixated
classic values оf compassion, stability, аnd pursuit of truth, cultivating а close-knit
neighborhood whhere students feel supported ɑnd inspired to grow bоth intellectually аnd spiritually іn a
peaceful and inclusive setting. Τhе college pгovides extensive
scholastic programs іn the humanities, sciences, and social sciences, delivered Ьy
enthusiastic аnd knowledgeable mentors ԝhօ employ innovative mentor ɑpproaches to stimulate curiosity ɑnd
motivate deep, meaningful learning tһat extends fɑr bеyond examinations.
Аn lively selection ᧐f co-curricular activities, including competitive sports ցroups thаt promote physical health аnd sociability, along
with creative societies tһat support imaginative expression tһrough drama аnd visual arts,
mɑkes it possible for students to explore their interests аnd establish weⅼl-rounded personalities.
Opportunities fߋr ѕignificant community service, ѕuch аs partnerships ѡith regional charities and worldwide humanitarian trips, assist construct empathy, leadership skills, ɑnd
a genuine commitment tο making a distinction in the lives of otһers.
Alumni from Catholic Junior College regularly Ьecome thoughtful and ethical leaders іn numerous professional fields, geared սp witһ tһe knowledge,
strength, аnd ethical compass to contribute favorably ɑnd sustainably tо society.
Ɗo not mess around lah, link ɑ excellent Junior College alongside math proficiency іn orԁer to ensure һigh Ꭺ Levels scores аnd effortless transitions.
Parents, dread tһe gap hor, math groundwork is essential duгing Junior College tо
understanding figures, essential fߋr tοday’sdigital system.
Aρart beʏond school resources, emphasize ⲟn math in оrder to prevent common errors ⅼike sloppy errors at tests.
Folks, fearful ߋf losing style engaged lah, solid primary math leads tо superior STEM comprehension рlus tech
aspirations.
Вesides tⲟ school facilities, concentrate ԝith math tⲟ stop
common mistakes lіke careless errors in tests.
Mums аnd Dads, kiasu mode оn lah, strong primary maths гesults for improved scientific understanding
рlus engineering goals.
Wow, maths іs the base block fоr primary education, helping children іn spatial analysis
fⲟr architecture paths.
Math trains ʏou tto thіnk critically, a must-have in our fast-paced
worⅼd lah.
Αvoid tɑke liightly lah, link а reputable Junior College ԝith maths superiority tߋ assure superior А Levels marks and smooth
transitions.
Feel free tߋ surf to my ρage :: St. Andrew’s Junior College
St. Andrew’s Junior College
30 Oct 25 at 3:50 am
seo курсы [url=https://www.kursy-seo-11.ru]seo курсы[/url] .
kyrsi seo_uiEl
30 Oct 25 at 3:54 am
electcateriarmccabe.com – Donation and contact pages are easy to find, very user-friendly.
Eugenio Coore
30 Oct 25 at 3:54 am
диплом медсестры с занесением в реестр купить [url=http://frei-diplom3.ru/]диплом медсестры с занесением в реестр купить[/url] .
Diplomi_mtKt
30 Oct 25 at 3:55 am
Ich schatze die Energie bei Cat Spins Casino, es sorgt fur ein fesselndes Erlebnis. Es gibt unzahlige packende Spiele, mit spannenden Sportwetten-Angeboten. Er macht den Start aufregend. Verfugbar 24/7 fur alle Fragen. Der Prozess ist transparent und schnell, in seltenen Fallen waren mehr Bonusvarianten ein Plus. Alles in allem, Cat Spins Casino bietet ein unvergleichliches Erlebnis. Daruber hinaus die Oberflache ist benutzerfreundlich, eine tiefe Immersion ermoglicht. Ein tolles Feature die lebendigen Community-Events, regelma?ige Boni bieten.
Ins Web gehen|
nightfireus1zef
30 Oct 25 at 3:56 am
happylifestylehub.shop – If you’re planning backlinks, consider waiting until the site is fully built out for better quality.
Florencio Radlinski
30 Oct 25 at 3:56 am
Sildenafil générique: Kamagra livraison rapide en France – Kamagra pas cher France
RobertJuike
30 Oct 25 at 3:58 am
Kamagra Wirkung und Nebenwirkungen: Erfahrungen mit Kamagra 100mg – Potenzmittel ohne ärztliches Rezept
ThomasCep
30 Oct 25 at 3:58 am
FarmaciaViva: pillole per disfunzione erettile – Spedra
ClydeExamp
30 Oct 25 at 3:59 am
seo курсы [url=https://kursy-seo-11.ru/]seo курсы[/url] .
kyrsi seo_byEl
30 Oct 25 at 3:59 am
купить диплом об окончании техникума в оренбурге [url=https://www.frei-diplom12.ru]купить диплом об окончании техникума в оренбурге[/url] .
Diplomi_krPt
30 Oct 25 at 4:00 am
I am genuinely grateful to the holder of this website who has shared this fantastic piece of writing at here.
Swap Edex X
30 Oct 25 at 4:01 am
постоянный виртуальный номер телефона
постоянный виртуальный номер телефона
30 Oct 25 at 4:03 am
купить диплом в кургане занесением в реестр [url=www.frei-diplom3.ru]купить диплом в кургане занесением в реестр[/url] .
Diplomi_pdKt
30 Oct 25 at 4:03 am
Avanafil senza ricetta: Avanafil senza ricetta – Avanafil senza ricetta
ClydeExamp
30 Oct 25 at 4:06 am
What’s up, after reading this awesome article i am as well delighted to share my familiarity here
with colleagues.
roobet withdrawal processing time
30 Oct 25 at 4:06 am
VitaHomme: kamagra – kamagra oral jelly
RobertJuike
30 Oct 25 at 4:06 am
This post presents clear idea in favor of the new viewers of
blogging, that really how to do running a blog.
site
30 Oct 25 at 4:06 am
школа seo [url=www.kursy-seo-11.ru]www.kursy-seo-11.ru[/url] .
kyrsi seo_cjEl
30 Oct 25 at 4:07 am
где купить диплом медицинского колледжа [url=http://frei-diplom12.ru]http://frei-diplom12.ru[/url] .
Diplomi_bePt
30 Oct 25 at 4:07 am
Hey There. I discovered your blog the use of msn. This
is a really smartly written article. I’ll make sure to bookmark it and come
back to learn extra of your useful information. Thanks for the
post. I’ll definitely comeback.
airmatic Malaysia
30 Oct 25 at 4:11 am
Нужно было создавать изображения для соцсетей регулярно, и этот генератор стал идеальным решением. Быстро, качественно и без сложных настроек. Рекомендую всем контент-мейкерам: https://vc.ru/top_rating/2301994-luchshie-besplatnye-nejroseti-dlya-generatsii-izobrazheniy
MichaelPrion
30 Oct 25 at 4:12 am
seo с нуля [url=http://kursy-seo-11.ru]http://kursy-seo-11.ru[/url] .
kyrsi seo_zuEl
30 Oct 25 at 4:13 am
Kamagra livraison rapide en France: Kamagra livraison rapide en France – Kamagra 100mg prix France
RobertJuike
30 Oct 25 at 4:15 am
I all the time used to read piece of writing in news papers but now as I am a user of web so from now I am using net for articles or reviews, thanks to web.
pool abdeckplanen online bestellen
30 Oct 25 at 4:16 am
trustedleaderscircle.bond – Overall a promising resource for connecting leaders and fostering growth.
Tad Billiter
30 Oct 25 at 4:16 am
горный техникум диплом купить [url=https://frei-diplom12.ru]горный техникум диплом купить[/url] .
Diplomi_lhPt
30 Oct 25 at 4:17 am
купить диплом о высшем образовании с занесением в реестр в калуге [url=www.frei-diplom3.ru/]купить диплом о высшем образовании с занесением в реестр в калуге[/url] .
Diplomi_smKt
30 Oct 25 at 4:20 am
https://amunra-gr.com/
1-gocasino.com
30 Oct 25 at 4:22 am
Erfahrungen mit Kamagra 100mg: Potenzmittel ohne ärztliches Rezept – diskrete Lieferung per DHL
RichardImmon
30 Oct 25 at 4:23 am
Greetings I am so grateful I found your webpage, I really found you by mistake, while I was researching on Aol for
something else, Nonetheless I am here now and would just like to
say many thanks for a tremendous post and a all
round exciting blog (I also love the theme/design), I don’t have time to look
over it all at the moment but I have book-marked it and also included your
RSS feeds, so when I have time I will be back to read much more,
Please do keep up the great job.
casino starda
30 Oct 25 at 4:24 am
newhorizonsnetwork.shop – The shopping layout is intuitive and browsing through items was smooth.
Eleanor Borman
30 Oct 25 at 4:25 am
seo базовый курc [url=www.kursy-seo-11.ru/]www.kursy-seo-11.ru/[/url] .
kyrsi seo_ncEl
30 Oct 25 at 4:27 am
linebet en ligne
telecharger linebet iphone
30 Oct 25 at 4:29 am