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=zaimy-19.ru]все займы онлайн[/url] .
zaimi_yhKl
20 Sep 25 at 5:30 am
купить диплом колледжа рукой [url=http://frei-diplom12.ru/]http://frei-diplom12.ru/[/url] .
Diplomi_mrPt
20 Sep 25 at 5:31 am
займ все [url=http://www.zaimy-17.ru]http://www.zaimy-17.ru[/url] .
zaimi_edSa
20 Sep 25 at 5:32 am
Футболки с принтом Спб и интересные футболки женские в Улан-Удэ. Свитшот с принтом на заказ и шапка капитана в Екатеринбурге. Футболки принт Магазин в Москве и Тула футболки с принтом в Балашихе. Одежда персонаж официальный сайт и элитная упаковка в Смоленске. Калуга принт на футболку оптом и футболки с названиями групп – https://futbolki-s-printom.ru/
Gregorysnisp
20 Sep 25 at 5:32 am
за1мы онлайн [url=https://zaimy-21.ru]за1мы онлайн[/url] .
zaimi_yykl
20 Sep 25 at 5:33 am
всезаймы [url=zaimy-20.ru]всезаймы[/url] .
zaimi_wjPr
20 Sep 25 at 5:33 am
лучшие займы онлайн [url=https://zaimy-18.ru]лучшие займы онлайн[/url] .
zaimi_guMl
20 Sep 25 at 5:35 am
I do believe all of the ideas you’ve presented to your post.
They’re really convincing and can certainly work. Nonetheless, the posts are very quick for beginners.
May you please prolong them a bit from next time?
Thanks for the post.
Wervion Avis
20 Sep 25 at 5:36 am
Farmasi Nutriplus România oferă suplimente și produse de
wellness care îmbină inovația, calitatea și accesibilitatea.
Descoperă o gamă variată pentru un stil de viață sănătos, cu beneficii reale, prețuri atractive și garanția unei mărci
de încredere.
Farmasi Nutriplus
20 Sep 25 at 5:37 am
где можно купить диплом техникум [url=http://www.frei-diplom12.ru]где можно купить диплом техникум[/url] .
Diplomi_gsPt
20 Sep 25 at 5:37 am
за1мы онлайн [url=www.zaimy-19.ru/]www.zaimy-19.ru/[/url] .
zaimi_czKl
20 Sep 25 at 5:37 am
мфо займ [url=www.zaimy-21.ru]мфо займ[/url] .
zaimi_yvkl
20 Sep 25 at 5:37 am
купить диплом товароведа [url=http://rudik-diplom1.ru]купить диплом товароведа[/url] .
Diplomi_cser
20 Sep 25 at 5:38 am
все займ [url=http://zaimy-20.ru]все займ[/url] .
zaimi_cgPr
20 Sep 25 at 5:38 am
займы все [url=www.zaimy-16.ru]www.zaimy-16.ru[/url] .
zaimi_xnMi
20 Sep 25 at 5:38 am
все микрозаймы на карту [url=zaimy-22.ru]zaimy-22.ru[/url] .
zaimi_xhKi
20 Sep 25 at 5:39 am
накрутка подписчиков в тг смм накрутка
DavidNOb
20 Sep 25 at 5:40 am
Fabulous, what a website it is! This website
presents helpful facts to us, keep it up.
memek becek
20 Sep 25 at 5:40 am
I’ve learn a few just right stuff here. Certainly value
bookmarking for revisiting. I surprise how a lot effort you set to make this kind
of great informative web site.
investment
20 Sep 25 at 5:41 am
Купить диплом техникума в Луганск [url=https://educ-ua7.ru/]https://educ-ua7.ru/[/url] .
Diplomi_dcea
20 Sep 25 at 5:41 am
займы россии [url=www.zaimy-19.ru]займы россии[/url] .
zaimi_zmKl
20 Sep 25 at 5:41 am
займ всем [url=http://zaimy-18.ru]займ всем[/url] .
zaimi_zkMl
20 Sep 25 at 5:44 am
Farmasi Nutriplus România oferă suplimente și produse de wellness care îmbină inovația, calitatea și accesibilitatea.
Descoperă o gamă variată pentru un stil de viață sănătos, cu beneficii
reale, prețuri atractive și garanția unei mărci de încredere.
Farmasi Nutriplus
20 Sep 25 at 5:45 am
Грузоперевозки по России: надёжно, доступно, профессионально
[url=https://tlk-triga.ru/gruzoperevozki_po_moskve/]грузоперевозки по москве дешево[/url]
Грузоперевозки остаются ключевым элементом логистики для бизнеса любого масштаба: от мелких доставок по Москве и области до межгородских перевозок тяжёлого и негабаритного оборудования по России. Транспортные компании предлагают широкий спектр услуг — грузовые перевозки, доставка оборудования, перевозка промышленных грузов и транспортировка технологического оборудования. Для спецзадач доступны низкорамные тралы и аренда трала, тралл машина, корыто трал и короткий трал, которые позволяют перевозить станки, модули, модульные дома и крупногабаритные грузы. Негабаритные перевозки по России автотранспортом и негабаритные перевозки Москва требуют точного расчёта: стоимость перевозки негабаритного груза зависит от габаритов, веса, маршрута и необходимости согласований.
https://tlk-triga.ru/tral/
грузоперевозки по россии цена
Доставка негабаритных грузов и перевозка тяжеловесных грузов по Москве выполняются с использованием специализированной техники — низкорамник, трал для перевозки спецтехники, аренда низкорамного трала в Москве. Перевозка станков и перевозка технического оборудования требуют упаковки, крепления и часто сопровождения ГАИ. Перевезти опасный груз нужно через компании с разрешением — перевозка опасных грузов автомобильным транспортом возможна при наличии документов и спецупаковки. Рефрижератор заказать стоит для перевозки холодильного оборудования и рефрижераторные перевозки — отдельная услуга.
Для экономии выбирают сборный груз и сборные грузоперевозки по России, а для срочных задач — фура 20 тонн, бортовая фура или фура грузовая. Доставка по России транспортными компаниями и междугородние грузоперевозки требуют грамотного планирования: рассчитать стоимость доставки поможет калькуляция по тоннажу, километражу и типу транспорта. Многие ищут дешёвые варианты — грузоперевозки по Москве и Московской области дешево или дешевые грузоперевозки по России — но важно не экономить на безопасности при перевозке негабарита.
Услуги транспортной компании включают заказ грузовой машины для переезда, аренду трала и услуги трала по перевозке негабаритных грузов, доставку крупногабаритного товара и перемещение оборудования. Транспортные компании по перевозке грузов по России, такие как ООО ТЛК или ТЛК Трига, предлагают комплексные решения: от оформления разрешений на негабарит до доставки «от двери до двери». Заказать грузоперевозку по Москве и области, заказать трал Москва или арендовать трал для перевозки спецтехники — просто, если выбирать проверенную грузовую компанию и заранее согласовывать условия перевозки.
EnriqueDioth
20 Sep 25 at 5:45 am
Quality articles is the crucial to invite the
viewers to pay a quick visit the web site, that’s what this web site is providing.
Pusulabet
20 Sep 25 at 5:46 am
все займы онлайн [url=www.zaimy-19.ru/]все займы онлайн[/url] .
zaimi_yjKl
20 Sep 25 at 5:46 am
за1мы онлайн [url=https://zaimy-17.ru]https://zaimy-17.ru[/url] .
zaimi_xtSa
20 Sep 25 at 5:46 am
займер ру [url=zaimy-22.ru]zaimy-22.ru[/url] .
zaimi_aaKi
20 Sep 25 at 5:47 am
займы всем [url=www.zaimy-18.ru]займы всем[/url] .
zaimi_inMl
20 Sep 25 at 5:48 am
Descubre Farmasi España y ordena productos cosméticos veganos
de alta calidad. Aprovecha increíbles descuentos frente al precio de catálogo oficial.
Compra maquillaje, cuidado personal y belleza natural con confianza, envío rápido
y garantía de satisfacción en Farmasi España.
Farmasi Spain
20 Sep 25 at 5:49 am
купить диплом о высшем образовании с занесением в реестр в красноярске [url=https://frei-diplom2.ru/]купить диплом о высшем образовании с занесением в реестр в красноярске[/url] .
Diplomi_vsEa
20 Sep 25 at 5:49 am
Hey there! I’ve been reading your blog for some time now and
finally got the courage to go ahead and give you a shout out from Porter Texas!
Just wanted to mention keep up the fantastic job!
Ruhig Finlore
20 Sep 25 at 5:50 am
займы россии [url=www.zaimy-25.ru/]www.zaimy-25.ru/[/url] .
zaimi_kwoa
20 Sep 25 at 5:50 am
официальные займы онлайн на карту бесплатно [url=https://www.zaimy-23.ru]https://www.zaimy-23.ru[/url] .
zaimi_omSl
20 Sep 25 at 5:51 am
микрозаймы все [url=www.zaimy-17.ru]микрозаймы все[/url] .
zaimi_ptSa
20 Sep 25 at 5:51 am
все займы ру [url=https://zaimy-22.ru/]https://zaimy-22.ru/[/url] .
zaimi_xdKi
20 Sep 25 at 5:51 am
все онлайн займы [url=http://zaimy-18.ru/]все онлайн займы[/url] .
zaimi_jeMl
20 Sep 25 at 5:53 am
диплом техникума купить в украине [url=https://frei-diplom9.ru]диплом техникума купить в украине[/url] .
Diplomi_haea
20 Sep 25 at 5:54 am
микрозайм всем [url=https://www.zaimy-25.ru]https://www.zaimy-25.ru[/url] .
zaimi_egoa
20 Sep 25 at 5:55 am
Mums and Dads, composed lah, ɡood school combined ᴡith robust mathematics base signifies ʏоur youngster maу
handle decimals and spatial concepts ᴡith assurance, leading
f᧐r superior generɑl scholarly rеsults.
Yishun Innova Junior College merges strengths fοr digital literacy ɑnd management quality.
Upgraded centers promote development ɑnd lifelong learning.
Diverse programs іn media and languages foster creativity ɑnd citizenship.
Community engagements develop compassion аnd skills.
Students emerge ɑs confident, tech-savvy leaders ready f᧐r the digital age.
St. Andrew’ѕ Junior College embraces Anglican values tο promote holistic
development, cultivating principled individuals ѡith robust
character qualities tһrough a mix of spiritual guidance, academic pursuit, ɑnd community
involvement іn a warm and inclusive environment.
Ƭhe college’s contemporary features, consisting оf
interactive class, sports complexes, аnd innovative arts studios, һelp with
excellence across academic disciplines, sports programs tһat highlight physical fitness аnd reasonable play, аnd artistic
ventures that encourage self-expression аnd innovation. Social ᴡork
efforts, such as volunteer collaborations ѡith regional companies ɑnd
outreach jobs, impart compassion, social duty, ɑnd a
sense of purpose, enriching trainees’ academic journeys.
А varied variety оf co-curricular activities, from debate
societies tߋ musical ensembles, promotes team effort, management skills, аnd personal discovery, allowing
еvery trainee to shine in thеir picked
ɑreas. Alumni of St. Andrew’ѕ Junior College consistently emerge as ethical, resistant leaders ԝho mɑke
siɡnificant contributions t᧐ society, ѕhowing the
organization’ѕ extensive influence ߋn developing ᴡell-rounded, νalue-driven individuals.
Oh dear, lacking robust math ɑt Junior College, regardless leading school children ⅽould stumble wuth secondary calculations, ѕo cultivate thіs promptly leh.
Hey hey, Singapore moms and dads, mathematics гemains ⅼikely
the extremely important primary discipline, fostering creativity fօr proƅlem-solving
fօr groundbreaking careers.
Αpart tо establishment facilities, emphasize on math in orɗer to aᴠoid typical mistakes including careless
blunders аt tests.
Oh man, еven whether institution iѕ һigh-еnd, math serves ɑs the critical topic to cultivates confidence regarding figures.
Alas, primary mathematics instructs real-ᴡorld uses like money
management, so maкe surе ʏour youngster gets that properly beginnіng eɑrly.
Ⅾon’t be complacent; A-levels аrе your launchpad tо
entrepreneurial success.
Folks, kiasu mode activated lah, robust primary mathematics guides t᧐ improved STEM grasp аnd engineering aspirations.
Wow, math serves аs the foundation pillar ߋf primary learning, helping kids f᧐r spatial thinking tⲟ
architecture paths.
Feel free tо surf to mү web-site – NUS High School of Mathematics and Science
NUS High School of Mathematics and Science
20 Sep 25 at 5:55 am
диплом купить техникум [url=http://frei-diplom8.ru]диплом купить техникум[/url] .
Diplomi_sxsr
20 Sep 25 at 5:55 am
Купить диплом колледжа в Ивано-Франковск [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_rxea
20 Sep 25 at 5:56 am
cheapest cialis: Generic Cialis without a doctor prescription – EverTrustMeds
DerekStops
20 Sep 25 at 5:56 am
все онлайн займы [url=https://zaimy-22.ru/]https://zaimy-22.ru/[/url] .
zaimi_scKi
20 Sep 25 at 5:57 am
I don’t know if it’s just me or if perhaps everybody else experiencing issues with your blog.
It appears as though some of the written text in 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
browser because I’ve had this happen before. Thanks
Crownmark Dexlin Legit Or Not
20 Sep 25 at 5:59 am
займ все [url=http://zaimy-17.ru/]http://zaimy-17.ru/[/url] .
zaimi_veSa
20 Sep 25 at 6:01 am
It’s enormous that you are getting ideas from this post as well as from our discussion made
at this place.
https://meta-moscow.ru/bitrix/redirect.php?goto=https://casinos-online-espana.mystrikingly.com/
20 Sep 25 at 6:04 am
диплом техникума старого образца до 1996 г купить [url=https://educ-ua7.ru]https://educ-ua7.ru[/url] .
Diplomi_nwea
20 Sep 25 at 6:05 am
Каждый этап проводится под контролем специалистов, что снижает риск осложнений и повышает эффективность лечения.
Разобраться лучше – http://
GoodiniIcock
20 Sep 25 at 6:05 am
официальные займы онлайн на карту бесплатно [url=http://zaimy-25.ru/]http://zaimy-25.ru/[/url] .
zaimi_awoa
20 Sep 25 at 6:05 am