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=https://rudik-diplom10.ru]куплю диплом цена[/url] .
Diplomi_abSa
20 Sep 25 at 1:14 am
купить диплом с реестром вуза [url=https://frei-diplom1.ru/]купить диплом с реестром вуза[/url] .
Diplomi_mtOi
20 Sep 25 at 1:15 am
купить новый диплом [url=www.rudik-diplom1.ru]купить новый диплом[/url] .
Diplomi_nber
20 Sep 25 at 1:15 am
накрутка настоящих подписчиков в телеграм канале
MatthewRow
20 Sep 25 at 1:16 am
Aw, this was an extremely nice post. Finding the
time and actual effort to produce a good article… but what can I
say… I put things off a lot and don’t seem to get anything
done.
get it delivered
20 Sep 25 at 1:17 am
купить диплом медсестры [url=frei-diplom13.ru]купить диплом медсестры[/url] .
Diplomi_dgkt
20 Sep 25 at 1:17 am
I got this web site from my pal who informed me
concerning this website and now this time I am browsing this
website and reading very informative articles or reviews at
this time.
dewapadel
20 Sep 25 at 1:18 am
если купить диплом техникума [url=https://frei-diplom9.ru]если купить диплом техникума[/url] .
Diplomi_nyea
20 Sep 25 at 1:18 am
Nice response in return of this matter with firm arguments and telling the whole thing concerning that.
beste online casino deutschland
20 Sep 25 at 1:19 am
микрозаймы онлайн [url=https://zaimy-17.ru/]микрозаймы онлайн[/url] .
zaimi_ooSa
20 Sep 25 at 1:19 am
After checking out a few of the blog posts on your website, I honestly appreciate your technique of blogging.
I added it to my bookmark site list and will be
checking back soon. Take a look at my website as well and tell me what you think.
بهترین برند لوازم آرایش
20 Sep 25 at 1:22 am
где купить дипломы медсестры [url=www.frei-diplom13.ru/]где купить дипломы медсестры[/url] .
Diplomi_iokt
20 Sep 25 at 1:23 am
https://internet59360.blogprodesign.com/58514230/la-guГa-definitiva-para-competencias-laborales
Identificar las competencias laborales mas valoradas en el mercado chileno es critico para entender los desafios que hoy enfrentan las organizaciones. La tecnologia, la globalizacion y la nueva generacion de trabajadores estan moldeando que habilidades se valoran en el mundo laboral.
Top de las habilidades mas valoradas
Adaptabilidad
Las companias del pais necesitan equipos capaces de moverse rapido a nuevos escenarios.
Comunicacion efectiva
No solo expresar, sino escuchar. En equipos hibridos, esta capacidad es esencial.
Pensamiento critico
Con inputs por todos lados, las empresas valoran a quienes filtran antes de actuar.
Sinergia grupal
Mas alla del “buena onda”, es poder coordinarse con departamentos de distintos rubros.
Gestion de personas
Incluso en equipos pequenos, se espera motivar y no solo dar ordenes.
Habilidades digitales
Desde software colaborativo hasta analitica, lo digital es hoy una skill base.
?Por que importan tanto las competencias laborales mas demandadas?
Porque son la distincion entre quedarse atras o crecer en tu carrera. En nuestro mercado, donde la fuga de talento es alta, cultivar estas capacidades se traduce en empleabilidad.
De que manera desarrollar las competencias laborales mas demandadas
Programas de formacion.
Coaching.
Experiencia practica.
Retroalimentacion constantes.
Las habilidades clave son el camino para asegurar tu empleabilidad.
JuniorShido
20 Sep 25 at 1:23 am
за1мы онлайн [url=http://www.zaimy-22.ru]http://www.zaimy-22.ru[/url] .
zaimi_kmKi
20 Sep 25 at 1:23 am
купить диплом пту с занесением в реестр [url=frei-diplom4.ru]купить диплом пту с занесением в реестр[/url] .
Diplomi_xtOl
20 Sep 25 at 1:25 am
все займы рф [url=https://zaimy-25.ru]https://zaimy-25.ru[/url] .
zaimi_tkoa
20 Sep 25 at 1:25 am
купить диплом пту в реестре [url=http://frei-diplom3.ru/]купить диплом пту в реестре[/url] .
Diplomi_agKt
20 Sep 25 at 1:25 am
купить диплом московского торгово экономического техникума [url=https://frei-diplom9.ru]купить диплом московского торгово экономического техникума[/url] .
Diplomi_tiea
20 Sep 25 at 1:26 am
займы россии [url=http://zaimy-17.ru/]займы россии[/url] .
zaimi_euSa
20 Sep 25 at 1:26 am
купить диплом в реестр [url=frei-diplom2.ru]купить диплом в реестр[/url] .
Diplomi_fgEa
20 Sep 25 at 1:26 am
купить диплом в смоленске [url=https://www.rudik-diplom1.ru]https://www.rudik-diplom1.ru[/url] .
Diplomi_aqer
20 Sep 25 at 1:26 am
все займы [url=https://zaimy-18.ru/]все займы[/url] .
zaimi_fpMl
20 Sep 25 at 1:27 am
все микрозаймы онлайн [url=https://zaimy-19.ru/]все микрозаймы онлайн[/url] .
zaimi_rbKl
20 Sep 25 at 1:28 am
кто купил диплом с занесением в реестр [url=http://frei-diplom6.ru/]кто купил диплом с занесением в реестр[/url] .
Diplomi_yuOl
20 Sep 25 at 1:29 am
как легально купить диплом о [url=https://www.frei-diplom5.ru]как легально купить диплом о[/url] .
Diplomi_ipPa
20 Sep 25 at 1:30 am
микрозаймы онлайн [url=https://zaimy-22.ru]https://zaimy-22.ru[/url] .
zaimi_zbKi
20 Sep 25 at 1:30 am
На данном этапе врач уточняет, как долго продолжается запой, какой тип алкоголя употребляется и имеются ли сопутствующие заболевания. Детальный анализ клинических данных помогает подобрать оптимальные методы детоксикации и минимизировать риск осложнений.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-murmansk0.ru/]вывод из запоя на дому круглосуточно мурманск[/url]
AlfredDierb
20 Sep 25 at 1:30 am
накрутка подписчиков в тг чат
DavidNOb
20 Sep 25 at 1:31 am
займер ру [url=http://www.zaimy-20.ru]займер ру[/url] .
zaimi_ycPr
20 Sep 25 at 1:31 am
займ всем [url=https://zaimy-25.ru]https://zaimy-25.ru[/url] .
zaimi_khoa
20 Sep 25 at 1:32 am
за1мы онлайн [url=https://zaimy-21.ru]за1мы онлайн[/url] .
zaimi_cfkl
20 Sep 25 at 1:32 am
купить диплом о среднем профессиональном образовании с занесением в реестр [url=http://frei-diplom1.ru]купить диплом о среднем профессиональном образовании с занесением в реестр[/url] .
Diplomi_blOi
20 Sep 25 at 1:32 am
купить диплом о высшем образовании с занесением в реестр в красноярске [url=http://frei-diplom3.ru]купить диплом о высшем образовании с занесением в реестр в красноярске[/url] .
Diplomi_dwKt
20 Sep 25 at 1:33 am
купить диплом по реестру [url=frei-diplom2.ru]купить диплом по реестру[/url] .
Diplomi_gnEa
20 Sep 25 at 1:34 am
https://xn--krken21-bn4c.com
Howardreomo
20 Sep 25 at 1:34 am
займы [url=www.zaimy-18.ru/]www.zaimy-18.ru/[/url] .
zaimi_hxMl
20 Sep 25 at 1:34 am
купить диплом в донском [url=rudik-diplom1.ru]rudik-diplom1.ru[/url] .
Diplomi_lver
20 Sep 25 at 1:34 am
все займы ру [url=zaimy-19.ru]zaimy-19.ru[/url] .
zaimi_bdKl
20 Sep 25 at 1:34 am
займы [url=https://www.zaimy-22.ru]https://www.zaimy-22.ru[/url] .
zaimi_xvKi
20 Sep 25 at 1:36 am
купить легальный диплом колледжа [url=https://frei-diplom6.ru]купить легальный диплом колледжа[/url] .
Diplomi_euOl
20 Sep 25 at 1:37 am
микрозаймы онлайн [url=www.zaimy-17.ru]микрозаймы онлайн[/url] .
zaimi_xmSa
20 Sep 25 at 1:37 am
Получить диплом университета поспособствуем. Купить диплом о высшем образовании в Хабаровске – [url=http://diplomybox.com/kupit-diplom-o-vysshem-obrazovanii-v-khabarovske/]diplomybox.com/kupit-diplom-o-vysshem-obrazovanii-v-khabarovske[/url]
Cazrnpm
20 Sep 25 at 1:37 am
займы всем [url=www.zaimy-20.ru/]займы всем[/url] .
zaimi_pxPr
20 Sep 25 at 1:38 am
Oh, maths serves as the base pillar οf primary learning, assisting children in dimensional thinking to building paths.
Alas, mіnus robust math ɑt Junior College, regardless leading establishment
children ϲould stumble with secondary calculations, tһuѕ cultivate this promрtly leh.
St. Andrew’ѕ Junior College cultivates Anglican values аnd holistic
growth, constructing principled people ԝith strong character.
Modern amenities support quality іn academics, sports, ɑnd
arts. Neighborhood service and leadership programs impart empathy аnd obligation. Varied сο-curricular activities promote team
effort ɑnd ѕelf-discovery. Alumni become ethical leaders, contributing meaningfully t᧐
society.
Yishun Innova Junior College, formed ƅy the merger оf Yishun Junior College
ɑnd Inniva Junior College, utilizes combined strengths tօ champion digital literacy andd
excellent leadership, preparing students fօr excellence in a technology-driven age tһrough forward-focused education. Updated facilities, ѕuch as clever class, media production studios, аnd development laboratories, promote
hands-᧐n knowing in emerging fields lіke digital media, languages, аnd computational thinking, fostering imagination аnd technical efficiency.
Diverse scholastic аnd co-curricular programs, consisting ⲟf language immersion courses аnd digital arts сlubs, encourage
expedition off individual interests whiⅼe developing citizenship
values ɑnd global awareness. Community engagement activities,fгom regional service
jobs to worldwide collaborations, cultivate compassion, collaborative
skills, ɑnd a sense of social obligation ɑmong trainees.
As confident ɑnd tech-savvy leaders, Yishun Innova Junior College’ѕ
graduates аre primed f᧐r thе digital age,
standing out іn college and innovative professions that demand flexibility аnd visionary
thinking.
Βesides tо establishment facilities, concentrate ԝith
maths to prevent typical pitfalls sucһ as inattentive blunders іn assessments.
Folks, competitive style engaged lah, robust primary maths гesults in improved
science comprehension ρlus engineering goals.
Ⲟһ no, primary math educates practical implementations ⅼike budgeting, tһerefore mаke ѕure ʏour child masters thіs properly beginning eaгly.
Oi oi, Singapore folks, math іs pеrhaps tһe extremely crucial primary subject, fostering
creativity tһrough challenge-tackling to innovative careers.
А-level success stories in Singapore оften start ԝith kiasu study habits from JC
days.
Alas, primary maths teaches everyday սѕes liкe money management, theгefore guarantee ʏοur child grasps tһіs properly fгom
eɑrly.
Here iѕ my blog – junior colleges singapore
junior colleges singapore
20 Sep 25 at 1:39 am
Купить диплом колледжа в Запорожье [url=https://educ-ua7.ru/]https://educ-ua7.ru/[/url] .
Diplomi_zdea
20 Sep 25 at 1:39 am
как купить легальный диплом [url=http://frei-diplom1.ru]http://frei-diplom1.ru[/url] .
Diplomi_ikOi
20 Sep 25 at 1:39 am
все займы ру [url=https://zaimy-19.ru/]https://zaimy-19.ru/[/url] .
zaimi_wjKl
20 Sep 25 at 1:41 am
prague drugstore cocain in prague fishscale
prague-drugs-998
20 Sep 25 at 1:42 am
мфо займ онлайн [url=http://www.zaimy-23.ru]http://www.zaimy-23.ru[/url] .
zaimi_mySl
20 Sep 25 at 1:42 am
займы онлайн [url=www.zaimy-25.ru]займы онлайн[/url] .
zaimi_vloa
20 Sep 25 at 1:43 am