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!
kraken актуальные ссылки kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
8 Sep 25 at 6:23 am
https://www.brownbook.net/business/54215202/купить-флер-наркотик-экс-нихило/
BillyDon
8 Sep 25 at 6:24 am
https://www.e-stroma.gr/journal3/blog/post?journal_blog_post_id=10
Georgeidomy
8 Sep 25 at 6:26 am
Do you mind if I quote a couple of your posts as long as
I provide credit and sources back to your website? My blog site is in the exact same area of interest as yours and my visitors would truly benefit from a lot of the information you present here.
Please let me know if this alright with you.
Appreciate it!
cipit88
8 Sep 25 at 6:26 am
https://olimpia-nv.ru/about/articls/?kakuyu_podderghku_okazyvaet_professionalynaya_buhgalterskaya_firma_vedeniyu_biznesa.html
Jasonzic
8 Sep 25 at 6:30 am
купить диплом о высшем образовании [url=https://educ-ua3.ru]купить диплом о высшем образовании[/url] .
Diplomi_tqki
8 Sep 25 at 6:31 am
На сайте https://t.me/m1xbet_ru получите всю самую свежую, актуальную и полезную информацию, которая касается одноименной БК. Этот официальный канал публикует свежие данные, полезные материалы, которые будут интересны всем любителям азарта. Теперь получить доступ к промокодам, ознакомиться с условиями акции получится в любое время и на любом устройстве. Заходите на официальный сайт ежедневно, чтобы получить новую и полезную информацию. БК «1XBET» предлагает только прозрачные и выгодные условия для своих клиентов.
Zatupked
8 Sep 25 at 6:32 am
http://www.waltbabylove.com/upload/image/inc/?1xbet_india_promo_codes.html
gbfuifm
8 Sep 25 at 6:33 am
Мы предлагаем документы институтов, расположенных на территории всей России. Купить диплом о высшем образовании:
[url=http://jobteck.com/companies/all-diplomy/]купить аттестаты за 11 вечерней школе 1992 2002 п яр или глазов[/url]
Diplomi_ovPn
8 Sep 25 at 6:34 am
Нужна профессиональную медпомощь рядом с вами? В медцентре [url=https://kristall-med.ru]https://kristall-med.ru[/url] оказываются услуги современной эндоскопии, функциональной диагностики и ДНК-диагностики — с профессиональным оборудованием и комфортной обстановкой. Центр работает с современными технологиями, работает с лицензированными специалистами и проводит комплексные исследования. Всё это — без лишних хлопот, стабильно и по всем медицинским нормам. Узнайте подробности — функциональная диагностика, генетическое исследование, качественная эндоскопия.
Spravkisnh
8 Sep 25 at 6:34 am
Новые актуальные промокод iherb kod herb для выгодных покупок! Скидки на витамины, БАДы, косметику и товары для здоровья. Экономьте до 30% на заказах, используйте проверенные купоны и наслаждайтесь выгодным шопингом.
promocod-iherb-892
8 Sep 25 at 6:34 am
маркетинговые стратегии статьи [url=https://blog-o-marketinge.ru/]маркетинговые стратегии статьи[/url] .
blog o marketinge_ecSn
8 Sep 25 at 6:37 am
руководства по seo [url=http://blog-o-marketinge.ru/]руководства по seo[/url] .
blog o marketinge_zfSn
8 Sep 25 at 6:41 am
Hello, I enjoy reading all of your post. I like to write a little comment to support you.
http://121.43.129.17/blaineleane512
8 Sep 25 at 6:41 am
darknet site dark market nexus dark [url=https://darknetmarketgate.com/ ]nexus darknet shop [/url]
DwayneAricE
8 Sep 25 at 6:50 am
https://pxlmo.com/Hill_lisan05799
BillyDon
8 Sep 25 at 6:52 am
Эта статья для ознакомления предлагает читателям общее представление об актуальной теме. Мы стремимся представить ключевые факты и идеи, которые помогут читателям получить представление о предмете и решить, стоит ли углубляться в изучение.
Открыть полностью – https://xiuse027.com/2024/01/01/lets-play-cards-and-papers
DavidImags
8 Sep 25 at 6:55 am
Мы готовы предложить документы любых учебных заведений, которые находятся на территории всей РФ. Приобрести диплом университета:
[url=http://woorichat.com/read-blog/54719_diplom-za-11-klass-kupit.html/]купить аттестат за 10 11 класс вечерней школы[/url]
Diplomi_lnPn
8 Sep 25 at 6:55 am
В Люберцах клиника Stop Alko предлагает капельницы от запоя не только с детоксикацией, но и с поддержкой печени, сердца и нервной системы.
Узнать больше – [url=https://kapelnica-ot-zapoya-lyubercy12.ru/]капельница от запоя вызов подольск[/url]
AnthonyVah
8 Sep 25 at 6:56 am
I like the helpful information you provide in your articles.
I’ll bookmark your blog and check again here frequently.
I’m quite certain I will learn a lot of new stuff right
here! Good luck for the next!
Youtube Fast Downloader
8 Sep 25 at 6:56 am
Новые актуальные промокод iherb на заказ для выгодных покупок! Скидки на витамины, БАДы, косметику и товары для здоровья. Экономьте до 30% на заказах, используйте проверенные купоны и наслаждайтесь выгодным шопингом.
promocod-iherb-70
8 Sep 25 at 6:56 am
Публикация приглашает вас исследовать неизведанное — от древних тайн до современных достижений науки. Вы узнаете, как случайные находки превращались в революции, а смелые мысли — в новые эры человеческого прогресса.
Подробная информация доступна по запросу – http://feedc0de.org/index.php?itemid=579&catid=14
Michaeldrype
8 Sep 25 at 6:58 am
оптимизация сайта блог [url=www.blog-o-marketinge.ru/]оптимизация сайта блог[/url] .
blog o marketinge_sjSn
8 Sep 25 at 6:58 am
I’m gone to tell my little brother, that he should
also pay a visit this website on regular basis to get updated from latest reports.
Purchase Nembutal Capsules Online
8 Sep 25 at 6:59 am
Oh my goodness! Impressive article dude! Thank you so much, However I am
having issues with your RSS. I don’t understand why I cannot subscribe to it.
Is there anybody else getting identical RSS problems?
Anyone who knows the answer can you kindly respond?
Thanx!!
Testimonials
8 Sep 25 at 7:01 am
Мы можем предложить документы любых учебных заведений, расположенных в любом регионе Российской Федерации. Заказать диплом о высшем образовании:
[url=http://wikirefuge.lpo.fr/index.php?title=Utilisateur:FreddyRiggs9260/]купить аттестат за 11 класс спб[/url]
Diplomi_icPn
8 Sep 25 at 7:02 am
seo статьи [url=https://blog-o-marketinge.ru/]seo статьи[/url] .
blog o marketinge_juSn
8 Sep 25 at 7:02 am
Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
Узнать напрямую – https://o-s-mtrading.com/best-practices-for-passing-inspection-o-s-m
WalterMEM
8 Sep 25 at 7:03 am
seo блог [url=https://blog-o-marketinge.ru]seo блог[/url] .
blog o marketinge_ocSn
8 Sep 25 at 7:04 am
кракен ссылка kraken kraken onion, kraken onion ссылка, kraken onion зеркала, kraken рабочая ссылка onion, сайт kraken onion, kraken darknet, kraken darknet market, kraken darknet ссылка, сайт kraken darknet, kraken актуальные ссылки, кракен ссылка kraken, kraken официальные ссылки, kraken ссылка тор, kraken ссылка зеркало, kraken ссылка на сайт, kraken онион, kraken онион тор, кракен онион, кракен онион тор, кракен онион зеркало, кракен даркнет маркет, кракен darknet, кракен onion, кракен ссылка onion, кракен onion сайт, kra ссылка, kraken сайт, kraken актуальные ссылки, kraken зеркало, kraken ссылка зеркало, kraken зеркало рабочее, актуальные зеркала kraken, kraken сайт зеркала, kraken маркетплейс зеркало, кракен ссылка, кракен даркнет
RichardPep
8 Sep 25 at 7:09 am
Hmm it appears like your blog ate my first comment (it was extremely long) so I guess I’ll
just sum it up what I had written and say, I’m
thoroughly enjoying your blog. I as well am an aspiring blog blogger but I’m still new to everything.
Do you have any tips for rookie blog writers?
I’d really appreciate it.
Trade Vector AI
8 Sep 25 at 7:10 am
купить старый диплом техникума [url=https://educ-ua3.ru/]купить старый диплом техникума[/url] .
Diplomi_epki
8 Sep 25 at 7:11 am
статьи про продвижение сайтов [url=http://statyi-o-marketinge2.ru/]статьи про продвижение сайтов[/url] .
stati o marketinge_bgKr
8 Sep 25 at 7:12 am
блог про продвижение сайтов [url=https://www.blog-o-marketinge.ru]блог про продвижение сайтов[/url] .
blog o marketinge_ktSn
8 Sep 25 at 7:12 am
Хотите получить профессиональную медпомощь по месту жительства? В медицинском центре [url=https://kristall-med.ru]https://kristall-med.ru[/url] оказываются услуги эндоскопии, функциональных исследований и генетической диагностики — с профессиональным оборудованием и комфортными условиями. Центр применяет инновационные методы, работает с лицензированными специалистами и предлагает полный спектр обследований. Всё это — без лишних хлопот, стабильно и на высоком уровне качества. Смотрите детали — функциональные исследования, анализ ДНК, качественная эндоскопия.
Spravkihfc
8 Sep 25 at 7:12 am
Этот текст призван помочь читателю расширить кругозор и получить практические знания. Мы используем простой язык, наглядные примеры и структурированное изложение, чтобы сделать обучение максимально эффективным и увлекательным.
Подробная информация доступна по запросу – https://lazuardi-haura.sch.id/haura-logo-min
PhilipNam
8 Sep 25 at 7:14 am
https://enginecrux.com/ is a comprehensive online resource dedicated to providing detailed information on various vehicle engines. The website offers in-depth engine specifications, maintenance tips, common issues, and comparative analyses across a wide range of brands including Audi, BMW, Honda, Hyundai, Mercedes-Benz, Toyota, and more. Whether you’re a car enthusiast, a mechanic, or simply interested in automotive technology, EngineCrux serves as a valuable tool for understanding the intricacies of modern engines.
Biqykcejoync
8 Sep 25 at 7:21 am
https://muckrack.com/person-27417053
BillyDon
8 Sep 25 at 7:22 am
Приобрести диплом любого ВУЗа!
Мы предлагаемвыгодно купить диплом, который выполнен на оригинальной бумаге и заверен печатями, штампами, подписями. Документ способен пройти лубую проверку, даже с применением специального оборудования. Достигайте своих целей быстро с нашими дипломами- [url=http://mf.getbb.ru/viewtopic.php?f=28&t=2096/]mf.getbb.ru/viewtopic.php?f=28&t=2096[/url]
Jariortti
8 Sep 25 at 7:22 am
seo и реклама блог [url=http://blog-o-marketinge.ru/]http://blog-o-marketinge.ru/[/url] .
blog o marketinge_ovSn
8 Sep 25 at 7:23 am
маркетинг в интернете блог [url=www.statyi-o-marketinge2.ru]www.statyi-o-marketinge2.ru[/url] .
stati o marketinge_jzKr
8 Sep 25 at 7:24 am
Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
Ссылка на источник – https://www.gasthaus-baule.de/2019/03/25/exploring-street-food-in-bangkok
Perrybuisk
8 Sep 25 at 7:24 am
Can I just say what a comfort to discover someone that actually knows what they’re discussing
on the internet. You certainly know how to bring an issue to light and make it important.
A lot more people should read this and understand this side of your story.
I can’t believe you’re not more popular because you certainly possess the
gift.
Look at my web-site: Aesthetic Women’s Casual Shorts (AOP)
Aesthetic Women's Casual Shorts (AOP)
8 Sep 25 at 7:24 am
PT. Sicurezza Solutions Indonesia provides security
solutions with integrating varieties of security products which can be adjusted to many needs from Access Control, Automatic Door, CCTV, Video
Intercom, Biometric Time & Attendance, etc.
Experience selling and installing security systems for all kinds of
buildings such as private house, apartment, hotel, resort, office,
government building, bank, factory, etc.
COLCOM Hotel Lock,COLCOM Minibar,COLCOM Kettle,COLCOM Kettle Set,COLCOM Locker
Lock,COLCOM Safe Deposit Box,COLCOM Infrared Body Temperature,COLCOM Portable Dishwasher,COLCOM Vaccum Sweep Mop Robot,
COLCOM Accessories,
SAMSUNG Digital Door Lock,SAMSUNG Video Intercom,
DOORHAN Sectional Door,DOORHAN Sliding Gate,DOORHAN Swing Gate,DOORHAN Parking Barrier,
ENIGMA Fingerprint,ENIGMA Automatic and Hermetic Door,ENIGMA Proximity Cards,
ENIGMA Access Control Readers,ENIGMA Access Control System,ENIGMA Electric Lock,ENIGMA Accessories,ENIGMA Parking Barrier,ENIGMA Digital Door Lock,
ENIGMA Body Temperature Screening Smart Camera,ENIGMA Window
Opener,ENIGMA Specialized Curtain Motor,
HID Access Control,HONEYWELL BLACK CCTV Analog System,HONEYWELL BLACK CCTV IP System,APOLLO CCTV,GUARD TOUR,
VIZPIN Smartphone Access Control System,OVAL One Touch Smart Lock,HIK VISION
Body Temperature Scanner
Sicurezza Solutions
8 Sep 25 at 7:26 am
Новые актуальные промокод iherb для выгодных покупок! Скидки на витамины, БАДы, косметику и товары для здоровья. Экономьте до 30% на заказах, используйте проверенные купоны и наслаждайтесь выгодным шопингом.
promocod-iherb-218
8 Sep 25 at 7:26 am
блог seo агентства [url=www.blog-o-marketinge.ru]www.blog-o-marketinge.ru[/url] .
blog o marketinge_pjSn
8 Sep 25 at 7:27 am
nexus market link bitcoin dark web nexus darknet link [url=https://darknetmarketsgate.com/ ]darknet market [/url]
Donaldfup
8 Sep 25 at 7:30 am
digital маркетинг блог [url=http://blog-o-marketinge.ru]digital маркетинг блог[/url] .
blog o marketinge_xdSn
8 Sep 25 at 7:31 am
darkmarket nexus dark nexus market link [url=https://darknetmarketgate.com/ ]nexus market darknet [/url]
DwayneAricE
8 Sep 25 at 7:33 am
Мы можем предложить документы ВУЗов, которые расположены в любом регионе Российской Федерации. Заказать диплом ВУЗа:
[url=http://avva.getbb.ru/viewtopic.php?f=3&t=2231/]где купить аттестат за 11 класс 2015[/url]
Diplomi_eePn
8 Sep 25 at 7:33 am