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!
Good article. I absolutely love this website. Stick with it!
Zeno Flow Engine
8 Oct 25 at 11:35 am
купить снюс Купить снюс – это распространенный запрос среди потребителей никотиносодержащей продукции, которые предпочитают бездымные альтернативы курению. Однако важно помнить, что продажа и употребление снюса регулируются законодательством различных стран, и могут быть ограничения или полный запрет на его реализацию. Перед покупкой необходимо ознакомиться с местными законами и правилами, чтобы избежать возможных проблем с законом. Кроме того, следует обращать внимание на состав продукта, приобретать его только у проверенных продавцов и учитывать потенциальные риски для здоровья, связанные с употреблением никотина.
Charlesjom
8 Oct 25 at 11:39 am
Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
Продолжить чтение – http://health.slickjump.com/cat?c=18
Louisrhync
8 Oct 25 at 11:39 am
Всё дело в том, что лава насыщает землю полезными микроэлементами
и делает её очень плодородной.
интернет казино
8 Oct 25 at 11:40 am
I am sure this post has touched all the internet people, its
really really good post on building up new website.
Live Draw Sdy
8 Oct 25 at 11:44 am
Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
Запросить дополнительные данные – http://health.slickjump.com/cat?c=18
ErnestoHot
8 Oct 25 at 11:44 am
This is a fantastic read! Your perspective is refreshing.
I found it particularly interesting how you discussed the importance of
innovation in our daily lives. If you’re interested, visit(https://arialief–usa.us/).
Arialief
8 Oct 25 at 11:48 am
What’s up to all, it’s in fact a good for me to pay a quick visit this web page, it includes priceless Information.
adameve coupon codes
8 Oct 25 at 11:48 am
linebet download app install
linebet ios app
8 Oct 25 at 11:49 am
Для перехода в мобильную версию
достаточно зайти на сайт через браузер на гаджете.
казино аркада играть
8 Oct 25 at 11:50 am
%url+Prostavive
Prostavive
8 Oct 25 at 11:51 am
Prednisone tablets online USA: how to buy prednisone – Prednisone tablets online USA
WillieRuivy
8 Oct 25 at 11:51 am
Howdy I am so excited I found your blog, I really found you by
accident, while I was searching on Yahoo for something else, Nonetheless I am here now and would just like to say thanks for a incredible post and
a all round exciting blog (I also love the theme/design),
I don’t have time to read it all at the moment but I have
book-marked it and also included your RSS feeds, so when I have time I will be back to read a
great deal more, Please do keep up the fantastic job.
new online casino
8 Oct 25 at 11:51 am
http://portal.krasno.ru/viewtopic.php?f=2&t=54649&p=56838
Thomasbip
8 Oct 25 at 11:53 am
Вас интересуют природные богатства России? Давайте исследуем их вместе!
Особенно понравился материал про Изучение ООПТ России: парки, заповедники, водоемы.
Смотрите сами:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Что думаете о красоте природы России? Делитесь мнениями!
fixRow
8 Oct 25 at 11:53 am
новости мирового спорта [url=https://novosti-sporta-7.ru/]novosti-sporta-7.ru[/url] .
novosti sporta_roOt
8 Oct 25 at 11:55 am
перевод документов в сочи с нотариусом Агентство переводов Сочи – это организация, предоставляющая услуги по переводу текстов и документов с различных языков мира. Агентства переводов обычно располагают штатом квалифицированных переводчиков, редакторов и корректоров, а также используют современные технологии для обеспечения высокого качества и оперативности перевода. При выборе агентства переводов важно учитывать его репутацию, опыт работы, специализацию на конкретных тематиках, стоимость услуг и отзывы клиентов. Также важно убедиться в наличии у агентства гарантии качества перевода.
AllenExpiz
8 Oct 25 at 11:56 am
hello!,I love your writing very much! share we keep in touch extra
about your post on AOL? I need a specialist on this house to unravel my problem.
May be that’s you! Looking forward to see you.
Lunel Bitrow
8 Oct 25 at 12:00 pm
It’s great that SugarMute USA offers such natural solutions for sugar cravings!
I’ve read many positive experiences about their approach.
Thank you for the post! For more details, check out https://sugarmute–usa.com/.
SugarMute order
8 Oct 25 at 12:01 pm
linebet live
linebet promo code
8 Oct 25 at 12:02 pm
1 вин регистрация [url=https://www.1win5516.ru]https://www.1win5516.ru[/url]
1win_xmOa
8 Oct 25 at 12:03 pm
купить диплом с занесением в реестр цена [url=http://frei-diplom4.ru/]купить диплом с занесением в реестр цена[/url] .
Diplomi_odOl
8 Oct 25 at 12:05 pm
Undeniably imagine that that you stated. Your favorite
reason appeared to be at the internet the simplest factor to consider of.
I say to you, I certainly get irked while other folks consider
issues that they plainly do not recognize about.
You controlled to hit the nail upon the highest and also
defined out the entire thing with no need side-effects , people could take
a signal. Will probably be again to get more. Thanks
web site
8 Oct 25 at 12:06 pm
https://dzen.ru/holstai Обложки маркетплейс – это визуальные элементы, представляющие товары на страницах маркетплейсов, таких как Wildberries, Ozon и другие. Они играют ключевую роль в привлечении внимания потенциальных покупателей и формировании первого впечатления о товаре. Обложки должны быть привлекательными, информативными, соответствовать требованиям маркетплейса и отражать суть предлагаемого продукта. Важно использовать качественные изображения, грамотно расположенные элементы дизайна и учитывать психологию потребителей при создании обложек для маркетплейсов.
JeromeThatt
8 Oct 25 at 12:07 pm
generic gabapentin pharmacy USA: gabapentin trade name australia – gabapentin kick in time
Morrisluh
8 Oct 25 at 12:09 pm
Dragon Money – стильное онлайн-казино с широким ассортиментом игр. Привлекательные бонусы, мгновенные выплаты и удобный интерфейс делают игру комфортной и выгодной
dragon money официальный сайт
JamesBob
8 Oct 25 at 12:16 pm
супер прогнозы на спорт [url=https://kompyuternye-prognozy-na-futbol23.ru/]kompyuternye-prognozy-na-futbol23.ru[/url] .
komputernie prognozi na fytbol_idPi
8 Oct 25 at 12:18 pm
выбор между гипсовой и цементной штукатуркой
Shawnsuene
8 Oct 25 at 12:18 pm
вывод из запоя москва недорого [url=https://vyvod-iz-zapoya-9.ru/]vyvod-iz-zapoya-9.ru[/url] .
vivod iz zapoya_ekEl
8 Oct 25 at 12:18 pm
linebet review
linebet bonus
8 Oct 25 at 12:23 pm
An intelligent AI WordPress plugin for generating content, posts, images, and website optimization. Easy installation, flexible settings, and full AI support.
RobertLop
8 Oct 25 at 12:24 pm
Hey! I understand this is kind of off-topic but I needed to
ask. Does managing a well-established website like yours take a lot of work?
I am brand new to running a blog but I do write in my journal every day.
I’d like to start a blog so I can easily share my personal experience and thoughts online.
Please let me know if you have any suggestions or tips for
new aspiring bloggers. Appreciate it!
au88 casino
8 Oct 25 at 12:25 pm
100 прогнозы на футбол [url=http://www.kompyuternye-prognozy-na-futbol23.ru]http://www.kompyuternye-prognozy-na-futbol23.ru[/url] .
komputernie prognozi na fytbol_clPi
8 Oct 25 at 12:27 pm
вывод. из. запоя. на. дому. москва. [url=www.vyvod-iz-zapoya-9.ru]www.vyvod-iz-zapoya-9.ru[/url] .
vivod iz zapoya_okEl
8 Oct 25 at 12:27 pm
В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
Всё, что нужно знать – https://souz-prokat.ru/products/prokat-izmereniya-urovny-radiazii-dozimetr
Michaelweimi
8 Oct 25 at 12:28 pm
This is my first time visit at here and i am really happy to read everthing at single place.
zumospin iDEAL
EarnestAbent
8 Oct 25 at 12:30 pm
надежные прогнозы на спорт [url=https://www.prognozy-ot-professionalov4.ru]https://www.prognozy-ot-professionalov4.ru[/url] .
prognozi ot professionalov_gtOr
8 Oct 25 at 12:31 pm
стеллажи складские Надежные металлические стеллажи для склада от производителя «Металлоизделия» Организуйте складское пространство с максимальной эффективностью! Компания «Металлоизделия» предлагает профессиональные металлические стеллажи для складов любого размера и назначения. Наши стеллажи для склада — это идеальное решение для хранения товаров, оборудования, архивов и материалов. Они позволяют использовать каждый квадратный метр площади по максимуму, обеспечивая легкий доступ к любой единице хранения. Почему выбирают наши стеллажи? Прочность и долговечность: Мы используем высококачественный стальной прокат и усиленные конструкции, выдерживающие значительные нагрузки (до 5000 кг на ячейку и более). Универсальность: Широкая линейка моделей — полочные, паллетные (фронтальные, гравитационные), консольные. Подберем решение под ваши задачи. Безопасность: Все конструкции имеют антикоррозийное покрытие и рассчитаны на многократную сборку-разборку. Строгое соблюдение ГОСТов. Модульность и масштабируемость: Вы можете легко нарастить систему или изменить конфигурацию при расширении склада. Выгодная цена: Работаем без посредников, так как являемся производителем.
Jasontaink
8 Oct 25 at 12:31 pm
seroquel without a prescription
buy generic seroquel pills
8 Oct 25 at 12:33 pm
Get a free Edumail and temporary email instantly at EdumailFree.com.
Enjoy a secure, fast, and anonymous email service perfect for students, professionals, and temporary use.
No signup required!
Get edu email for discounts
8 Oct 25 at 12:33 pm
Excellent, what a web site it is! This webpage presents valuable information to us,
keep it up.
Pink Salt Trick Reviews
8 Oct 25 at 12:34 pm
Dragon Money – современное онлайн-казино с огромным выбором игр. Выгодные бонусы, быстрые выплаты и удобный интерфейс обеспечивают приятный игровой процесс
драгон мани рабочее зеркало
RonnieSak
8 Oct 25 at 12:34 pm
Nice blog here! Also your web site loads
up very fast! What host are you using? Can I get your affiliate link to your
host? I wish my site loaded up as quickly as yours lol
toto togel
8 Oct 25 at 12:34 pm
Minotaurus presale docs detail fair distribution. $MTAUR’s play-to-earn model sustainable. Endless mazes promise hours of play.
minotaurus presale
WilliamPargy
8 Oct 25 at 12:35 pm
Hey there! Quick question that’s entirely off topic.
Do you know how to make your site mobile friendly? My website looks weird when browsing from my
apple iphone. I’m trying to find a template or plugin that might be
able to resolve this issue. If you have any suggestions,
please share. Many thanks!
adameve promo code
8 Oct 25 at 12:37 pm
Rеmain smart ѡith Kaizenaire.com, Singapore’s tօp collector of deals,
promotions, аnd shopping occasions.
Singapore’ѕ fame aѕ a shopping pⅼace iѕ enhanced by citizens’ love fօr deals.
Singaporeans ⅼike joining flash crowds in public spaces fⲟr
spontaneous fun, and remember tօ stay updated օn Singapore’ѕ
neѡest promotions аnd shopping deals.
Careless Ericka ᥙses edgy, speculative fashion, treasured ƅy bold Singaporeans fоr theiг daring cuts and vibrant prints.
BMW delivers һigh-end vehicles ԝith innovative performance lah, treasured Ьy Singaporeans fоr tһeir driving
enjoyment ɑnd standing sign lor.
Itacho Sushi serves costs sashimi аnd rolls, adored fⲟr top notch fish and stylish presentations.
Eh,Singaporeans, ƅetter book mark Kaizenaire.ϲom lah,
check սsually for fresh discounts mah.
mу web site; seal of orichalcos ude promotions
seal of orichalcos ude promotions
8 Oct 25 at 12:38 pm
Magnificent items from you, man. I have be mindful your stuff prior to and you are just too great.
I really like what you’ve got right here, really like what you
are saying and the way in which you assert it. You are making it enjoyable and
you continue to care for to stay it smart.
I can not wait to learn much more from you. This is actually a terrific site.
Vonk Tradewise Ervaringen
8 Oct 25 at 12:39 pm
математический прогноз на футбол [url=https://kompyuternye-prognozy-na-futbol23.ru]https://kompyuternye-prognozy-na-futbol23.ru[/url] .
komputernie prognozi na fytbol_erPi
8 Oct 25 at 12:43 pm
вывод из запоя цены москва [url=http://vyvod-iz-zapoya-9.ru/]http://vyvod-iz-zapoya-9.ru/[/url] .
vivod iz zapoya_spEl
8 Oct 25 at 12:43 pm
Woah! I’m really loving the template/theme of this website.
It’s simple, yet effective. A lot of times it’s very hard to get that “perfect balance” between superb usability and appearance.
I must say that you’ve done a awesome job with this. Additionally,
the blog loads very fast for me on Safari.
Exceptional Blog!
Aurelia Portdex Recensione
8 Oct 25 at 12:43 pm