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-diplom2.ru]https://rudik-diplom2.ru[/url] .
Diplomi_aepi
15 Oct 25 at 10:24 am
В этой статье-обзоре мы соберем актуальную информацию и интересные факты, которые освещают важные темы. Читатели смогут ознакомиться с различными мнениями и подходами, что позволит им расширить кругозор и глубже понять обсуждаемые вопросы.
Изучите внимательнее – https://netsurf.monster/theseus-cast
NathanNef
15 Oct 25 at 10:24 am
ZenCare Meds com: safe online medication store – ZenCareMeds
AndrewPal
15 Oct 25 at 10:25 am
купить диплом в калуге [url=www.rudik-diplom7.ru]купить диплом в калуге[/url] .
Diplomi_gkPl
15 Oct 25 at 10:27 am
Этот текст призван помочь читателю расширить кругозор и получить практические знания. Мы используем простой язык, наглядные примеры и структурированное изложение, чтобы сделать обучение максимально эффективным и увлекательным.
Это стоит прочитать полностью – https://www.dhosgent.be/leraar
RichardVeics
15 Oct 25 at 10:29 am
Whats up very cool site!! Man .. Excellent .. Wonderful ..
I’ll bookmark your blog and take the feeds also?
I’m satisfied to find a lot of useful information right here within the submit, we need
develop extra strategies on this regard, thanks for sharing.
. . . . .
Lys Finthera Ervaringen
15 Oct 25 at 10:30 am
купить диплом о среднем образовании с занесением в реестр [url=http://frei-diplom1.ru/]купить диплом о среднем образовании с занесением в реестр[/url] .
Diplomi_ahOi
15 Oct 25 at 10:31 am
findyourwayforward – The message gives hope and a clearer path, very nice
Perry Nola
15 Oct 25 at 10:31 am
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Секреты успеха внутри – https://nikpendar.com/students-inducted-into-business-honor-society
Stephencruib
15 Oct 25 at 10:31 am
купить диплом техникума нижний новгород [url=frei-diplom8.ru]купить диплом техникума нижний новгород[/url] .
Diplomi_nksr
15 Oct 25 at 10:31 am
медсестра которая купила диплом врача [url=https://frei-diplom13.ru]медсестра которая купила диплом врача[/url] .
Diplomi_bxkt
15 Oct 25 at 10:32 am
купить диплом механика [url=www.rudik-diplom9.ru]купить диплом механика[/url] .
Diplomi_yjei
15 Oct 25 at 10:33 am
купить диплом в хабаровске [url=www.rudik-diplom2.ru]www.rudik-diplom2.ru[/url] .
Diplomi_bwpi
15 Oct 25 at 10:33 am
With havin so much content and articles do you ever run into any
problems of plagorism or copyright infringement?
My blog has a lot of completely unique content I’ve either written myself or outsourced but it seems a
lot of it is popping it up all over the web without my permission. Do you know any solutions to help stop content from
being stolen? I’d really appreciate it. https://reparatur.it/index.php?title=Benutzer:RandallHeydon46
купить диплом в воронеже
15 Oct 25 at 10:33 am
купить диплом в владивостоке [url=https://rudik-diplom10.ru]купить диплом в владивостоке[/url] .
Diplomi_agSa
15 Oct 25 at 10:33 am
где купить диплом техникума будь [url=www.frei-diplom9.ru]где купить диплом техникума будь[/url] .
Diplomi_bqea
15 Oct 25 at 10:33 am
купить диплом мед колледжа [url=www.frei-diplom11.ru]купить диплом мед колледжа[/url] .
Diplomi_zmsa
15 Oct 25 at 10:34 am
купить диплом в кызыле [url=www.rudik-diplom7.ru]купить диплом в кызыле[/url] .
Diplomi_xgPl
15 Oct 25 at 10:36 am
https://t.me/s/Online_1_xbet/1513
AnthonyFuP
15 Oct 25 at 10:36 am
Медицинский юрист — это специалист, который оказывает юридическую помощь в сфере
медицинской практики. Основная функция этого юриста — защита интересов пациентов и
медицинских учреждений. Профессиональный юрист содействует в разрешении трудных правовых
вопросов, касающихся лечения и предоставления медицинских услуг.
Предоставляемые услуги медицинским юристом
Юрист, работающий в сфере медицины,
предлагает множество услуг, в числе которых:
Правовые консультации по вопросам, связанным с медицинскими правами;
Подготовка и анализ документов;
Защита интересов клиентов в судах;
Представительство в медицинских
организациях;
Содействие в сборе доказательственной базы для
судебных разбирательств;
Работа с жалобами и претензиями к медицинским учреждениям.
Особенности работы медицинского юриста
Востребованность медицинского юриста обусловлена
часто возникающими вопросами, связанными с правами пациентов
и юридическими обязанностями медицинских учреждений.
К таким вопросам могут относиться:
Согласие пациента на лечение;
Обработки персональных данных;
Морального вреда, причиненного некачественным лечением;
Случаев врачебной ошибки.
Рекомендации по выбору медицинского юриста
Выбирая медицинского юриста, следует учитывать несколько важных факторов:
Опыт работы в сфере медицинского права;
Наличие положительных отзывов от клиентов;
Узкая специализация в области медицинского права;
Условия работы, подходящие для клиента;
Способы связи для получения консультаций;
Куда обратиться за помощью
В случае возникновения юридических вопросов лучше
сразу обратиться к медицинскому юристу.
Своевременная помощь на начальном
этапе может оказать значительное влияние
на конечный результат. Звонок
в адвокатскую контору или консультация через сайт помогут быстро
получить необходимую информацию и поддержку.
Безусловно, работа медицинского юриста
включает в себя множество нюансов, и его помощь может быть как в вопросах профилактики, так и
в сложных судебных разбирательствах.
Защита прав пациентов и медицинских организаций — это основа его деятельности, которая требует высокой квалификации
и знаний в области медицинского и правового
законодательства. услуги медицинского юриста
Итоги
Ведение медицинских дел требует глубокого понимания как правовых аспектов, так и особенностей сферы здравоохранения.
Специалист по медицинскому праву
является важным союзником для пациентов и медицинских
организаций. Эффективная юридическая
помощь способна существенно облегчить решение возникающих проблем
и защитить интересы участников.
Роль медицинского юриста особенно важна в следующих обстоятельствах:
Составление и анализ медицинских документов;
Защита интересов пациентов в судебных разбирательствах;
Юридические советы по соблюдению
законодательства в области медицины;
Поддержка в сборе и обработке личных данных;
Защита интересов в ситуациях, когда нарушаются права пациентов.
Сотрудничая с профессионалом, вы можете быть
уверены, что ваше дело будет учтено с учетом всех
деталей и в соответствии с действующими законами.
Юридическая практика в медицине требует от специалиста не только правовых знаний, но и осознания этических принципов,
что обеспечит эффективную защиту интересов клиентов.
Необходимо учитывать, что медицинские разногласия могут затрагивать как эмоциональные, так и финансовые аспекты,
и только опытный адвокат может предложить всесторонний подход к разрешению этих вопросов.
Наличие опытного юриста на вашей стороне может существенно повлиять на исход дела.
Если у вас есть вопросы или требуется консультация, не бойтесь попросить о помощи.
Мы готовы предоставить вам
все необходимые услуги и поддерживать вас на каждом этапе.
Для получения дополнительной информации посетите наш сайт или
свяжитесь с нами по указанным контактам.
Пусть ваши права будут охраняемы, а медицинское лечение проходит без юридических
трудностей.
https://www.cambodb.com/bbs/board.php?bo_table=free&wr_id=85904
15 Oct 25 at 10:37 am
https://telegra.ph/Arkon-alfa-teplovizor-kupit-10-13-3
DennisNeene
15 Oct 25 at 10:37 am
https://t.me/s/Online_1_xbet/1164
AnthonyFuP
15 Oct 25 at 10:37 am
I am not sure where you’re getting your info, but great topic.
I needs to spend some time learning much more or
understanding more. Thanks for fantastic info I was looking for
this info for my mission.
789F01
15 Oct 25 at 10:37 am
Just swapped BNB for $MTAUR—smooth on BSC. Referral rewards motivate sharing. Game’s power-ups via tokens strategic.
minotaurus presale
WilliamPargy
15 Oct 25 at 10:38 am
купить диплом об окончании колледжа [url=www.frei-diplom12.ru/]купить диплом об окончании колледжа[/url] .
Diplomi_wvPt
15 Oct 25 at 10:39 am
купить диплом проведенный [url=http://frei-diplom1.ru/]купить диплом проведенный[/url] .
Diplomi_epOi
15 Oct 25 at 10:40 am
1win az bonus 500 [url=http://1win5005.com]http://1win5005.com[/url]
1win_owml
15 Oct 25 at 10:40 am
где можно купить диплом медсестры [url=https://frei-diplom13.ru]где можно купить диплом медсестры[/url] .
Diplomi_vxkt
15 Oct 25 at 10:40 am
купить диплом техникума об окончании [url=http://frei-diplom9.ru/]купить диплом техникума об окончании[/url] .
Diplomi_mcea
15 Oct 25 at 10:41 am
1win az giriş [url=www.1win5004.com]www.1win5004.com[/url]
1win_fgoi
15 Oct 25 at 10:41 am
https://t.me/s/Online_1_xbet/900
AnthonyFuP
15 Oct 25 at 10:42 am
https://t.me/s/Online_1_xbet/634
AnthonyFuP
15 Oct 25 at 10:42 am
купить диплом инженера механика [url=https://rudik-diplom10.ru]купить диплом инженера механика[/url] .
Diplomi_vySa
15 Oct 25 at 10:43 am
купить речной диплом [url=http://www.rudik-diplom2.ru]купить речной диплом[/url] .
Diplomi_fvpi
15 Oct 25 at 10:44 am
купить легальный диплом колледжа [url=https://www.frei-diplom1.ru]купить легальный диплом колледжа[/url] .
Diplomi_pxOi
15 Oct 25 at 10:45 am
купить диплом в красноярске [url=rudik-diplom7.ru]купить диплом в красноярске[/url] .
Diplomi_rqPl
15 Oct 25 at 10:46 am
купить диплом в сочи [url=rudik-diplom6.ru]купить диплом в сочи[/url] .
Diplomi_zwKr
15 Oct 25 at 10:49 am
купить медицинский диплом медсестры [url=http://frei-diplom13.ru/]купить медицинский диплом медсестры[/url] .
Diplomi_jukt
15 Oct 25 at 10:50 am
диплом купить колледжа искусств пять плюс [url=https://frei-diplom8.ru]https://frei-diplom8.ru[/url] .
Diplomi_nksr
15 Oct 25 at 10:51 am
купить диплом колледжа настоящий [url=http://frei-diplom9.ru/]http://frei-diplom9.ru/[/url] .
Diplomi_cfea
15 Oct 25 at 10:52 am
https://eda-sait.ru/kontakty/
Nathanhip
15 Oct 25 at 10:52 am
Hey there this is kind of of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually code with HTML.
I’m starting a blog soon but have no coding skills so I wanted to get guidance from
someone with experience. Any help would be enormously appreciated!
comet ai browser tamil
15 Oct 25 at 10:53 am
OMT’s bite-sized lessons prevent overwhelm, permitting gradual love fоr mathematics t᧐ grow
and influence consistent exam preparation.
Сhange mathematics obstacles іnto accomplishments ᴡith OMT Math Tuition’ѕ blend of online and on-site choices, bbacked Ƅy
a track record ߋf student excellence.
Ꭲhe holistic Singapore Math method, which develops
multilayered analytical abilities, highlights
ԝhy math tuition іs vital fⲟr mastering
thе curriculum and getting ready foг future careers.
For PSLE achievers, tuition proviɗes mock exams and feedback,
assisting improve responses fⲟr maҳimum marks іn botһ multiple-choice and open-ended sections.
Holistic advancement ѵia math tuition not just increases O
Level scores Ьut additionally ɡrows sensible thinking abilities
useful for lifelong understanding.
Junior college math tuition іs crucial f᧐r А Levels aѕ it
strengthens understanding of innovative calculus topics ⅼike combination techniques аnd differential
equations, ѡhich aгe central to thе examination syllabus.
The individuality оf OMT depends օn іts personalized educational program
tһat bridges MOE syllabus gaps ᴡith supplementary resources ⅼike proprietary worksheets and remedies.
OMT’s e-learning minimizes math anxiety lor, mаking you more positive and causing greater examination marks.
Math tuition рrovides prompt comments օn method efforts, accelerating enhancement fοr
Singapore test takers.
Stop ƅy my web pаge :: math tuition singapore
math tuition singapore
15 Oct 25 at 10:53 am
купить диплом в новороссийске [url=www.rudik-diplom10.ru]купить диплом в новороссийске[/url] .
Diplomi_doSa
15 Oct 25 at 10:54 am
натяжной потолок самара [url=https://natyazhnye-potolki-samara-2.ru/]натяжной потолок самара[/url] .
natyajnie potolki samara_fzPi
15 Oct 25 at 10:54 am
buy clomid: buy propecia – buy amoxil
Andresstold
15 Oct 25 at 10:54 am
купить диплом с реестром цена [url=https://frei-diplom2.ru]купить диплом с реестром цена[/url] .
Diplomi_szEa
15 Oct 25 at 10:55 am
купить диплом вуза занесением реестр [url=http://frei-diplom3.ru/]http://frei-diplom3.ru/[/url] .
Diplomi_edKt
15 Oct 25 at 10:55 am
диплом техникума колледжа купить [url=frei-diplom12.ru]диплом техникума колледжа купить[/url] .
Diplomi_ywPt
15 Oct 25 at 10:55 am
Having read this I believed it was very informative.
I appreciate you finding the time and effort to put this
short article together. I once again find myself spending a lot of time both reading
and leaving comments. But so what, it was still worth it!
turkey visa for australians
15 Oct 25 at 10:57 am