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=http://www.frei-diplom4.ru]купить проведенный диплом всеми[/url] .
Diplomi_ldOl
1 Nov 25 at 8:25 am
купить диплом логопеда [url=www.rudik-diplom2.ru/]купить диплом логопеда[/url] .
Diplomi_mnpi
1 Nov 25 at 8:25 am
online pharmacy [url=https://safemedsguide.com/#]trusted online pharmacy USA[/url] online pharmacy
Hermanengam
1 Nov 25 at 8:25 am
купить диплом [url=www.rudik-diplom8.ru/]купить диплом[/url] .
Diplomi_jwMt
1 Nov 25 at 8:27 am
медсестра которая купила диплом врача [url=https://frei-diplom13.ru/]медсестра которая купила диплом врача[/url] .
Diplomi_jbkt
1 Nov 25 at 8:27 am
купить диплом в комсомольске-на-амуре [url=http://rudik-diplom4.ru/]купить диплом в комсомольске-на-амуре[/url] .
Diplomi_bzOr
1 Nov 25 at 8:27 am
В этой статье-обзоре мы соберем актуальную информацию и интересные факты, которые освещают важные темы. Читатели смогут ознакомиться с различными мнениями и подходами, что позволит им расширить кругозор и глубже понять обсуждаемые вопросы.
Изучите внимательнее – https://moriyamaseko.wpxblog.jp/%E3%82%B3%E3%83%BC%E3%83%8A%E3%83%B3%EF%BD%90%EF%BD%92%EF%BD%8F%E6%96%B0%E5%AE%88%E5%B1%B1%E5%BA%97%EF%BC%88%E4%BB%AE%E7%A7%B0%EF%BC%89
BrettPeemi
1 Nov 25 at 8:28 am
Safe Meds Guide: promo codes for online drugstores – compare online pharmacy prices
Johnnyfuede
1 Nov 25 at 8:28 am
купить диплом диспетчера [url=https://www.rudik-diplom10.ru]купить диплом диспетчера[/url] .
Diplomi_tsSa
1 Nov 25 at 8:28 am
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Ознакомиться с отчётом – https://flexparagon.com/top-remote-job-opportunities-you-can-apply-for-right-now
Victoreluts
1 Nov 25 at 8:29 am
купить диплом в кропоткине [url=www.rudik-diplom2.ru/]www.rudik-diplom2.ru/[/url] .
Diplomi_zapi
1 Nov 25 at 8:29 am
Статья знакомит с важнейшими моментами, которые сформировали наше общество. От великих изобретений до культурных переворотов — вы узнаете, как прошлое влияет на наше мышление, технологии и образ жизни.
Жми сюда — получишь ответ – https://tokorouta.com/josei-wo-teki-ni-mawasu-uta
CharlieTop
1 Nov 25 at 8:29 am
https://t.me/ud_Kent/61
MichaelPione
1 Nov 25 at 8:29 am
купить диплом в рыбинске [url=http://rudik-diplom9.ru/]http://rudik-diplom9.ru/[/url] .
Diplomi_fmei
1 Nov 25 at 8:29 am
карнизы с электроприводом [url=https://elektrokarniz499.ru/]карнизы с электроприводом[/url] .
elektrokarniz_byKl
1 Nov 25 at 8:30 am
Aussie Meds Hub: AussieMedsHubAu – verified online chemists in Australia
HaroldSHems
1 Nov 25 at 8:31 am
купить проведенный диплом отзывы [url=www.frei-diplom6.ru/]www.frei-diplom6.ru/[/url] .
Diplomi_msOl
1 Nov 25 at 8:31 am
https://t.me/ud_Gizbo/46
MichaelPione
1 Nov 25 at 8:32 am
купить проведенный диплом провести [url=http://frei-diplom1.ru]купить проведенный диплом провести[/url] .
Diplomi_dwOi
1 Nov 25 at 8:32 am
купить диплом в тюмени [url=https://www.rudik-diplom3.ru]купить диплом в тюмени[/url] .
Diplomi_xiei
1 Nov 25 at 8:33 am
купить диплом в зеленодольске [url=http://rudik-diplom11.ru]купить диплом в зеленодольске[/url] .
Diplomi_fhMi
1 Nov 25 at 8:33 am
Hi, I do think this is an excellent website. I stumbledupon it 😉 I
will return once again since I book marked it.
Money and freedom is the best way to change, may you be rich and continue to help others.
ضرایب دروس در امتحان نهایی ۱۴۰۵
1 Nov 25 at 8:34 am
Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
Откройте для себя больше – https://www.tcoberlabill.at/?attachment_id=44
Williamsaw
1 Nov 25 at 8:34 am
медсестра которая купила диплом врача [url=http://frei-diplom13.ru/]медсестра которая купила диплом врача[/url] .
Diplomi_smkt
1 Nov 25 at 8:34 am
Эта статья предлагает живое освещение актуальной темы с множеством интересных фактов. Мы рассмотрим ключевые моменты, которые делают данную тему важной и актуальной. Подготовьтесь к насыщенному путешествию по неизвестным аспектам и узнайте больше о значимых событиях.
Узнать напрямую – https://hearld.news/udderly-unbelievable-first-female-ceo-milks-tech
Davidbit
1 Nov 25 at 8:34 am
купить диплом в севастополе [url=http://rudik-diplom10.ru]купить диплом в севастополе[/url] .
Diplomi_eySa
1 Nov 25 at 8:36 am
купить диплом моториста [url=www.rudik-diplom5.ru]купить диплом моториста[/url] .
Diplomi_nlma
1 Nov 25 at 8:37 am
mostbet kg [url=https://www.mostbet12033.ru]https://www.mostbet12033.ru[/url]
mostbet_kg_xopa
1 Nov 25 at 8:39 am
купить диплом с занесением в реестр в архангельске [url=www.frei-diplom1.ru/]купить диплом с занесением в реестр в архангельске[/url] .
Diplomi_wqOi
1 Nov 25 at 8:41 am
мостбет скачать бесплатно [url=https://mostbet12034.ru]https://mostbet12034.ru[/url]
mostbet_kg_vpPr
1 Nov 25 at 8:41 am
What we’re covering
[url=https://megaweb19at.com]mgmarket7 at[/url]
• Israel is facing growing condemnation after it attacked Hamas leadership in the capital of Qatar, a US ally and key mediator in Gaza ceasefire talks — putting hostage negotiations at risk.
[url=https://megaweb-1at.com]mgmarket6[/url]
• Hamas said the strike killed five members but failed to assassinate the negotiating delegation, the target of the strikes.
• US President Donald Trump has criticized the strike, saying that by the time his administration learned of the attack and told the Qataris, there was little he could do to stop it.
• The attack is the first publicly acknowledged strike on a Gulf state by Israel. Qatar’s prime minister was visibly angry and said his country’s tradition of diplomacy “won’t be deterred.”
https://megaweb-9at.com
mgmarket4.at
JasonBup
1 Nov 25 at 8:41 am
купить диплом в томске [url=http://www.rudik-diplom12.ru]http://www.rudik-diplom12.ru[/url] .
Diplomi_qgPi
1 Nov 25 at 8:42 am
купить диплом повара-кондитера [url=http://rudik-diplom2.ru]купить диплом повара-кондитера[/url] .
Diplomi_uupi
1 Nov 25 at 8:43 am
https://ukmedsguide.com/# legitimate pharmacy sites UK
Haroldovaph
1 Nov 25 at 8:44 am
https://t.me/s/ud_Flagman/51
MichaelPione
1 Nov 25 at 8:45 am
купить аттестат [url=http://rudik-diplom8.ru/]купить аттестат[/url] .
Diplomi_jjMt
1 Nov 25 at 8:45 am
https://t.me/ud_Izzi/60
MichaelPione
1 Nov 25 at 8:46 am
купить диплом техникума цена [url=https://www.educ-ua7.ru]https://www.educ-ua7.ru[/url] .
Diplomi_emea
1 Nov 25 at 8:46 am
как купить легальный диплом о среднем образовании [url=http://www.frei-diplom6.ru]http://www.frei-diplom6.ru[/url] .
Diplomi_wvOl
1 Nov 25 at 8:46 am
купить диплом пту с занесением в реестр [url=http://www.frei-diplom1.ru]купить диплом пту с занесением в реестр[/url] .
Diplomi_hyOi
1 Nov 25 at 8:47 am
купить диплом агронома [url=http://rudik-diplom9.ru/]купить диплом агронома[/url] .
Diplomi_kxei
1 Nov 25 at 8:47 am
First off I want to say fantastic blog! I had a quick
question which I’d like to ask if you do not mind.
I was interested to find out how you center yourself and clear your thoughts prior to writing.
I have had a hard time clearing my mind in getting my thoughts out there.
I do take pleasure in writing but it just seems like the
first 10 to 15 minutes are generally wasted simply just
trying to figure out how to begin. Any ideas or hints?
Thank you!
enjoy
1 Nov 25 at 8:48 am
Bl555
Bl555 app
1 Nov 25 at 8:48 am
Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
Подробная информация доступна по запросу – https://revistashape.com.br/2023/02/04/aruko-x-maringa-assistir-ao-vivo-campeonato-paranaense-de-2023-hoje-04-02-palpites-e-escalacoes
ArthurPef
1 Nov 25 at 8:48 am
купить диплом с занесением в реестр в украине [url=http://www.frei-diplom5.ru]http://www.frei-diplom5.ru[/url] .
Diplomi_fpPa
1 Nov 25 at 8:48 am
Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
Откройте для себя больше – https://www.studioto.com/2022/04/14/a-review-of-all-the-thirty-five-worldwide-fintech
BrianBeise
1 Nov 25 at 8:49 am
купить диплом моториста [url=www.rudik-diplom7.ru/]купить диплом моториста[/url] .
Diplomi_ruPl
1 Nov 25 at 8:49 am
affordable medication Ireland
Edmundexpon
1 Nov 25 at 8:50 am
Надёжные бытовки и дачные домики под ключ с доставкой по Москве и области — визитная карточка https://bitovkimsk.ru/ Производитель предлагает деревянные и металлические модели, хозблоки, мини-домики, бани и дровяники с продуманной тепло и пароизоляцией, аккуратной электрикой и опциями отделки. Прозрачные цены, соблюдение сроков, гарантия на работы и реальные отзывы подтверждают качество. Хотите быстрое, тёплое и долговечное решение для участка? Закажите готовый модуль или проект под задачи — монтаж без хлопот.
taqassLyday
1 Nov 25 at 8:51 am
Do you have a spam problem on this site; I also am a blogger, and I
was wanting to know your situation; many of us have developed
some nice methods and we are looking to swap solutions with others,
please shoot me an e-mail if interested.
Dubai Night Tour From USA
1 Nov 25 at 8:51 am