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!
Thankfulness to my father who told me concerning this webpage, this web site is truly remarkable.
Rico Valbit
14 Aug 25 at 3:26 am
Заказать диплом об образовании!
Мы готовы предложить дипломы психологов, юристов, экономистов и других профессий по приятным ценам— [url=http://clickup-web.ru/]clickup-web.ru[/url]
Lazrfmd
14 Aug 25 at 3:26 am
На сайте https://eliseevskiydom.ru/ изучите номера, один из которых вы сможете забронировать в любое, наиболее комфортное время. Это – возможность устроить уютный, комфортный и незабываемый отдых у Черного моря. Этот дом находится в нескольких минутах ходьбы от пляжа. Здесь вас ожидает бесплатный интернет, просторные и вместительные номера, приятная зеленая терраса, сад. Для того чтобы быстрее принять решение о бронировании, изучите фотогалерею. Имеются номера как для семейных, так и тех, кто прибыл на отдых один.
FucivAsync
14 Aug 25 at 3:30 am
диплом с проводкой купить [url=https://arus-diplom35.ru/]диплом с проводкой купить[/url] .
Diplomi_ulOn
14 Aug 25 at 3:31 am
віршик для мами на день народження
Haroldmog
14 Aug 25 at 3:32 am
Hi mates, its fantastic article about teachingand fully defined, keep it up all
the time.
Fynzario
14 Aug 25 at 3:35 am
Hey, I think your site might be having browser compatibility issues.
When I look at your blog site in Opera, it looks fine but when opening in Internet Explorer, it
has some overlapping. I just wanted to give you a quick heads
up! Other then that, fantastic blog!
to288
14 Aug 25 at 3:37 am
Selecting the right broker is one of the most important decisions for any trader. Pay attention to licensing, commission rates, order execution speed, and customer support quality. Don’t focus solely on low fees — security and fund protection often matter more. Read reviews, compare terms, and test demo accounts before committing real capital.
gatis eglitis exante
gatis eglitis sanctions
14 Aug 25 at 3:39 am
Важной частью реабилитации является социализация пациента, возвращение его к активной общественной жизни и формирование новых, здоровых привычек. Для этого в клинике организуются различные мероприятия и программы адаптации.
Получить дополнительные сведения – https://lechenie-narkomanii-tver0.ru/klinika-lechenie-narkomanii-v-tveri/
DavidUnows
14 Aug 25 at 3:39 am
Indian Meds One: top 10 pharmacies in india – Indian Meds One
RoccoaritA
14 Aug 25 at 3:40 am
reputable indian pharmacies: Indian Meds One – Indian Meds One
JamesHeelo
14 Aug 25 at 3:42 am
Espectro de vibracion
Equipos de calibracion: esencial para el desempeno fluido y eficiente de las dispositivos.
En el campo de la avances contemporanea, donde la rendimiento y la seguridad del sistema son de alta significancia, los equipos de equilibrado juegan un rol esencial. Estos equipos adaptados estan disenados para ajustar y estabilizar piezas moviles, ya sea en herramientas manufacturera, automoviles de traslado o incluso en dispositivos caseros.
Para los profesionales en reparacion de dispositivos y los especialistas, operar con aparatos de ajuste es fundamental para promover el desempeno fluido y seguro de cualquier mecanismo movil. Gracias a estas soluciones avanzadas sofisticadas, es posible limitar significativamente las movimientos, el zumbido y la tension sobre los soportes, prolongando la vida util de piezas valiosos.
Igualmente significativo es el funcion que tienen los aparatos de ajuste en la servicio al comprador. El ayuda experto y el reparacion constante empleando estos dispositivos facilitan proporcionar prestaciones de gran nivel, incrementando la agrado de los compradores.
Para los duenos de proyectos, la contribucion en sistemas de ajuste y dispositivos puede ser esencial para mejorar la eficiencia y eficiencia de sus sistemas. Esto es especialmente significativo para los inversores que dirigen pequenas y intermedias emprendimientos, donde cada elemento importa.
Ademas, los dispositivos de equilibrado tienen una amplia implementacion en el sector de la prevencion y el control de nivel. Posibilitan localizar posibles fallos, previniendo arreglos elevadas y danos a los dispositivos. Ademas, los informacion generados de estos equipos pueden aplicarse para optimizar metodos y incrementar la presencia en sistemas de investigacion.
Las sectores de aplicacion de los dispositivos de equilibrado cubren variadas industrias, desde la manufactura de transporte personal hasta el control de la naturaleza. No importa si se trata de enormes elaboraciones manufactureras o reducidos establecimientos hogarenos, los aparatos de equilibrado son indispensables para garantizar un operacion eficiente y libre de interrupciones.
SamuelDep
14 Aug 25 at 3:42 am
funny shooter 2 unblocked
What’s up Dear, are you in fact visiting this web site on a regular basis,
if so then you will absolutely get good know-how.
funny shooter 2 unblocked
14 Aug 25 at 3:43 am
You could definitely see your skills within the article you write.
The sector hopes for even more passionate writers like
you who are not afraid to mention how they believe.
All the time go after your heart.
บาคาร่า
14 Aug 25 at 3:44 am
https://wanderlog.com/view/qlbvxvmwzc/
Kevincat
14 Aug 25 at 3:47 am
В экстренной ситуации на фоне алкоголя — обращайтесь к скорой помощи Narcology Clinic в Москве. Качественный выезд нарколога, медицинская поддержка, нейтрализация последствий и помощь в восстановлении.
Получить дополнительные сведения – [url=https://skoraya-narkologicheskaya-pomoshch11.ru/]платная наркологическая помощь москва[/url]
PeterVoils
14 Aug 25 at 3:50 am
20
Исследовать вопрос подробнее – [url=https://skoraya-narkologicheskaya-pomoshch-moskva13.ru/]narkologicheskaya-pomoshch-na-domu moskva[/url]
BobbyDag
14 Aug 25 at 3:52 am
Link exchange is nothing else but it is simply placing
the other person’s blog link on your page at proper place and other person will also do same in support
of you.
AI Arbitrage
14 Aug 25 at 3:52 am
I visited many web sites however the audio quality for
audio songs current at this web site is genuinely wonderful.
Scott
14 Aug 25 at 3:55 am
Купить диплом об образовании!
Мы изготавливаем дипломы любой профессии по выгодным ценам— [url=http://dip-expert.ru/]dip-expert.ru[/url]
Lazrbzh
14 Aug 25 at 3:55 am
Скорая наркологическая помощь в Москве — Narcology Clinic выезжает круглосуточно напрямую к пациенту. Срочные капельницы, детокс, контроль состояния и экстренная поддержка. Анонимно, профессионально, оперативно.
Подробнее тут – [url=https://skoraya-narkologicheskaya-pomoshch12.ru/]наркологическая помощь телефон москве[/url]
Brianges
14 Aug 25 at 3:59 am
real mexican pharmacy USA shipping: Mexican Pharmacy Hub – Mexican Pharmacy Hub
JamesHeelo
14 Aug 25 at 4:01 am
гидроизоляция цена [url=http://gidroizolyaciya-cena-3.ru]http://gidroizolyaciya-cena-3.ru[/url] .
gidroizolyaciya cena_puSi
14 Aug 25 at 4:02 am
https://www.themeqx.com/forums/users/agafqigo/
VanceTox
14 Aug 25 at 4:05 am
Hey I know this is off topic but I was wondering if you knew of any widgets I could add to
my blog that automatically tweet my newest twitter updates.
I’ve been looking for a plug-in like this for
quite some time and was hoping maybe you would have some experience with something like this.
Please let me know if you run into anything. I truly enjoy reading your blog
and I look forward to your new updates. https://tw.8fun.net/bbs/space-uid-364203.html
диплом о высшем образовании купить в красноярске
14 Aug 25 at 4:06 am
Дисконт-центр Румба в Санкт-Петербурге — это более 100 магазинов брендов со скидками до 70%. Одежда, обувь и аксессуары по выгодным ценам. Заходите на сайт, чтобы узнать подробности и планировать выгодный шопинг уже сегодня https://rumbastock.ru/
ThomasHes
14 Aug 25 at 4:11 am
Сайт https://interaktivnoe-oborudovanie.ru/ – это оборудование для бизнеса и учебных заведений по выгодной стоимости. У нас: интерактивное оборудование, проекционное оборудование, видео стены, профессиональные панели, информационные киоски и многое другое. Ознакомьтесь с нашим существенным каталогом!
wocecsTah
14 Aug 25 at 4:15 am
It’s very effortless to find out any topic on web
as compared to books, as I found this post at this site.
강남쩜오
14 Aug 25 at 4:16 am
Mexican Pharmacy Hub: best mexican online pharmacies – best mexican online pharmacies
Justinsoync
14 Aug 25 at 4:22 am
Fastidious answer back in return of this difficulty with genuine arguments
and describing all about that.
Tokenpocket wallet
14 Aug 25 at 4:24 am
https://odysee.com/@kaskiblaess4
Kevincat
14 Aug 25 at 4:26 am
Awesome article.
Immediate Edge
14 Aug 25 at 4:29 am
Экстренная наркологическая служба в Москве от Narcology Clinic предлагает оперативный выезд врача на дом. Срочный детокс, стабилизация и круглосуточная поддержка пациента с полным соблюдением конфиденциальности.
Подробнее можно узнать тут – [url=https://skoraya-narkologicheskaya-pomoshch-moskva11.ru/]вызвать наркологическую помощь[/url]
ThomasREIBE
14 Aug 25 at 4:33 am
кашпо с автополивом цена [url=http://kashpo-s-avtopolivom-kazan.ru/]http://kashpo-s-avtopolivom-kazan.ru/[/url] .
gorshok s avtopolivom_vsei
14 Aug 25 at 4:36 am
оформление перепланировки квартиры в Москве [url=https://taksafonchik.borda.ru/?1-19-0-00000148-000-0-0-1754486136]оформление перепланировки квартиры в Москве [/url] .
proekt pereplanirovki v Moskve _jupn
14 Aug 25 at 4:40 am
Normally I do not read article on blogs, however I
wish to say that this write-up very compelled me to take a look at and do so!
Your writing style has been surprised me. Thanks, quite
nice post.
betpuan
14 Aug 25 at 4:45 am
https://odysee.com/@naderscamp66
VanceTox
14 Aug 25 at 4:45 am
Аренда авто Краснодар посуточно
MarvinJak
14 Aug 25 at 4:47 am
Современная наркологическая клиника — это не просто учреждение для экстренной помощи, а центр комплексной поддержки человека, столкнувшегося с зависимостью. В «КузбассМед» в Новокузнецке реализуется модель интенсивного вмешательства, где используются новейшие медицинские технологии, мультидисциплинарный подход и мобильные выездные службы. Специалисты готовы прибыть на дом за 30 минут с полным набором оборудования и медикаментов, обеспечив пациенту помощь в привычной и безопасной среде. Наркология здесь строится на индивидуализации: каждый случай рассматривается отдельно, с учётом психофизического состояния, анамнеза и жизненного контекста пациента.
Изучить вопрос глубже – http://narkologicheskaya-klinika-novokuzneczk0.ru
Morrislycle
14 Aug 25 at 4:47 am
Оперативное лечение на дому имеет ряд значимых преимуществ, особенно когда каждая минута имеет значение:
Ознакомиться с деталями – [url=https://narco-vivod-clean.ru/]вывод из запоя круглосуточно в санкт-петербурге[/url]
AnthonyFug
14 Aug 25 at 4:50 am
проект перепланировки в Москве [url=www.eisberg.forum24.ru/?1-3-0-00000376-000-0-0-1754486777]проект перепланировки в Москве [/url] .
proekt pereplanirovki v Moskve _hdpn
14 Aug 25 at 4:51 am
Great post! I really appreciated reading about Lucky Jet.
It’s such a fun game, and the thrill of choosing when to cash out is what makes it unique.
Kazino-Uz.top
14 Aug 25 at 4:59 am
подключение интернета омск
volgograd-domashnij-internet005.ru
домашний интернет омск
internetvolgogradelini
14 Aug 25 at 5:00 am
Экстренная помощь при алкоголизме от Narcology Clinic в Москве — выезд врачей в любую точку города, купирование острых состояний, поддержка пациента до стабильного состояния, профессионально и в конфиденциальности.
Получить дополнительную информацию – [url=https://skoraya-narkologicheskaya-pomoshch15.ru/]наркологическая помощь на дому москва[/url]
Davidpoido
14 Aug 25 at 5:01 am
I do consider all the concepts you have presented in your post.
They are really convincing and will certainly work.
Still, the posts are too short for starters. May just you please
prolong them a little from subsequent time?
Thanks for the post.
آخرین مهلت ثبت نام دانشگاه علمی کاربردی بدون کنکور
14 Aug 25 at 5:01 am
I always emailed this weblog post page to all my associates, since if like
to read it after that my friends will too.
Zyven Yield
14 Aug 25 at 5:02 am
https://kemono.im/bgybadqu/guanchzhou-kupit-ekstazi-mdma-lsd-kokain
Kevincat
14 Aug 25 at 5:05 am
Heya just wanted to give you a brief heads up and let you know a few of the pictures aren’t
loading correctly. I’m not sure why but I think its a linking issue.
I’ve tried it in two different web browsers and
both show the same outcome.
adam and eve discount code
14 Aug 25 at 5:05 am
If you want to improve your experience only keep
visiting this website and be updated with the most recent
news posted here.
Summers Plumbing Heating & Cooling
14 Aug 25 at 5:06 am
20
Выяснить больше – [url=https://skoraya-narkologicheskaya-pomoshch16.ru/]круглосуточная наркологическая помощь[/url]
Richardner
14 Aug 25 at 5:12 am