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-diplom1.ru]купить диплом с проведением в[/url] .
Diplomi_zxOi
20 Sep 25 at 2:35 am
Промокод 1WIN на 500% на первые 20 депозитов:
https://vmestedeshevle.listbb.ru/viewtopic.php?t=15391. Актуальность промокода: настоящий момент. Сумма бонуса по промокоду: до 200 000 рублей.
Rogermiz
20 Sep 25 at 2:35 am
все микрозаймы онлайн [url=http://www.zaimy-20.ru]все микрозаймы онлайн[/url] .
zaimi_daPr
20 Sep 25 at 2:36 am
все микрозаймы [url=http://www.zaimy-23.ru]http://www.zaimy-23.ru[/url] .
zaimi_yaSl
20 Sep 25 at 2:36 am
официальные займы онлайн на карту бесплатно [url=https://www.zaimy-21.ru]официальные займы онлайн на карту бесплатно[/url] .
zaimi_tikl
20 Sep 25 at 2:36 am
สล็อต
สล็อต
20 Sep 25 at 2:37 am
список займов онлайн на карту [url=https://www.zaimy-17.ru]список займов онлайн на карту[/url] .
zaimi_bzSa
20 Sep 25 at 2:37 am
диплом с занесением в реестр купить [url=www.frei-diplom5.ru/]диплом с занесением в реестр купить[/url] .
Diplomi_gnPa
20 Sep 25 at 2:38 am
https://evertrustmeds.com/# Ever Trust Meds
RichardceaNy
20 Sep 25 at 2:38 am
все займы [url=www.zaimy-25.ru]все займы[/url] .
zaimi_pooa
20 Sep 25 at 2:38 am
список займов онлайн [url=http://zaimy-22.ru/]http://zaimy-22.ru/[/url] .
zaimi_bjKi
20 Sep 25 at 2:39 am
микро займы онлайн [url=http://www.zaimy-17.ru]микро займы онлайн[/url] .
zaimi_jySa
20 Sep 25 at 2:41 am
накрутка подписчиков и просмотров тг
JerryBealo
20 Sep 25 at 2:42 am
кто купил диплом техникума отзывы [url=https://frei-diplom9.ru]кто купил диплом техникума отзывы[/url] .
Diplomi_dfea
20 Sep 25 at 2:42 am
диплом техникума ссср купить [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_qpea
20 Sep 25 at 2:42 am
Oi oi, Singapore folks, mathematics гemains lіkely thе most imρortant primary subject, encouraging innovation tһrough issue-resolving fօr groundbreaking jobs.
Ɗon’t take lightly lah, combine a excellent Junior College ԝith maths superiority fοr assure elevated Α Levels marks and smooth cһanges.
Parents, dread tһe difference hor, math groundwork іs essential іn Junior College for comprehending figures, crucial fⲟr current online economy.
Anglo-Chinese Junior College stands ɑѕ a beacon of ᴡell balanced
education, blending rigorous academics ѡith ɑ supporting Christian ethos tһat influences
moral stability ɑnd personal growth. Ꭲhe college’s state-ⲟf-tһe-art centers and
knowledgeable faculty assistance exceptional efficiency
іn Ьoth arts and sciences, with trainees frequently
accomplishing leading distinctions. Τhrough itѕ emphasis
оn sports аnd carrying оut arts, students establish discipline, sociability, аnd an enthusiasm fοr excellence
ƅeyond the classroom. International partnerships ɑnd exchange chances enhance
the learning experience, promoting global awareness ɑnd cultural appreciation. Alumni
flourish іn varied fields, testament to the college’ѕ role in shaping principled leaders ready tօ contribute favorably to society.
Singapore Sports School masterfully stabilizes ᴡorld-class
athletic training ᴡith a extensive scholastic curriculum, dedicated tо
nurturing elite professional athletes ѡho stand out not only іn sports but aⅼso in individual and professional life domains.
Ꭲhe school’s personalized academic paths provide
versatile scheduling tο accommodate extensive training and competitors,
guaranteeing students keep hіgh scholastic standards whіle pursuing theiг sporting
enthusiasms ѡith steady focus. Boasting tоp-tier
facilities ⅼike Olympic-standard training arenas, sports science labs, ɑnd recovery centers,
іn adⅾition to professional training fгom prominent specialists,
tһe organization supports peak physical performance and holistic
athlete development. International exposures tһrough
international tournaments, exchange programs ԝith overseas sports academies, аnd management workshops develop resilience, tactical thinking, аnd substantial networks tһat extend beyond the playing field.
Trainees finish aѕ disciplined, goal-oriented leaders, ѡell-prepared for professions іn expert sports, sports management, ⲟr hіgher education,
highlighting Singapore Sports School’ѕ exceptional function іn cultivating champions οf character and
achievement.
Ιn additiοn fгom institution facilities, focus on maths tօ avoid typical pitfalls including careless
errors іn tests.
Parents, fearful օf losing style օn lah, strong primary mathematics guides f᧐r improved scientific grasp ɑnd engineering aspirations.
Oh dear, lacking strong maths iin Junior College, гegardless prestigious school kids mɑy falter іn secondary equations,
tһᥙs develop this ρromptly leh.
Wah lao, еvеn whether establishment is fancy, mathematics
serves ɑs tһe critical topic fоr cultivates assurance reɡarding numƄers.
Alas, primary mathematics teaches practical ᥙsеs such аs
financial planning, thеrefore ensure yоur youngster masters
this rigһt beginnіng үoung age.
Math at A-levels builds endurance fօr marathon study sessions.
Parents, fearful оf losing approach on lah,
robust primary maths гesults f᧐r superior
science grasp ɑnd construction dreams.
Oh, mathematics іѕ tһe foundation pillar foг primary schooling,
aiding kids ԝith geometric reasoning foг building careers.
Мy site best math tutor
best math tutor
20 Sep 25 at 2:42 am
kraken ссылка на сайт kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
20 Sep 25 at 2:42 am
все микрозаймы онлайн [url=http://www.zaimy-25.ru]http://www.zaimy-25.ru[/url] .
zaimi_heoa
20 Sep 25 at 2:42 am
buy mdma prague cocain in prague from columbia
prague-drugs-205
20 Sep 25 at 2:43 am
все займы на карту [url=zaimy-18.ru]все займы на карту[/url] .
zaimi_zmMl
20 Sep 25 at 2:43 am
все займы рф [url=https://zaimy-19.ru/]все займы рф[/url] .
zaimi_ioKl
20 Sep 25 at 2:43 am
мфо займ онлайн [url=https://www.zaimy-17.ru]мфо займ онлайн[/url] .
zaimi_kdSa
20 Sep 25 at 2:44 am
займы всем [url=www.zaimy-20.ru]займы всем[/url] .
zaimi_apPr
20 Sep 25 at 2:44 am
микрозайм всем [url=http://www.zaimy-21.ru]микрозайм всем[/url] .
zaimi_mokl
20 Sep 25 at 2:44 am
Купить диплом любого университета поможем. Купить диплом бакалавра в Уфе – [url=http://diplomybox.com/kupit-diplom-bakalavra-v-ufe/]diplomybox.com/kupit-diplom-bakalavra-v-ufe[/url]
Cazrzkm
20 Sep 25 at 2:45 am
Normally I do not read article on blogs, however
I would like to say that this write-up very pressured me to try
and do so! Your writing style has been surprised me.
Thanks, very nice post.
ww88sun.com
20 Sep 25 at 2:45 am
займер ру [url=zaimy-25.ru]займер ру[/url] .
zaimi_gjoa
20 Sep 25 at 2:45 am
как набрать 1000 подписчиков в тг
MatthewRow
20 Sep 25 at 2:46 am
Купить диплом техникума в Запорожье [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_exea
20 Sep 25 at 2:47 am
микрозайм все [url=https://www.zaimy-22.ru]https://www.zaimy-22.ru[/url] .
zaimi_fwKi
20 Sep 25 at 2:49 am
купить диплом москва легально [url=www.frei-diplom2.ru/]www.frei-diplom2.ru/[/url] .
Diplomi_uiEa
20 Sep 25 at 2:51 am
купить диплом с занесением в реестры [url=http://www.frei-diplom3.ru]купить диплом с занесением в реестры[/url] .
Diplomi_tzKt
20 Sep 25 at 2:51 am
список займов онлайн [url=www.zaimy-18.ru]список займов онлайн[/url] .
zaimi_alMl
20 Sep 25 at 2:51 am
за1мы онлайн [url=http://zaimy-19.ru]http://zaimy-19.ru[/url] .
zaimi_doKl
20 Sep 25 at 2:52 am
где купить дипломы медсестры [url=https://www.frei-diplom13.ru]где купить дипломы медсестры[/url] .
Diplomi_dokt
20 Sep 25 at 2:52 am
I am really delighted how to talk to doctor about ed read this web site posts which carries tons of useful
facts, thanks for providing such information.
how to talk to doctor about ed
20 Sep 25 at 2:52 am
Когда проблемы с алкоголизмом достигают критической точки, оперативное вмешательство становится жизненно необходимым. В Мариуполе квалифицированные наркологи оказывают помощь на дому, обеспечивая оперативную детоксикацию организма, стабилизацию жизненно важных показателей и психологическую поддержку. Такой формат лечения позволяет пациенту получить качественную медицинскую помощь в привычной домашней обстановке, сохраняя конфиденциальность и минимизируя стресс, связанный с посещением стационара.
Выяснить больше – https://narcolog-na-dom-mariupol0.ru/narkolog-na-dom-kruglosutochno-mariupol/
Romanuteda
20 Sep 25 at 2:52 am
все онлайн займы [url=http://zaimy-22.ru]http://zaimy-22.ru[/url] .
zaimi_vvKi
20 Sep 25 at 2:52 am
всезаймы [url=https://zaimy-20.ru/]всезаймы[/url] .
zaimi_zoPr
20 Sep 25 at 2:53 am
займ все [url=http://zaimy-21.ru/]займ все[/url] .
zaimi_axkl
20 Sep 25 at 2:53 am
накрутка подписчиков телеграм канал
MatthewRow
20 Sep 25 at 2:53 am
список займов онлайн на карту [url=www.zaimy-18.ru/]список займов онлайн на карту[/url] .
zaimi_cdMl
20 Sep 25 at 2:55 am
взо [url=www.zaimy-19.ru/]взо[/url] .
zaimi_pwKl
20 Sep 25 at 2:55 am
займ всем [url=http://www.zaimy-20.ru]займ всем[/url] .
zaimi_ppPr
20 Sep 25 at 2:56 am
займы все онлайн [url=www.zaimy-17.ru]www.zaimy-17.ru[/url] .
zaimi_gySa
20 Sep 25 at 2:56 am
займер ру [url=www.zaimy-25.ru]займер ру[/url] .
zaimi_stoa
20 Sep 25 at 2:56 am
все микрозаймы [url=zaimy-21.ru]все микрозаймы[/url] .
zaimi_gpkl
20 Sep 25 at 2:56 am
список займов онлайн [url=https://zaimy-23.ru]https://zaimy-23.ru[/url] .
zaimi_jaSl
20 Sep 25 at 2:59 am
купить диплом о высшем образовании легально [url=https://www.frei-diplom6.ru]купить диплом о высшем образовании легально[/url] .
Diplomi_dgOl
20 Sep 25 at 2:59 am
можно купить диплом медсестры [url=www.frei-diplom13.ru/]можно купить диплом медсестры[/url] .
Diplomi_vikt
20 Sep 25 at 3:00 am