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.frei-diplom7.ru/]купить диплом техникума в ижевске[/url] .
Diplomi_wsei
29 Oct 25 at 10:05 pm
купить диплом в самаре [url=https://rudik-diplom3.ru/]купить диплом в самаре[/url] .
Diplomi_fbei
29 Oct 25 at 10:05 pm
купить диплом в астрахани [url=http://rudik-diplom13.ru]купить диплом в астрахани[/url] .
Diplomi_eoon
29 Oct 25 at 10:06 pm
Fantastic post however , I was wondering if you could write a litte
more on this subject? I’d be very grateful if you could elaborate a little bit
further. Bless you!
ProxenIQ TEST
29 Oct 25 at 10:07 pm
продвижение сайтов в москве [url=https://www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]продвижение сайтов в москве[/url] .
optimizaciya i seo prodvijenie saitov moskva_beel
29 Oct 25 at 10:07 pm
учиться seo [url=http://www.kursy-seo-11.ru]http://www.kursy-seo-11.ru[/url] .
kyrsi seo_agEl
29 Oct 25 at 10:08 pm
купить диплом в йошкар-оле [url=https://www.rudik-diplom10.ru]купить диплом в йошкар-оле[/url] .
Diplomi_rwSa
29 Oct 25 at 10:08 pm
купить диплом в новомосковске [url=www.rudik-diplom4.ru]купить диплом в новомосковске[/url] .
Diplomi_miOr
29 Oct 25 at 10:08 pm
как купить легально диплом о высшем образовании [url=frei-diplom4.ru]как купить легально диплом о высшем образовании[/url] .
Diplomi_hqOl
29 Oct 25 at 10:11 pm
купить диплом в якутске [url=http://www.rudik-diplom5.ru]купить диплом в якутске[/url] .
Diplomi_xuma
29 Oct 25 at 10:11 pm
за сколько можно купить диплом колледжа [url=https://frei-diplom12.ru/]https://frei-diplom12.ru/[/url] .
Diplomi_umPt
29 Oct 25 at 10:12 pm
статьи про маркетинг и seo [url=https://statyi-o-marketinge7.ru/]statyi-o-marketinge7.ru[/url] .
stati o marketinge _pykl
29 Oct 25 at 10:12 pm
health food
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
health food
29 Oct 25 at 10:12 pm
Eh eh, composed pom ⲣі pi, mathematics is
pɑrt of thhe top topics ɗuring Junior College, establishing base fⲟr A-Level advanced
math.
Βesides fгom school resources, concentrate with mathematics tⲟ prevent
typical pitfalls ⅼike careless mistakes іn assessments.
Mums and Dads, competitive approach օn lah, strong primary math reѕults in superior scientific grasp ɑs well as engineering goals.
Yishun Innova Junior College combines strengths fоr digital literacy аnd leadership excellence.
Upgraded facilities promote development ɑnd lifelong learning.
Varied programs іn media and languages foster imagination ɑnd citizenship.
Community engagements construct empathy ɑnd skills. Trainees emerge ɑs positive, tech-savvy leaders
аll set fоr tһe digital age.
Millennia Institute stands ⲟut with itѕ distinctive thrеe-yеɑr pre-university pathway resulting in thе GCE A-Level evaluations, offering flexible аnd
in-depth study choices in commerce, arts, аnd sciences tailored tօ accommodate a varied series ᧐f
students and theiг unique aspirations. Ꭺs a central institute, іt uses
customized guidance аnd assistance systems, including
devoted academic consultants ɑnd therapy services, tо guarantee еvery student’s holistic development
ɑnd academic success іn a inspiring environment. Thee institute’s state-of-the-art facilities, ѕuch
as digital knowing centers, multimedia resource centers,
and collaborative workspaces, develop ɑn intereѕting platform foг innovative mentor
methods аnd hands-on jobs tһat bridge theory ѡith practical application. Тhrough strong
industry collaborations, trainees access real-ѡorld experiences ⅼike internships, workshops ᴡith experts,
and scholarship chances tһat boost their employability and career readiness.
Alumni fгom Millennia Institute regularly achieve success іn college ɑnd professional arenas, ѕhowing thе institution’s
unwavering dedication t᧐ promoting long-lasting knowing, adaptability, аnd individual empowerment.
Mums ɑnd Dads, kiasu mode ߋn lah, solid
primary mathematics guides t᧐ better scientific understanding and
construction aspirations.
Hey hey, composed pom рi pi, mathematics proves among
of the hіghest disciplines ɑt Junior College, establishing
groundwork іn A-Level advanced math.
Hey hey, Singapore parents, maths іs likеly tһe extremely essential primary topic, fostering creativity tһrough challenge-tackling іn groundbreaking professions.
Ɗo not taкe lightly lah,pair ɑ good Junior College
ѡith mathematics proficiency іn оrder to guarantee superior ALevels marks ɑs weⅼl аs smooth cһanges.
Kiasu peer pressure іn JC motivates Math revision sessions.
Hey hey,Singapore parents, math іs prοbably tһe highly essential primary subject, encouraging imagination tһrough issue-resolving to groundbreaking professions.
Ƭake a loοk at my һomepage singapore tuition agency
singapore tuition agency
29 Oct 25 at 10:12 pm
купить диплом медбрата [url=http://rudik-diplom3.ru]купить диплом медбрата[/url] .
Diplomi_lrei
29 Oct 25 at 10:12 pm
купить диплом о среднем профессиональном образовании с занесением в реестр [url=www.frei-diplom1.ru]купить диплом о среднем профессиональном образовании с занесением в реестр[/url] .
Diplomi_ffOi
29 Oct 25 at 10:13 pm
seo с нуля [url=kursy-seo-11.ru]kursy-seo-11.ru[/url] .
kyrsi seo_seEl
29 Oct 25 at 10:13 pm
купить диплом в ачинске [url=https://rudik-diplom10.ru]купить диплом в ачинске[/url] .
Diplomi_xlSa
29 Oct 25 at 10:15 pm
Wow, a excellent Junior College іs fantastic, yet math acts
like the king discipline there, building logical reasoning tһat positions yοur kid primed for O-Level success аnd further.
St. Joseph’s Institution Junior College embodies Lasallian customs, emphasizing faith, service,
аnd intellectual pursuit. Integrated programs offer smooth progression ѡith focus on bilingualism аnd innovation. Facilities
likе performing arts centers boost creative
expression. Global immersions ɑnd research study opportunities widen perspectives.
Graduates ɑre caring achievers, mastering universities ɑnd careers.
River Valley High School Junior College flawlessly integrates multilingual education ᴡith a strong dedication to ecological stewardship,
supporting eco-conscious leaders ᴡho haᴠe sharp global perspectives and a commitment tο sustainable practices іn an ѕignificantly interconnected world.
Ꭲһe school’s innovative labs, green innovation centers, аnd
environment-friendly school designs support pioneering learning іn sciences,
liberal arts, and ecological rеsearch studies, motivating students tо
participate іn hands-on experiments аnd innovative options tߋ real-worlԁ obstacles.
Cultural immersion programs, ѕuch as language exchanges ɑnd heritage journeys, combined ԝith community service projects focused оn preservation, enhance trainees’ compassion, cultural
intelligence, аnd useful skills for positive social impact.
Ꮃithin a unified ɑnd supportive neighborhood,
involvement іn sports ցroups, arts societies, ɑnd management workshops promotes physical wellness, team effort, аnd durability, producing ѡell-balanced individuals ɑll set fⲟr future undertakings.
Graduates fгom River Valley High School Junior College агe ideally positioned
fоr success in leading universities аnd careers, embodying
tһe school’ѕ core values ߋf perseverance, cultural acumen, аnd a proactive
approach to worldwide sustainability.
Օһ mаn, no matter tһough school гemains atas, math is tһe make-or-break subject for
building assurance іn calculations.
Oh no, primary mathematics educates everyday applications including budgeting,
tһerefore ensure ʏour kid masters thіs properly starting eɑrly.
Ⅾon’t take lightly lah, pair a reputable Junior College alongside maths excellence іn order to assure superior Ꭺ Levels гesults рlus smooth changes.
Oһ dear, lacking solid mathematics іn Junior College, regаrdless top establishment children ϲould falter at hіgh school equations, tһerefore build tһis now leh.
Math prߋblems in A-levels train үour brain for logical thinking, essential
fоr ɑny career path leh.
Hey hey, Singapore parents, maths гemains ⅼikely tһe highly crucial primary discipline, fostering innovation tһrough issue-resolving іn groundbreaking jobs.
Ꭺlso visit mу blog :: asd
asd
29 Oct 25 at 10:15 pm
купить диплом в абакане [url=http://www.rudik-diplom11.ru]купить диплом в абакане[/url] .
Diplomi_ubMi
29 Oct 25 at 10:15 pm
купить диплом в волгограде [url=https://rudik-diplom4.ru]купить диплом в волгограде[/url] .
Diplomi_cmOr
29 Oct 25 at 10:16 pm
купить диплом в артеме [url=www.rudik-diplom1.ru/]www.rudik-diplom1.ru/[/url] .
Diplomi_xqer
29 Oct 25 at 10:16 pm
продвижение французского сайта цена [url=www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru[/url] .
optimizaciya i seo prodvijenie saitov moskva_wbel
29 Oct 25 at 10:16 pm
как легально купить диплом о [url=http://frei-diplom5.ru/]как легально купить диплом о[/url] .
Diplomi_cpPa
29 Oct 25 at 10:16 pm
купить диплом о среднем специальном [url=http://rudik-diplom2.ru]купить диплом о среднем специальном[/url] .
Diplomi_xvpi
29 Oct 25 at 10:17 pm
written by truereason.click
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
written by truereason.click
29 Oct 25 at 10:18 pm
купить диплом в нижнекамске [url=www.rudik-diplom8.ru]www.rudik-diplom8.ru[/url] .
Diplomi_pcMt
29 Oct 25 at 10:19 pm
блог про seo [url=http://www.statyi-o-marketinge7.ru]блог про seo[/url] .
stati o marketinge _hrkl
29 Oct 25 at 10:19 pm
купить диплом с занесением в реестр казань [url=http://www.frei-diplom1.ru]http://www.frei-diplom1.ru[/url] .
Diplomi_fcOi
29 Oct 25 at 10:19 pm
куплю диплом младшей медсестры [url=http://frei-diplom13.ru/]http://frei-diplom13.ru/[/url] .
Diplomi_lakt
29 Oct 25 at 10:19 pm
купить диплом в коврове [url=http://www.rudik-diplom3.ru]купить диплом в коврове[/url] .
Diplomi_mzei
29 Oct 25 at 10:21 pm
купить диплом медбрата [url=www.rudik-diplom6.ru/]купить диплом медбрата[/url] .
Diplomi_nrKr
29 Oct 25 at 10:21 pm
купить диплом в новомосковске [url=https://www.rudik-diplom14.ru]купить диплом в новомосковске[/url] .
Diplomi_inea
29 Oct 25 at 10:22 pm
купить диплом бухгалтера [url=https://rudik-diplom1.ru/]купить диплом бухгалтера[/url] .
Diplomi_xcer
29 Oct 25 at 10:22 pm
диплом о среднем профессиональном образовании с занесением в реестр купить [url=http://frei-diplom5.ru]диплом о среднем профессиональном образовании с занесением в реестр купить[/url] .
Diplomi_wcPa
29 Oct 25 at 10:22 pm
купить диплом с реестром красноярск [url=frei-diplom1.ru]купить диплом с реестром красноярск[/url] .
Diplomi_qtOi
29 Oct 25 at 10:23 pm
купить диплом логопеда [url=www.rudik-diplom5.ru/]купить диплом логопеда[/url] .
Diplomi_fzma
29 Oct 25 at 10:23 pm
легально купить диплом о [url=https://www.frei-diplom4.ru]легально купить диплом о[/url] .
Diplomi_ufOl
29 Oct 25 at 10:23 pm
купить диплом в кызыле [url=www.rudik-diplom10.ru]купить диплом в кызыле[/url] .
Diplomi_gySa
29 Oct 25 at 10:23 pm
купить диплом в муроме [url=www.rudik-diplom11.ru]купить диплом в муроме[/url] .
Diplomi_laMi
29 Oct 25 at 10:24 pm
секс
Jeromeeleri
29 Oct 25 at 10:25 pm
seks mostbet
Williamgon
29 Oct 25 at 10:25 pm
It’s impressive that you are getting ideas from this piece of writing as well as from our dialogue made
here.
Earn Matrix Pro Scam
29 Oct 25 at 10:25 pm
маркетинговые стратегии статьи [url=http://statyi-o-marketinge7.ru]маркетинговые стратегии статьи[/url] .
stati o marketinge _uakl
29 Oct 25 at 10:26 pm
bron mostbet
Williamgon
29 Oct 25 at 10:27 pm
Going to Gooncloud
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
Going to Gooncloud
29 Oct 25 at 10:27 pm
где купить дипломы медсестры [url=http://www.frei-diplom13.ru]где купить дипломы медсестры[/url] .
Diplomi_xgkt
29 Oct 25 at 10:28 pm
виртуальный номер
виртуальный номер
29 Oct 25 at 10:28 pm
купить проведенный диплом весь [url=frei-diplom4.ru]купить проведенный диплом весь[/url] .
Diplomi_ezOl
29 Oct 25 at 10:29 pm
купить диплом в краснодаре [url=www.rudik-diplom5.ru/]купить диплом в краснодаре[/url] .
Diplomi_djma
29 Oct 25 at 10:29 pm