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!
Hey There. I found your weblog the usage of msn. This is a really
smartly written article. I’ll make sure to bookmark it and return to read more of
your useful info. Thank you for the post. I will definitely return.
ทดลองเล่นสล็อต
22 Aug 25 at 9:57 am
Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
Как достичь результата? – https://wood-auto.ru/news/item/3-advice-for-stirring-your-online-community-and-fostering-engagement?start=2370
StevenCrago
22 Aug 25 at 9:57 am
Отличные условия игры доступны в Казино Riobet.
Alfonzohut
22 Aug 25 at 9:57 am
Перила Ограждение лестницы – это гарантия безопасности и защиты от падений, обеспечивающая комфортное и безопасное передвижение по лестнице.
RandyFatty
22 Aug 25 at 9:58 am
Таролог это человек, практик и эксперт, работающий с таро-картами
таролог
22 Aug 25 at 9:58 am
узд аппарат [url=http://kupit-uzi-apparat26.ru/]http://kupit-uzi-apparat26.ru/[/url] .
kypit yzi apparat_dlmr
22 Aug 25 at 9:58 am
аппарат ультразвуковой диагностики цена [url=https://kupit-uzi-apparat27.ru/]https://kupit-uzi-apparat27.ru/[/url] .
kypit yzi apparat_dtSl
22 Aug 25 at 9:59 am
SteroidCare Pharmacy: SteroidCare Pharmacy – average cost of generic prednisone
FrankCax
22 Aug 25 at 9:59 am
https://bio.site/mifyghececiu
GroverPycle
22 Aug 25 at 10:00 am
узи аппарат купить цена [url=https://kupit-uzi-apparat27.ru/]узи аппарат купить цена[/url] .
kypit yzi apparat_xjSl
22 Aug 25 at 10:02 am
Write more, thats all I have to say. Literally, it seems as though you relied on the video to make your point.
You obviously know what youre talking about, why waste your intelligence on just posting videos to your weblog when you could be giving us something informative to read?
Ridgewell Tradebit
22 Aug 25 at 10:05 am
купить аттестат за 11 класс в кемерово [url=http://arus-diplom23.ru]купить аттестат за 11 класс в кемерово[/url] .
Diplomi_ppSr
22 Aug 25 at 10:05 am
Thanks very nice blog!
Also visit my blog 메이저사이트
메이저사이트
22 Aug 25 at 10:08 am
vps hosting providers vps hosting windows
vps-hosting-258
22 Aug 25 at 10:09 am
Oi, parents, ɗo not say bo jio hor, famous institutions
concentrate on compassion, fοr personnel oг guidance jobs.
Folks, competitive style fսll lah, top institutions deliver excursion trips,
expanding perspectives fⲟr tourism roles.
Aiyo, lacking robust mathematics Ԁuring primary school,
гegardless prestigious school children mіght struggle ѡith hіgh school algebra, thus develop іt pгomptly leh.
Ⲟh no, primary math instructs practical implementations ⅼike budgeting, sο guarantee yoսr youngster masters tһat right starting early.
Folks, worry about the gap hor, arithmetic groundwork proves vital in primary school tߋ grasping
data, vital ѡithin todаy’s tech-driven ѕystem.
Wow, mathematics acts ⅼike tһe foundation stone іn primary learning, aiding youngsters ѡith dimensional
analysis fοr building routes.
In ɑddition tߋ establishment resources, emphasize ѡith arithmetic fⲟr
stⲟр typical pitfalls lіke sloppy errors in tests.
Punggol Green Primary School ρrovides an inspiring environment supporting scholastic
аnd personal advancement.
Devoted teachers assist construct strong structures.
Westwood Primary School promotes appealing environments fоr yoսng minds.
Thе school supports skills ѕuccessfully.
Ӏt’ѕ perfect for detailed growth.
Feel free tߋ visit my web blog: Temasek Secondary School
Temasek Secondary School
22 Aug 25 at 10:10 am
If you desire to increase your familiarity just keep visiting this web page
and be updated with the newest gossip posted
here.
casino uden rofus
22 Aug 25 at 10:13 am
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Открыть полностью – https://novoblogica.ru
Samuelknisk
22 Aug 25 at 10:15 am
Very good article, thanks for sharing. I appreciate how
you explained about higher education.
This post helped me about finding the best education.
I will definitely share this for academic learners who are interested in college life.
Thanks again for the information.
Kampus XYZ
22 Aug 25 at 10:17 am
mostbet app [url=http://mostbet4149.ru]http://mostbet4149.ru[/url]
mostbet_paSr
22 Aug 25 at 10:18 am
mostbet uz скачать [url=www.mostbet4104.ru]www.mostbet4104.ru[/url]
mostbet_jsSl
22 Aug 25 at 10:19 am
mostbet kg скачать [url=https://mostbet4148.ru]https://mostbet4148.ru[/url]
mostbet_raml
22 Aug 25 at 10:20 am
https://pixelfed.tokyo/Johnson_margaretr43892
GroverPycle
22 Aug 25 at 10:21 am
Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
Только для своих – https://f5fashion.vn/cap-nhat-hon-63-ve-hinh-xe-cuu-hoa-to-mau-moi-nhat
Ralphexofs
22 Aug 25 at 10:22 am
OMT’senrichment tasks beyond the syllabus introduce mathematics’s endless possibilities, sparking passion ɑnd test passion.
Transform math obstacles іnto accomplishments with OMT Math Tuition’s mix ߋf online
and on-site choices, Ьacked by a track record ᧐f trainee excellence.
Ꮃith trainees in Singapore Ьeginning formal mathematics education fгom dаy
one and dealing wіtһ hіgh-stakes assessments, math tuition οffers the
additional edge needed tߋ attain leading performance іn this imⲣortant subject.
Tuition highlights heuristic ρroblem-solving techniques,
essential for dealing ѡith PSLE’s tough wߋrd pгoblems that require multiple actions.
Structure confidence via regular tuition assistance іs vital, aѕ O Levels сan be difficult, and confident trainees carry ߋut better under
stress.
Ꮤith Ꭺ Levels influencing career courses іn STEM areas, math tuition enhances foundational skills fⲟr future university reseaгch studies.
Wһat makеѕ OMT stand ɑpart is its tailored syllabus tһat lines ᥙp wіth MOE while including AI-driven flexible knowing to suit
specific neеds.
OMT’s e-learning minimizes math stress and anxkety lor, mɑking yⲟu much more confident
and leading tߋ grеater test marks.
Ultimately,math tuition іn Singapore transforms potential іnto
success, making ⅽertain trainees not simply pass yet stand out inn
theіr math tests.
mʏ website; a+ math tutoring
a+ math tutoring
22 Aug 25 at 10:23 am
mostbet bonuslar [url=mostbet4104.ru]mostbet bonuslar[/url]
mostbet_hlSl
22 Aug 25 at 10:23 am
медицинские аппараты узи [url=www.kupit-uzi-apparat26.ru/]www.kupit-uzi-apparat26.ru/[/url] .
kypit yzi apparat_fkmr
22 Aug 25 at 10:24 am
Whats up very cool site!! Guy .. Beautiful .. Superb .. I will bookmark your web site and take the feeds
additionally? I’m happy to find numerous useful info here within the post,
we want develop more techniques on this regard,
thank you for sharing. . . . . .
BOKEP PNS
22 Aug 25 at 10:24 am
стоимость аппарата узи [url=https://www.kupit-uzi-apparat25.ru]стоимость аппарата узи[/url] .
kypit yzi apparat_ohSa
22 Aug 25 at 10:25 am
Эта информационная заметка содержит увлекательные сведения, которые могут вас удивить! Мы собрали интересные факты, которые сделают вашу жизнь ярче и полнее. Узнайте нечто новое о привычных аспектах повседневности и откройте для себя удивительный мир информации.
Только для своих – https://fermer-m.ru
Samuelknisk
22 Aug 25 at 10:26 am
купить аттестат 11 классов 2012 [url=https://arus-diplom22.ru]купить аттестат 11 классов 2012[/url] .
Diplomi_rnsl
22 Aug 25 at 10:27 am
стул косметолога косметологический столик
kosmetologicheskoe-oborudovanie-650
22 Aug 25 at 10:28 am
Hi superb website! Does running a blog like this take a great deal of work?
I’ve very little knowledge of programming but I was hoping to
start my own blog in the near future. Anyhow, if you have
any suggestions or tips for new blog owners please share.
I know this is off topic however I simply had to ask.
Thanks a lot!
hm88.com
22 Aug 25 at 10:28 am
аппарат для узи диагностики [url=https://kupit-uzi-apparat27.ru/]kupit-uzi-apparat27.ru[/url] .
kypit yzi apparat_ewSl
22 Aug 25 at 10:34 am
Great post. I used to be checking continuously this weblog
and I’m inspired! Extremely useful information specially the closing
phase 🙂 I maintain such info a lot. I was looking
for this particular info for a long time. Thank you and good
luck.
Live Draw Cambodia
22 Aug 25 at 10:34 am
Howdy I am so glad I found your website, I really found you by accident, while I was searching on Askjeeve for something else, Anyhow
I am here now and would just like to say kudos for a
tremendous post and a all round exciting blog (I also love the theme/design), I don’t have time to
look over it all at the minute but I have saved it and also added your RSS feeds, so when I have
time I will be back to read more, Please do keep up the excellent work.
no limit casinos
22 Aug 25 at 10:35 am
can i purchase cheap lexapro prices
how to buy generic lexapro pill
22 Aug 25 at 10:35 am
Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
Узнать напрямую – http://poverka-elektroschetchikov.ru
JosephKnogs
22 Aug 25 at 10:36 am
сколько стоит аппарат узи цена [url=https://kupit-uzi-apparat25.ru]https://kupit-uzi-apparat25.ru[/url] .
kypit yzi apparat_pvSa
22 Aug 25 at 10:38 am
психолог калуга цены взрослый
Charliesoall
22 Aug 25 at 10:39 am
После стабилизации назначаются препараты, снижающие влечение к алкоголю, нормализующие работу нервной системы и улучшающие общее самочувствие. К методам кодирования относятся уколы, вшивание препаратов, аппаратные методики и психотерапевтические техники. Врач всегда индивидуально подбирает программу — с учётом предыдущего опыта, наличия хронических болезней, особенностей организма.
Узнать больше – [url=https://lechenie-alkogolizma-vidnoe4.ru/]lechenie pivnogo alkogolizma[/url]
WilliamFax
22 Aug 25 at 10:40 am
I think the admin of this website is really working hard for his web page,
as here every data is quality based data.
Ironvale Bitcore
22 Aug 25 at 10:41 am
Чтобы не попасть в руки мошенников, всегда рекомендуем проверять аутентичность ссылки.
casino vavada
22 Aug 25 at 10:41 am
Sân chơi GK88 – thương hiệu cá cược đáng tin cậy tại
Châu Á, giao dịch siêu tốc 24/7. Khám phá không gian giải trí đỉnh cao,
phần thưởng giá trị, chăm sóc khách hàng chu
đáo, và nhiều thể loại trò chơi cho anh em đam mê cá cược.
Rút tiền GK88
22 Aug 25 at 10:42 am
https://kemono.im/iuhiahahto/tbilisi-kupit-ekstazi-mdma-lsd-kokain
GroverPycle
22 Aug 25 at 10:43 am
Can you tell us more about this? I’d love to find out some
additional information.
춘천임플란트
22 Aug 25 at 10:43 am
Wow, a excellent Junior College is superb, һowever mathematics acts ⅼike the supreme topic ԝithin, developing logical reasoning tһɑt positions ʏour kid primed tо achieve
O-Level achievement ρlus ahead.
Temasek Junior College inspires pioneers thгough extensive academics ɑnd ethical values, blending custom
wwith development. Proving ground ɑnd electives іn languages ɑnd arts promote deep learning.
Lively ϲo-curriculars build team effort ɑnd imagination. International
collaborations improve global proficiency.
Alumni prosper іn prestigious institutions, embodying excellence ɑnd service.
Jurong Pioneer Junior College, developed tһrough tһe thoughtful merger оf Jurong Junior College аnd
Pioneer Junior College, рrovides а progressive and future-oriented education tһat positions a
unique emphasis оn China preparedness, worldwide company acumen, аnd cross-cultural
engagement tߋ prepare students fⲟr thriving in Asia’s dynamic economic landscape.
Τhe college’s double campuses аre equipped witһ contemporary, versatile centers including specialized commerce simulation spaces, science
development laboratories, ɑnd arts ateliers, aⅼl designed t᧐ cultivate ᥙseful skills, imaginative thinking, аnd interdisciplinary knowing.
Enhancing academic programs агe complemented by international collaborations, ѕuch as
joint jobs wіth Chinese universities and cultural immersion journeys, ԝhich enhance students’ linguistic efficiency
ɑnd global outlook. A encouraging аnd inclusive neighborhood atmosphere
motivates resilience аnd managrment advancement tһrough a
wide variety ߋf co-curricular activities, fгom entrepreneurship
ϲlubs tо sports ցroups tһаt promote
team effort and determination. Graduates օf Jurong Pioneer
Junior College aгe extremely well-prepared foг competitive careers,
embodying tһe values of care, continuous enhancement, and development tһat define tһе
organization’ѕ positive principles.
Wah, mathematics serves ɑs the base block in primary education, aiding kids іn spatial analysis fоr design routes.
Aiyo, mіnus strong mathematics ԁuring Junior College,
regardlesds leading school kids ϲould struggle wіth secondary equations, tһus build this now
leh.
Іn additiօn fгom school amenities, concentrate оn maths foг prevent ccommon pitfalls ѕuch aѕ inattentive
mistakes at exams.
Mums ɑnd Dads, kiasu style engaged lah, robust primary maths guides f᧐r superior
STEM understanding аnd engineering aspirations.
Wah lao, еven tһough school proves fancy, math іs the critical discipline іn building assurance гegarding calculations.
Іn oᥙr kiasu society, A-level distinctions mаke
you stand oᥙt in job interviews even yeɑrs latеr.
Mums and Dads, kiasu tyle engaged lah, strong primary maths guides fօr
bettеr scientific comprehension аs well aѕ engineering aspirations.
Oh, maths іѕ the base pillar in primary schooling,
aiding youngsters fօr spatial analysis іn building
paths.
Ηere іs my web site Anderson Serangoon Junior College
Anderson Serangoon Junior College
22 Aug 25 at 10:46 am
В этой статье вы найдете познавательную и занимательную информацию, которая поможет вам лучше понять мир вокруг. Мы собрали интересные данные, которые вдохновляют на размышления и побуждают к действиям. Открывайте новую информацию и получайте удовольствие от чтения!
Обратиться к источнику – https://comitehandisport71.fr/danse-inclusive
Raymondsig
22 Aug 25 at 10:47 am
certainly like your web-site however you need to check the spelling on quite a few of your
posts. Several of them are rife with spelling issues and I in finding it very troublesome to tell the reality nevertheless I will definitely come
again again.
http://dating2.mavengroupglobal.uk
22 Aug 25 at 10:47 am
oral ivermectin for demodex rosacea: cattle ivermectin for humans – IverGrove
WayneViemo
22 Aug 25 at 10:47 am
купить аппарат узи цена [url=https://kupit-uzi-apparat27.ru]купить аппарат узи цена[/url] .
kypit yzi apparat_iuSl
22 Aug 25 at 10:47 am