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!
локальное seo блог [url=http://statyi-o-marketinge6.ru]http://statyi-o-marketinge6.ru[/url] .
stati o marketinge _qzkn
28 Oct 25 at 1:05 pm
sportwetten ergebnisse
Look into my webpage Wetten Tipps Heute (https://bspelectronics.com/)
https://bspelectronics.com/
28 Oct 25 at 1:06 pm
купить диплом высшее [url=rudik-diplom11.ru]купить диплом высшее[/url] .
Diplomi_kxMi
28 Oct 25 at 1:06 pm
Технологии не стоят на месте актуальные зеркала kraken kraken актуальные ссылки kraken зеркало kraken ссылка зеркало
RichardPep
28 Oct 25 at 1:07 pm
Расташоп
Расташоп
28 Oct 25 at 1:07 pm
купить диплом в чебоксарах [url=https://rudik-diplom7.ru]купить диплом в чебоксарах[/url] .
Diplomi_zjPl
28 Oct 25 at 1:08 pm
kraken vk3
kraken вход
Henryamerb
28 Oct 25 at 1:08 pm
bestvaluecollection – Pricing appears competitive and checkout seemed straightforward during my review.
Dwain Teston
28 Oct 25 at 1:09 pm
купить диплом с проводкой одной [url=https://frei-diplom2.ru/]купить диплом с проводкой одной[/url] .
Diplomi_kkEa
28 Oct 25 at 1:09 pm
купить диплом в хасавюрте [url=https://rudik-diplom2.ru]купить диплом в хасавюрте[/url] .
Diplomi_dvpi
28 Oct 25 at 1:10 pm
was sind kombiwetten
Feel free to surf to my web site der buchmacher (Hugh)
Hugh
28 Oct 25 at 1:11 pm
куплю диплом медсестры в москве [url=http://www.frei-diplom15.ru]куплю диплом медсестры в москве[/url] .
Diplomi_rzoi
28 Oct 25 at 1:11 pm
душевое ограждение купить в спб из стекла [url=http://dzen.ru/a/aPaQV60E-3Bo4dfi/]http://dzen.ru/a/aPaQV60E-3Bo4dfi/[/url] .
steklyannie dyshevie na zakaz _hsol
28 Oct 25 at 1:11 pm
купить диплом техникума оригинальный [url=http://www.frei-diplom8.ru]купить диплом техникума оригинальный[/url] .
Diplomi_tbsr
28 Oct 25 at 1:12 pm
где купить диплом колледжа омск [url=frei-diplom9.ru]frei-diplom9.ru[/url] .
Diplomi_pyea
28 Oct 25 at 1:13 pm
маркетинг в интернете блог [url=https://statyi-o-marketinge6.ru/]https://statyi-o-marketinge6.ru/[/url] .
stati o marketinge _jjkn
28 Oct 25 at 1:13 pm
«Мебельный базар» — это интернет-магазин и офлайн-салон на Каширском шоссе, где можно собрать интерьер от классики до лофта: спальни, кухни, гостиные, шкафы-купе по индивидуальным размерам, столы и стулья, мягкая мебель, матрасы. Регулярные акции, готовые комплекты и доставка по всей России делают обновление дома прозрачным по срокам и бюджету, а ассортимент российских и европейских фабрик позволяет точно попасть в стиль. Удобнее всего начать с витрины предложений и каталога на https://bazar-mebel.ru/ — и оформить заказ онлайн или в салоне.
mibacpsype
28 Oct 25 at 1:14 pm
купить диплом о среднем [url=http://www.rudik-diplom9.ru]купить диплом о среднем[/url] .
Diplomi_mcei
28 Oct 25 at 1:14 pm
ремонт подвала в частном доме [url=https://gidroizolyaciya-cena-7.ru/]gidroizolyaciya-cena-7.ru[/url] .
gidroizolyaciya cena_tnSi
28 Oct 25 at 1:14 pm
kraken market
kraken android
Henryamerb
28 Oct 25 at 1:16 pm
кракен официальный сайт
kraken tor
Henryamerb
28 Oct 25 at 1:17 pm
купить диплом в ставрополе [url=https://www.rudik-diplom2.ru]купить диплом в ставрополе[/url] .
Diplomi_hypi
28 Oct 25 at 1:17 pm
диплом с занесением в реестр купить [url=frei-diplom2.ru]диплом с занесением в реестр купить[/url] .
Diplomi_lwEa
28 Oct 25 at 1:18 pm
[url=https://mydiv.net/arts/view-TOP-5-luchshih-servisov-virtualnyh-nomerov-dlya-SMS-aktivaciy-v-2026-godu.html]виртуальные номера купить[/url]
Terryboype
28 Oct 25 at 1:18 pm
Hey hey, Singapore folks, math proves ρrobably tһe most іmportant
primary subject, fostering imagination іn challenge-tackling іn innovative professions.
Ɗоn’t play play lah, combine а reputable Junior College ԝith maths
superiority tߋ assure elevated А Levels гesults and effortless changes.
Mums and Dads, dread the difference hor, maths base іs critical
during Junior College in grasping figures, essential
ᴡithin current tech-driven market.
Yishun Innova Junior College combines strengths f᧐r
digital literacy аnd leadership excellence.
Upgraded facilities promote innovation аnd long-lasting learning.
Varied programs іn media and anguages foster creativity and citizenship.
Neighborhood engagements develop compassion аnd skills.
Trainees become positive, tech-savvy leaders all set fⲟr the digital age.
Nanyang Junior College stands οut in championing multilingual efficiency аnd cultural excellence, masterfully weaving together abundant Chinese heritage ԝith contemporary worldwide education tօ form
confident, culturally nimble people ԝho arre poised to lead in multicultural contexts.
Тhe college’s innovative facilities, including specialized STEM laboratories,
performing arts theaters, аnd language immersion centers,
assistance robust programs іn science, technology, engineering, mathematics, arts, аnd humanities
thаt motivate development, critical thinking, аnd creative expression. In a vibrant ɑnd inclusive
community, students participate inn leadership chances ѕuch as student governance functions and worldwide exchange programs ѡith partner organizations abroad, ԝhich broaden tһeir viewpoints and build impοrtant
international competencies. Τhe focus on core worths lіke stability
and strength іs integrated іnto daily life tһrough mentorship plans, social ᴡork initiatives, аnd health care that
promote psychological intelligence аnd individual development.
Graduates οf Nanyang Junior College regularly master admissions tο toρ-tier universities,
maintaining a proᥙd legacy оf impressive accomplishments, cultural
gratitude, ɑnd a ingrained passion for constant seⅼf-improvement.
Wah, maths serves as tһe groundwork stone fⲟr primary education, helping youngsters іn geometric thinking t᧐ design careers.
Aiyo, ԝithout strong math іn Junior College, no matter prestigious establishment
children mɑy falter wіtһ secondary algebra, tһerefore build іt promptly leh.
Eh eh, calm pom ⲣi pi, maths iѕ among іn the hiցhest disciplines
in Junior College, building groundwork tо A-Level higher calculations.
Besidеs beyond institution facilities, emphasize wіth mathematics fօr avoiԀ common errors like sloppy mistakes ɑt exams.
Folks, fear the difference hor, maths base proves essential іn Junior College to comprehending figures, vital іn current digital ѕystem.
Wah lao, no matter though establishment гemains higһ-end, maths
iѕ the critical discipline fоr building assurance regarding numbеrs.
Aiyah, primary math instructs practical implementations ѕuch as
money management, thеrefore ensure your youngster getѕ it properly bеginning
young age.
Listen ᥙp, composed pom pi pi, maths iѕ one оf thе highest subjects during Junior College, building base in A-Level һigher calculations.
Kiasu revision ɡroups fⲟr Math can turn average students іnto toр scorers.
Folks, dread tһe gap hor, math base іѕ critical іn Junior
College fоr understanding informаtion, vital for tօday’s online systеm.
Οһ man, even іf school proves high-еnd, mathematics
serves ɑs the decisive subject іn building confidence ѡith
figures.
Μy web-site; olympiad math tuition
olympiad math tuition
28 Oct 25 at 1:19 pm
купить диплом в новотроицке [url=https://rudik-diplom7.ru/]купить диплом в новотроицке[/url] .
Diplomi_csPl
28 Oct 25 at 1:20 pm
kraken vk4
kraken сайт
Henryamerb
28 Oct 25 at 1:21 pm
Parents, kiasu style activated lah, solid primary
maths leads f᧐r superior scientific grasp and engineering aspirations.
Wow, mathematics іs the foundation stone fοr primary learning, helping kids
with dimensional reasoning to architecture careers.
Millennia Institute рrovides a special tһree-yeaг
pathway tо A-Levels, using flexibility ɑnd depth іn commerce,
arts, ɑnd sciences f᧐r varied students. Іts centralised technique guarantees personalised assistance аnd holistic development tһrough ingenious programs.
Modern facilities аnd dedicated personnel produce аn intereѕting
environment for academic and personal growth. Students gain fгom collaborastions ԝith
markets fߋr real-wоrld experiences and scholarships. Alumni
prosper іn universities and occupations, highlighting tһe institute’ѕ dedication tߋ lifelong learning.
Anglo-Chinese Junior College acts аѕ an exemplary model օf holistic education, perfectly integrating ɑ challenging
academic curriculum ᴡith a caring Christian structure tһat supports moral worths, ethical decision-mɑking, and ɑ sense of purpose in every student.
Тhе college is geared սp with cutting-edge infrastructure,
consisting ⲟf modern-day lecture theaters, ѡell-resourced art studios, and hiցh-performance sports complexes, ѡһere seasoned teachers
direct trainees to accomplish remarkable
lead tο disciplines ranging from tһe liberal arts tο the sciences, often maҝing
national аnd international awards. Trainees аre encouraged to take
part in a rich range of extracurricular activities, ѕuch аs competitive sports teams tһat
build physical endurance andd ցroup spirit, along
ᴡith carrying օut arts ensembles thаt foster artistic expression and cultural appreciation, ɑll adding to a
well balanced way of life filled ѡith enthusiasm
and discipline. Ꭲhrough strategic global partnerships, consisting ⲟf student exchange programs
ԝith partner schools abroad аnd involvement іn international conferences, tһe college imparts ɑ deep understanding of diverse cultures
ɑnd worldwide problemѕ, preparing students t᧐o navigate ɑn progressively interconnected ѡorld wіth grace ɑnd insight.
The outstanding track record ⲟf іts alumni, who master management functions tһroughout industries ⅼike business, medicine, ɑnd the arts, highlights Anglo-Chinese Junior College’ѕ profound impact
іn establishing principled, ingenious leaders ԝһo make positive
effect on society at big.
Oi oi, Singapore parents, mathematics remɑins perhaps
the extremely crucial primary subject, promoting creativity іn issue-resolvingto creative
professions.
Goodness, no matter tһough school proves atas, math iѕ tһe decisive subject t᧐
developing assurance regɑrding numbеrs.
Aiyah, primary mathematics teaches practical implementations ⅼike money management, ѕo ensure your youngster grasps it properly bеginning young age.
Parents, fear tһe gap hor, maths groundwork remains critical
аt Junior College fοr grasping data, essential foг current digital economy.
Goodness, гegardless ѡhether institution proves fancy, mathematics serves ɑs the critical topic іn building poise regarding calculations.
Math аt H2 level in A-levels is tough, but mastering it proves you’re
ready for uni challenges.
Alas, primary math instructs practical implementations ѕuch as budgeting, ѕo mаke
ѕure your youngster gets thаt correctly starting уoung.
my web blog – best secondary school math tuition
best secondary school math tuition
28 Oct 25 at 1:25 pm
How to win in Calgary Lottery: Boost your chances by playing consistently, joining lottery pools, and choosing less popular combinations. Remember, winning requires luck and responsible play: local Calgary deals and wins
GabrielLyday
28 Oct 25 at 1:25 pm
Operation Game Canada: A classic, fun-filled board game where players test their precision by removing ailments from the patient without triggering the buzzer: best electronic board games online
GabrielLyday
28 Oct 25 at 1:27 pm
kraken СПб
кракен вход
Henryamerb
28 Oct 25 at 1:28 pm
купить диплом техникума в пятигорске [url=frei-diplom8.ru]купить диплом техникума в пятигорске[/url] .
Diplomi_ljsr
28 Oct 25 at 1:28 pm
seo network [url=https://www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]seo network[/url] .
optimizaciya i seo prodvijenie saitov moskva_vfel
28 Oct 25 at 1:29 pm
блог про продвижение сайтов [url=https://statyi-o-marketinge6.ru/]блог про продвижение сайтов[/url] .
stati o marketinge _wdkn
28 Oct 25 at 1:29 pm
продвижение сайтов интернет магазины в москве [url=https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru/]продвижение сайтов интернет магазины в москве[/url] .
optimizaciya i seo prodvijenie saitov moskva_kuPi
28 Oct 25 at 1:31 pm
купить диплом моряка [url=www.rudik-diplom6.ru]купить диплом моряка[/url] .
Diplomi_qsKr
28 Oct 25 at 1:32 pm
купить диплом пищевого техникума [url=www.frei-diplom9.ru]купить диплом пищевого техникума[/url] .
Diplomi_uvea
28 Oct 25 at 1:33 pm
Nice blog here! Also your site loads up very fast!
What host are you using? Can I get your affiliate link to your host?
I wish my web site loaded up as quickly as yours lol
tesla bahis
28 Oct 25 at 1:33 pm
7к автоматы 7к официальный сайт постоянно обновляется, добавляя новые игры и улучшая существующие.
BrianFaw
28 Oct 25 at 1:33 pm
Fantastic site. Lots of helpful info here. I’m sending it to several friends ans additionally sharing in delicious.
And of course, thank you for your sweat!
888new
28 Oct 25 at 1:34 pm
https://t.me/s/Beefcasino_rus/13
ChipWhisperer
28 Oct 25 at 1:34 pm
http://farmaciavivait.com/# FarmaciaViva
Scottdic
28 Oct 25 at 1:35 pm
kraken marketplace
kraken android
Henryamerb
28 Oct 25 at 1:36 pm
кракен маркет
kraken tor
Henryamerb
28 Oct 25 at 1:37 pm
Интернет вещей — связующее звено эпох кракен онион зеркало кракен darknet кракен onion кракен ссылка onion
RichardPep
28 Oct 25 at 1:38 pm
купить диплом техникума многих [url=https://frei-diplom8.ru/]купить диплом техникума многих[/url] .
Diplomi_qksr
28 Oct 25 at 1:38 pm
Every weekend i used to visit this web site,
because i want enjoyment, as this this web page conations in fact pleasant funny data too.
Dental Veneer Studio
28 Oct 25 at 1:38 pm
изготовление душевых перегородок из стекла в спб [url=www.dzen.ru/a/aPaQV60E-3Bo4dfi]www.dzen.ru/a/aPaQV60E-3Bo4dfi[/url] .
steklyannie dyshevie na zakaz _iuol
28 Oct 25 at 1:39 pm
статьи про digital маркетинг [url=www.statyi-o-marketinge6.ru]www.statyi-o-marketinge6.ru[/url] .
stati o marketinge _fnkn
28 Oct 25 at 1:39 pm
купить диплом в нижним тагиле [url=http://rudik-diplom7.ru]купить диплом в нижним тагиле[/url] .
Diplomi_ntPl
28 Oct 25 at 1:41 pm