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!
Скачать видео с YouTube https://www.fsaved.com онлайн: MP4/WEBM/3GP, качество 144p–4K, конвертация в MP3/M4A, поддержка Shorts и плейлистов, субтитры и обложки. Без регистрации, быстро и безопасно, на телефоне и ПК. Используйте только с разрешения правообладателя и в рамках правил YouTube.
fsaved-57
24 Oct 25 at 5:57 am
Hi! I just wish to offer you a big thumbs up
for the great information you have got here on this post.
I will be coming back to your site for more soon.
best drugs
24 Oct 25 at 5:57 am
kraken обмен
кракен
JamesDaync
24 Oct 25 at 5:58 am
Hello there, just became alert to your blog through Google,
and found that it is truly informative. I’m going to watch out for brussels.
I’ll be grateful if you continue this in future.
A lot of people will be benefited from your writing.
Cheers!
เว็บ 888
24 Oct 25 at 5:58 am
займы без отказа займ всем
srochnie-zaymy-949
24 Oct 25 at 5:59 am
кракен маркет
кракен вход
кракен даркнет маркет
24 Oct 25 at 6:00 am
1xbet resmi sitesi [url=https://www.1xbet-giris-1.com]https://www.1xbet-giris-1.com[/url] .
1xbet giris_uxkt
24 Oct 25 at 6:01 am
срочно онлайн займ отказа https://zaimy-91.ru
srochnie-zaymy-234
24 Oct 25 at 6:01 am
1xbet t?rkiye [url=1xbet-giris-7.com]1xbet t?rkiye[/url] .
1xbet giris_osKn
24 Oct 25 at 6:02 am
1xbet yeni giri? adresi [url=www.1xbet-giris-4.com/]www.1xbet-giris-4.com/[/url] .
1xbet giris_kfSa
24 Oct 25 at 6:03 am
1xbet g?ncel giri? [url=https://1xbet-4.com]https://1xbet-4.com[/url] .
1xbet_erol
24 Oct 25 at 6:05 am
Скачать видео с YouTube https://www.fsaved.com онлайн: MP4/WEBM/3GP, качество 144p–4K, конвертация в MP3/M4A, поддержка Shorts и плейлистов, субтитры и обложки. Без регистрации, быстро и безопасно, на телефоне и ПК. Используйте только с разрешения правообладателя и в рамках правил YouTube.
fsaved-518
24 Oct 25 at 6:05 am
I go to see day-to-day a few sites and sites to read articles or reviews, however
this weblog offers quality based content.
Adventure Gear for Dogs
24 Oct 25 at 6:05 am
Soziale Medienplattformen sind zu einer großartigen Quelle für Medieninhalte wie Videos und Musik geworden.
savefrom net
24 Oct 25 at 6:06 am
Скачать видео с YouTube https://www.fsaved.com онлайн: MP4/WEBM/3GP, качество 144p–4K, конвертация в MP3/M4A, поддержка Shorts и плейлистов, субтитры и обложки. Без регистрации, быстро и безопасно, на телефоне и ПК. Используйте только с разрешения правообладателя и в рамках правил YouTube.
fsaved-324
24 Oct 25 at 6:07 am
кредит займ быстрый микрозайм онлайн без проверок
srochnie-zaymy-36
24 Oct 25 at 6:07 am
1x bet giri? [url=https://www.1xbet-giris-8.com]1x bet giri?[/url] .
1xbet giris_tyPn
24 Oct 25 at 6:07 am
купить диплом медсестры [url=www.frei-diplom14.ru]купить диплом медсестры[/url] .
Diplomi_gvoi
24 Oct 25 at 6:08 am
бк 1 win зеркало [url=http://1win5519.ru/]http://1win5519.ru/[/url]
1win_kg_yfEr
24 Oct 25 at 6:08 am
Как юридическое лицо, оценили профессионализм сотрудников и прозрачность процесса. Все документы были оформлены чётко и вовремя, что позволило избежать простоев. Отличный сервис для компаний, работающих с импортом: Таможенное оформление во Внуково
Brianovalt
24 Oct 25 at 6:08 am
Как купить Мефедрон кристаллы в Яхроме?Обратил внимание на https://1024×600.ru
– судя по отзывам ок. Цены приемлемые, доставляют. Кто-нибудь пробовал? Как с чистотой?
Stevenref
24 Oct 25 at 6:09 am
kraken РФ
кракен сайт
JamesDaync
24 Oct 25 at 6:09 am
Thank you for sharing your thoughts. I really appreciate your efforts and I will be
waiting for your further post thanks once again.
cialis
24 Oct 25 at 6:09 am
Эта статья сочетает в себе как полезные, так и интересные сведения, которые обогатят ваше понимание насущных тем. Мы предлагаем практические советы и рекомендации, которые легко внедрить в повседневную жизнь. Узнайте, как улучшить свои навыки и обогатить свой опыт с помощью простых, но эффективных решений.
Прочитать подробнее – https://www.beritasulut.co.id/2018/11/06/call-center-manado-siaga112-jadi-finalis-kompetisi-cc-world-global-2018-di-republik-ceko
Davidgrori
24 Oct 25 at 6:09 am
1xbet t?rkiye [url=1xbet-giris-10.com]1xbet t?rkiye[/url] .
1xbet giris_obka
24 Oct 25 at 6:10 am
1 xbet giri? [url=1xbet-giris-8.com]1xbet-giris-8.com[/url] .
1xbet giris_toPn
24 Oct 25 at 6:11 am
advancedtradingtools – Their downloadable tools integrated smoothly into my trading setup — very satisfied.
Gladys Sliz
24 Oct 25 at 6:11 am
1xbet spor bahislerinin adresi [url=http://www.1xbet-giris-7.com]1xbet spor bahislerinin adresi[/url] .
1xbet giris_vxKn
24 Oct 25 at 6:11 am
официальный сайт конторы 1win [url=http://1win5519.ru/]официальный сайт конторы 1win[/url]
1win_kg_rfEr
24 Oct 25 at 6:11 am
http://confiafarmacia.com/# Viagra sin prescripcion medica
JamesSlilk
24 Oct 25 at 6:11 am
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Детали по клику – https://vedikabookstores.com/stay-informed-and-inspired-popular-non-fiction-ebooks
Ronaldfek
24 Oct 25 at 6:12 am
1x lite [url=https://1xbet-giris-4.com]https://1xbet-giris-4.com[/url] .
1xbet giris_liSa
24 Oct 25 at 6:12 am
В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
Посмотреть всё – https://mediaperaevents.com/lo-esencial-es-invisible-a-los-ojos
Danielcog
24 Oct 25 at 6:12 am
1xbet g?ncel giri? [url=https://1xbet-giris-1.com]https://1xbet-giris-1.com[/url] .
1xbet giris_lzkt
24 Oct 25 at 6:13 am
It is really a nice and useful piece of info. I’m satisfied that
you shared this helpful information with us. Please stay
uss iformed like this. Thank you for sharing.
Vape Juices
24 Oct 25 at 6:13 am
Скачать видео с YouTube https://www.fsaved.com онлайн: MP4/WEBM/3GP, качество 144p–4K, конвертация в MP3/M4A, поддержка Shorts и плейлистов, субтитры и обложки. Без регистрации, быстро и безопасно, на телефоне и ПК. Используйте только с разрешения правообладателя и в рамках правил YouTube.
fsaved-453
24 Oct 25 at 6:13 am
kraken ссылка
kraken android
kraken vk2
24 Oct 25 at 6:15 am
1xbet [url=https://1xbet-giris-9.com/]1xbet[/url] .
1xbet giris_uhon
24 Oct 25 at 6:16 am
kraken 2025
kraken tor
kraken сайт
24 Oct 25 at 6:16 am
1win контора [url=https://1win5518.ru/]https://1win5518.ru/[/url]
1win_kg_idkl
24 Oct 25 at 6:17 am
1xbet lite [url=1xbet-giris-9.com]1xbet lite[/url] .
1xbet giris_ohon
24 Oct 25 at 6:19 am
Многие пользователи постоянно пытаются найти надежный и проверенный путь для входа на маркетплейс Kraken, встречаясь с обилием мошеннических ресурсов и устаревшей инструкциями. Дабы минимизировать подобные проблемы и сэкономить свои нервы, существует простое и эффективное место для поиска. [url=https://diagnozaobd2.ro/]ссылка кракен[/url] Именно данный проверенный канал обеспечивает пользователю беспрепятственное попадание на оригинальный сайт Kraken, в обход любые посредников и потенциальные угрозы. Такой подход является самым разумным решением для тех, кто ценит собственную анонимность и желает иметь полную уверенность в защите личного профиля и средств на нем.
Othex
24 Oct 25 at 6:20 am
xbet [url=https://1xbet-giris-10.com]xbet[/url] .
1xbet giris_zbka
24 Oct 25 at 6:21 am
1xbet yeni giri? [url=https://1xbet-giris-1.com]https://1xbet-giris-1.com[/url] .
1xbet giris_xckt
24 Oct 25 at 6:21 am
1xbet giris [url=http://www.1xbet-giris-8.com]1xbet giris[/url] .
1xbet giris_pxPn
24 Oct 25 at 6:22 am
1xbet t?rkiye giri? [url=http://1xbet-giris-4.com/]1xbet t?rkiye giri?[/url] .
1xbet giris_poSa
24 Oct 25 at 6:23 am
kraken
kraken vk3
JamesDaync
24 Oct 25 at 6:23 am
1xbet t?rkiye giri? [url=http://1xbet-giris-7.com/]1xbet t?rkiye giri?[/url] .
1xbet giris_lyKn
24 Oct 25 at 6:25 am
купить диплом в калининграде [url=https://rudik-diplom9.ru]купить диплом в калининграде[/url] .
Diplomi_wwei
24 Oct 25 at 6:27 am
Secondary school math tuition іs impоrtant for building yоur
Secondary 1 child’ѕ resilience against academic setbacks in Singapore.
Lor, it’s no surprise Singapore students lead іn global math, they worҝ һard mah.
Aѕ moms and dads, outcome ѕpecify ᴡith Singapore math tuition’s dedication. Secondary math tuition dedicates need.
Тhrough secondary 1 math tuition, guidelines exponent.
Secondary 2 math tuition рrovides flexible scheduling options, mɑking it accessible
fοr busy trainees. Wіth emphasis on problem-solving techniques, secondary 2
math tuition enhances critical believing skills. Moms ɑnd dads appreciɑtе hоw secondary 2 math tuition offers progress reports tօ
track enhancement. This targeted secondary 2 math tuition helps аvoid learning gaps fгom expanding.
Ꮃith O-Levels on the horizon, secondary 3 math exams underscore tһe importancе of
peak efficiency to protect helpful positions. Strong outcomes һelp ᴡith targeted tuition іf required, optimizing Sеc 4
efforts. Іn Singapore, tһis ϲan lead to better
L1R5 scores and broader instructional options.
Singapore’ѕ education values secondary 4 exams f᧐r preferences.
Secondary 4 math tuition fits night students. Τhiѕ respect increases О-Level consistency.
Secondary 4 math tuition accommodates.
Mathematics ցoes Ьeyond exams; it’s a cornerstone competency іn the AI boom, powering smart һome integrations.
Excellence іn mathematics іs rooted іn passion fоr thе subject and daily life applications.
Ꭲhe imⲣortance of ѕuch practice іs evident іn how it
allοws students to compare theiг performance аgainst standards from t᧐p Singapore secondary schools fоr math exams.
In Singapore, online math tuition е-learning boosts scores Ƅy enabling cross-device access fⲟr seamless study continuity.
Heng lor, relax ɑh, secondary school life balanced, no unnecessary stress.
OMT’ѕ alternative technique nurtures not јust
abilities howevеr happiness іn mathematics, inspiring trainees to welcome thе subject and shine
in tһeir examinations.
Ԍet ready for success іn upcoming exams ԝith OMT Math Tuition’ѕ
exclusive curriculum, designed tߋ promote critical thinking ɑnd ѕelf-confidence in eveгy
student.
As math forms the bedrock ߋf logical thijking аnd important рroblem-solving in Singapore’ѕ education system, expert math tuition οffers the individualized guidance essential tо turn difficulties into victories.
primary school math tuition develops examination endurance tһrough timed drills, simulating tһe PSLE’s
two-paper format ɑnd assisting trainees handle tіme
successfully.
Offered tһe һigh stakes ᧐f O Levels for hіgh school progression in Singapore,
math tuition optimizes possibilities fοr leading qualities ɑnd desired positionings.
Math tuition ɑt thе junior college degree emphasizes conceptual quality ⲟveг memorizing memorization, essential fοr
tackling application-based A Level questions.
OMT sets іtself apart ѡith a syllabus designed tο improve MOE material tһrough tһorough explorations of geometry
evidence аnd theories for JC-level learners.
Unrestricted retries оn quizzes sia,excellent foг
grasping subjects and accomplishing tһose Α grades іn math.
Witһ limited course timе in schools, math tuition expands learning һourѕ,
critical for understanding thе comprehensive Singapore mathematics syllabus.
Мy webpage maths tuition (https://filedn.eu/)
https://filedn.eu/
24 Oct 25 at 6:30 am