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-diplom6.ru/]купить диплом о высшем образовании с занесением в реестр цена[/url] .
Diplomi_qcOl
29 Oct 25 at 7:12 pm
купить диплом в ельце [url=rudik-diplom1.ru]rudik-diplom1.ru[/url] .
Diplomi_goer
29 Oct 25 at 7:12 pm
купить диплом в барнауле [url=www.rudik-diplom3.ru]купить диплом в барнауле[/url] .
Diplomi_xqei
29 Oct 25 at 7:12 pm
купить медицинский диплом с занесением в реестр [url=www.frei-diplom4.ru/]купить медицинский диплом с занесением в реестр[/url] .
Diplomi_ioOl
29 Oct 25 at 7:12 pm
купить диплом в волжском [url=https://www.rudik-diplom5.ru]купить диплом в волжском[/url] .
Diplomi_cama
29 Oct 25 at 7:13 pm
купить диплом биолога [url=www.rudik-diplom6.ru/]купить диплом биолога[/url] .
Diplomi_uzKr
29 Oct 25 at 7:13 pm
диплом с реестром купить [url=www.frei-diplom5.ru]диплом с реестром купить[/url] .
Diplomi_lgPa
29 Oct 25 at 7:14 pm
купить диплом медсестры [url=frei-diplom13.ru]купить диплом медсестры[/url] .
Diplomi_ozkt
29 Oct 25 at 7:15 pm
Good post. I learn something totally new and challenging on blogs I stumbleupon on a daily basis.
It’s always useful to read through content from other writers and use a little something from their
web sites.
Avvio Finevox
29 Oct 25 at 7:15 pm
купить диплом вуза с проводкой [url=http://www.frei-diplom1.ru]http://www.frei-diplom1.ru[/url] .
Diplomi_uuOi
29 Oct 25 at 7:15 pm
in majority cases they can turn out tall enough that they do not influence most players, but in [url=https://api.searchiq.co/api/click?url=aHR0cHM6Ly9zcGlucmlzZS1jYXNpbm8tY2FuYWRhLmNvbS8]https://api.searchiq.co/api/click?url=aHR0cHM6Ly9zcGlucmlzZS1jYXNpbm8tY2FuYWRhLmNvbS8[/url], there are limits on success or transfers cash winnings, what are able to be extremely significant.
Kathleendub
29 Oct 25 at 7:18 pm
купить дипломы о высшем с занесением [url=https://rudik-diplom10.ru/]купить дипломы о высшем с занесением[/url] .
Diplomi_bbSa
29 Oct 25 at 7:18 pm
sghjt.com – Color palette felt calming, nothing distracting, just focused, thoughtful design.
Lakendra Kennan
29 Oct 25 at 7:18 pm
где купить диплом техникума всеми [url=https://frei-diplom8.ru/]где купить диплом техникума всеми[/url] .
Diplomi_qqsr
29 Oct 25 at 7:18 pm
купить проведенный диплом отзывы [url=http://www.frei-diplom4.ru]http://www.frei-diplom4.ru[/url] .
Diplomi_diOl
29 Oct 25 at 7:19 pm
купить диплом в соликамске [url=http://rudik-diplom11.ru]купить диплом в соликамске[/url] .
Diplomi_mkMi
29 Oct 25 at 7:20 pm
купить диплом в норильске [url=www.rudik-diplom6.ru/]купить диплом в норильске[/url] .
Diplomi_lrKr
29 Oct 25 at 7:20 pm
купить диплом в набережных челнах [url=https://www.rudik-diplom5.ru]купить диплом в набережных челнах[/url] .
Diplomi_csma
29 Oct 25 at 7:20 pm
купить диплом математика [url=https://rudik-diplom3.ru]купить диплом математика[/url] .
Diplomi_jxei
29 Oct 25 at 7:21 pm
I don’t know if it’s just me or if perhaps everybody else experiencing
issues with your website. It seems like some of the written text on your content
are running off the screen. Can someone else please provide feedback and let me
know if this is happening to them as well? This might be a issue
with my internet browser because I’ve had this happen before.
Thank you
Look At This
29 Oct 25 at 7:21 pm
диплом техникума купить цена [url=http://frei-diplom7.ru/]диплом техникума купить цена[/url] .
Diplomi_itei
29 Oct 25 at 7:22 pm
купить диплом в дербенте [url=http://rudik-diplom4.ru]купить диплом в дербенте[/url] .
Diplomi_iaOr
29 Oct 25 at 7:24 pm
виртуальный номер навсегда купить
виртуальный номер навсегда купить
29 Oct 25 at 7:24 pm
купить диплом в туймазы [url=https://rudik-diplom11.ru]купить диплом в туймазы[/url] .
Diplomi_dfMi
29 Oct 25 at 7:26 pm
linebet promo code
linebet promokod
29 Oct 25 at 7:26 pm
купить диплом в нефтекамске [url=https://rudik-diplom1.ru]купить диплом в нефтекамске[/url] .
Diplomi_nfer
29 Oct 25 at 7:27 pm
купить диплом в юрге [url=https://rudik-diplom10.ru/]купить диплом в юрге[/url] .
Diplomi_chSa
29 Oct 25 at 7:27 pm
где лучше купить диплом техникума [url=https://frei-diplom8.ru]где лучше купить диплом техникума[/url] .
Diplomi_xpsr
29 Oct 25 at 7:28 pm
купить диплом с занесением в реестр [url=http://frei-diplom5.ru/]купить диплом с занесением в реестр[/url] .
Diplomi_ruPa
29 Oct 25 at 7:28 pm
zanwechat.com – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
Breann Darvish
29 Oct 25 at 7:29 pm
купить диплом занесением реестр украины [url=http://frei-diplom1.ru]http://frei-diplom1.ru[/url] .
Diplomi_ahOi
29 Oct 25 at 7:30 pm
купить диплом нового образца [url=https://rudik-diplom4.ru]купить диплом нового образца[/url] .
Diplomi_taOr
29 Oct 25 at 7:30 pm
купить диплом с занесением в реестр в москве [url=frei-diplom4.ru]купить диплом с занесением в реестр в москве[/url] .
Diplomi_seOl
29 Oct 25 at 7:32 pm
fl508.com – Appreciate the typography choices; comfortable spacing improved my reading experience.
Corinne Dibonaventura
29 Oct 25 at 7:33 pm
можно купить диплом медсестры [url=http://frei-diplom13.ru/]можно купить диплом медсестры[/url] .
Diplomi_sakt
29 Oct 25 at 7:33 pm
купить диплом техникума в екатеринбурге с внесением в реестр [url=http://www.frei-diplom7.ru]купить диплом техникума в екатеринбурге с внесением в реестр[/url] .
Diplomi_xzei
29 Oct 25 at 7:34 pm
купить диплом в якутске [url=www.rudik-diplom5.ru]купить диплом в якутске[/url] .
Diplomi_hqma
29 Oct 25 at 7:34 pm
купить диплом в дзержинске [url=https://www.rudik-diplom11.ru]купить диплом в дзержинске[/url] .
Diplomi_juMi
29 Oct 25 at 7:35 pm
Быстро выйти из запоя можно с помощью клиники «ЧСП№1» в Ростове-на-Дону. Доступен выезд нарколога на дом.
Подробнее тут – [url=https://vyvod-iz-zapoya-rostov16.ru/]вывод из запоя клиника в ростове-на-дону[/url]
Michaelgaupe
29 Oct 25 at 7:35 pm
купить диплом инженера механика [url=www.rudik-diplom2.ru/]купить диплом инженера механика[/url] .
Diplomi_wdpi
29 Oct 25 at 7:36 pm
диплом техникума торгового купить [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_hwea
29 Oct 25 at 7:36 pm
купить диплом в туймазы [url=http://rudik-diplom8.ru]купить диплом в туймазы[/url] .
Diplomi_lpMt
29 Oct 25 at 7:36 pm
диплом купить с занесением в реестр рязань [url=http://frei-diplom6.ru/]http://frei-diplom6.ru/[/url] .
Diplomi_vbOl
29 Oct 25 at 7:36 pm
szsfujin.com – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
Kay Haataja
29 Oct 25 at 7:37 pm
go to website
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
go to website
29 Oct 25 at 7:37 pm
Нужно было разобраться в нейросетях для изображений, и эта подборка оказалась самой информативной. Все варианты актуальные, с реальными возможностями. Спасибо за качественную работу: https://vc.ru/top_rating/2301994-luchshie-besplatnye-nejroseti-dlya-generatsii-izobrazheniy
MichaelPrion
29 Oct 25 at 7:37 pm
Listen uρ, composed pom pі ρi, mathematics iѕ ɑmong
frоm tһe tߋp topics in Junior College, building foundation іn А-Level һigher calculations.
Ӏn аddition from institution resources, emphasize
օn mathematics to stop common pitfalls like careless mistakes ɗuring tests.
Mums and Dads, fearful ⲟf losing style engaged lah, strong primary maths results in superior
STEM comprehension аs weⅼl aѕ construction dreams.
Hwa Chong Institution Junior College іs renowned for its integrated program
tһɑt flawlessly combines scholastic rigor ԝith character development, producing global scholars аnd leaders.
Ϝirst-rate centers аnd skilled faculty support quality іn research study, entrepreneurship, ɑnd bilingualism.
Students gain from extensive worldwide exchanges ɑnd competitors, broadening point
of views аnd sharpening skills. Thе organization’ѕ focus on innovation and service cultivates strength ɑnd ethical worths.
Alumni networks ⲟpen doors to leading universities аnd prominent careers worldwide.
St. Joseph’ѕ Institution Junior College upholds valued Lasallian
customs оf faith, service, and intellectual intereѕt, creating
an empowering environment ԝhere trainees pursue knowledge with enthusiasm ɑnd dedicate themseⅼves to
uplifting others thrⲟugh thoughtful actions. Τhe incorporated program guarantees а fluid progression from secondary tо pre-university
levels, wіth ɑ focus on bilingual proficiency and innovative curricula supported Ьy facilities likе
state-of-tһe-art carrying оut arts centers аnd science reseaгch laboratories that motivate creative
ɑnd analytical excellence. Global immersion experiences,
consisting οf worldwide service journeys аnd cultural exchange programs, broaden trainees’ horizons, improve
linguistic skills, ɑnd cultivate a deep gratitude
fоr diverse worldviews. Opportunities fοr sophisticated гesearch, leadership roles іn student companies,
аnd mentorship from accomplished faculty build confidence,
crucial thinking, аnd a commitment to lifelong
knowing. Graduates аre understood fοr their compassion aand hiցh
achievements, protecting locations іn distinguished universities ɑnd standing oᥙt in professions tһat align with
tһe college’ѕ principles օf service and intellectual rigor.
Parents, worry ɑbout tһe difference hor, maths foundation proves critical аt Junior College to understanding figures, essential ԝithin modern digital system.
Wah lao, regardless tһough establishment гemains atas,
math is thee critical discipline tօ developing poise
іn figures.
Hey hey, Singapore folks, math proves ⅼikely the mօѕt crucial primary subject, fostering innovation fⲟr prοblem-solving to groundbreaking
jobs.
Parents, competitive approach οn lah, solid primary mathematics leads t᧐
superior scientific grasp аs welⅼ as engineering dreams.
Oh,math serves ɑs the base pillar for primary schooling,
assisting kids ᴡith geometric reasoning іn architecture careers.
Strong Α-levels mean eligibility fоr double
degrees.
Οһ, mathematics is tһe base pillar fߋr primary learning, assisting youngsters fߋr spatial reasoning t᧐ building
paths.
Aiyo, lacking strong math іn Junior College, гegardless top
institution youngsters mіght stumble ɑt secondary equations, ѕo build thіs now leh.
Heгe is my web ⲣage; list of secondary school
list of secondary school
29 Oct 25 at 7:37 pm
It’s genuinely very complex in this active life to listen news on Television, so I just use the web for that
purpose, and take the hottest news.
جشنواره خوارزمی نوجوان ۱۴۰۴
29 Oct 25 at 7:37 pm
купить диплом в таганроге [url=rudik-diplom4.ru]rudik-diplom4.ru[/url] .
Diplomi_wmOr
29 Oct 25 at 7:37 pm
диплом колледжа купить с занесением в реестр [url=http://frei-diplom5.ru/]диплом колледжа купить с занесением в реестр[/url] .
Diplomi_soPa
29 Oct 25 at 7:38 pm