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!
лайки инстаграм
Williamthimi
16 Aug 25 at 10:07 am
выплаты участникам ‘‚Ћ
Willardken
16 Aug 25 at 10:08 am
По ссылке https://vc.ru/crypto/2132102-obmen-usdt-v-nizhnem-novgorode-podrobnyi-gid-v-2025-godu почитайте информацию про то, как обменять USDT в городе Нижнем Новгороде. Перед вами самый полный гид, из которого вы в подробностях узнаете о том, как максимально безопасно, быстро произвести обмен USDT и остальных популярных криптовалют. Есть информация и о том, почему выгодней сотрудничать с профессиональным офисом, и почему это считается безопасно. Статья расскажет вам и о том, какие еще криптовалюты являются популярными в Нижнем Новгороде.
KawamAntep
16 Aug 25 at 10:10 am
https://www.brownbook.net/business/54155493/братислава-кокаин-мефедрон-марихуана/
MichaelNox
16 Aug 25 at 10:14 am
https://www.brownbook.net/business/54154883/негрил-марихуана-гашиш-канабис/
LemuelJaido
16 Aug 25 at 10:25 am
Link exchange is nothing else except it is only placing the
other person’s weblog link on your page at
appropriate place and other person will also do similar
in support of you.
رتبه های برتر کنکور انسانی ۱۴۰۴
16 Aug 25 at 10:28 am
Современная наркология предлагает два основных формата вывода из запоя:
Получить дополнительную информацию – [url=https://nadezhnyj-vyvod-iz-zapoya.ru/]срочный вывод из запоя санкт-петербруг[/url]
MichaelMes
16 Aug 25 at 10:29 am
По ссылке https://tartugi.net/111268-kak-priruchit-drakona.html вы сможете посмотреть увлекательный, добрый и интересный мультфильм «Как приручить дракона». Он сочетает в себе сразу несколько жанров, в том числе, приключения, комедию, семейный, фэнтези. На этом портале он представлен в отличном качестве, с хорошим звуком, а посмотреть его получится на любом устройстве, в том числе, планшете, телефоне, ПК, в командировке, во время длительной поездки или в выходной день. Мультик обязательно понравится вам, ведь в нем сочетается юмор, доброта и красивая музыка.
DalanoHof
16 Aug 25 at 10:31 am
https://community.wongcw.com/blogs/1129759/%D0%9D%D1%8F%D1%87%D0%B0%D0%BD%D0%B3-%D0%BA%D1%83%D0%BF%D0%B8%D1%82%D1%8C-%D0%BA%D0%BE%D0%BA%D0%B0%D0%B8%D0%BD-%D0%BC%D0%B5%D1%84%D0%B5%D0%B4%D1%80%D0%BE%D0%BD-%D0%BC%D0%B0%D1%80%D0%B8%D1%85%D1%83%D0%B0%D0%BD%D1%83
Lonnienam
16 Aug 25 at 10:33 am
generic sildenafil from india: can you buy viagra in mexico over the counter – female version of viagra
PeterTEEFS
16 Aug 25 at 10:34 am
Мега сайт
RichardPep
16 Aug 25 at 10:36 am
What’s up, for all time i used to check website posts here in the early
hours in the morning, for the reason that i
enjoy to gain knowledge of more and more.
ibobet
16 Aug 25 at 10:45 am
Скорая наркологическая помощь в Москве — Narcology Clinic выезжает круглосуточно напрямую к пациенту. Срочные капельницы, детокс, контроль состояния и экстренная поддержка. Анонимно, профессионально, оперативно.
Узнать больше – [url=https://skoraya-narkologicheskaya-pomoshch-moskva11.ru/]экстренная наркологическая помощь москве[/url]
TerryPROOT
16 Aug 25 at 10:47 am
When some one searches for his required
thing, so he/she wishes to be available that in detail, so
that thing is maintained over here.
Slot Crazy Casino
16 Aug 25 at 10:52 am
https://hoo.be/mtuhlweiuihi
Lonnienam
16 Aug 25 at 10:53 am
https://nature75185.full-design.com/selecci%C3%B3n-de-personal-para-tontos-78786806
La contratación de talento es fundamental para el desempeño de cualquier organización.
Tener el equipo correcto en los puestos correctos potencia los resultados en productividad.
1. Identificar el puesto ideal
Antes de comenzar el proceso de reclutamiento, es vital definir con claridad el perfil profesional que la empresa requiere. Esto incluye habilidades técnicas, trayectoria y valores que se alineen con la cultura de la organización.
2. Fuentes de talento
Hoy en día, las organizaciones pueden usar bolsas de empleo como Indeed, además de programas de recomendación para conseguir al mejor talento.
Diversificar fuentes aumenta la posibilidad de reclutar candidatos de calidad.
3. Preselección y entrevistas
Una vez recibidas las solicitudes, se debe filtrar a los perfiles que más se acercan a los requisitos.
Después, las entrevistas sirven para evaluar no solo la experiencia del candidato, sino también su encaje cultural con la empresa.
4. Pruebas y evaluaciones
Para asegurar que el candidato ideal cumple con lo esperado, se pueden realizar tests de competencias, análisis de personalidad o dinámicas de grupo.
Esto reduce el margen de equivocación al contratar.
5. Selección definitiva
Tras el proceso de evaluación, se procede de seleccionar al candidato que mejor cumple con los requisitos.
La comunicación clara y un buen onboarding son cruciales para garantizar que el nuevo empleado se integre fácilmente.
6. Seguimiento y mejora continua
Un proceso de reclutamiento nunca se queda fijo.
Medir indicadores como rotación de personal permite optimizar la estrategia y mejorar los resultados.
En definitiva, el proceso de contratación es mucho más que cubrir puestos.
Es una apuesta en el futuro de la empresa, donde atraer al equipo adecuado define su éxito.
JuniorShido
16 Aug 25 at 10:54 am
https://t.me/s/APK_1xBet_Android
Raymondtew
16 Aug 25 at 10:56 am
hi!,I love your writing very much! proportion we keep in touch extra
about your post on AOL? I require an expert
on this area to solve my problem. Maybe that’s you! Looking
forward to look you. https://redebuck.com.br/read-blog/55056_kupit-diplom-ob-okonchanii-11-klassov.html
диплом купить екатеринбург
16 Aug 25 at 10:57 am
Greetings! I’ve been reading your web site for
some time now and finally got the courage to go ahead and give you a shout out from New Caney Texas!
Just wanted to tell you keep up the fantastic job!
Sentrip 구매
16 Aug 25 at 11:04 am
ламинирование бровей севастополь Салон красоты Севастополь: Место, где рождается красота. Полный спектр услуг для создания неповторимого образа.
RickyNut
16 Aug 25 at 11:04 am
https://pxlmo.com/JacobMeadowsJac
JessieSic
16 Aug 25 at 11:08 am
Does your website have a contact page? I’m having trouble locating it but, I’d like to send you an email.
I’ve got some creative ideas for your blog you
might be interested in hearing. Either way, great blog and I look forward to seeing
it grow over time.
water damage repair nearby
16 Aug 25 at 11:10 am
https://say.la/read-blog/125127
Lonnienam
16 Aug 25 at 11:13 am
what possible side effect should a patient taking tadalafil report to a physician quizlet: Tadalify – cialis or levitra
PeterTEEFS
16 Aug 25 at 11:14 am
Основные показания для обращения в нашу клинику включают.
Выяснить больше – https://alko-konsultaciya.ru/vivod-iz-zapoya-cena-v-smolenske
CharlesDinly
16 Aug 25 at 11:17 am
Экстренная помощь при алкоголизме от Narcology Clinic в Москве — выезд врачей в любую точку города, купирование острых состояний, поддержка пациента до стабильного состояния, профессионально и в конфиденциальности.
Разобраться лучше – [url=https://skoraya-narkologicheskaya-pomoshch-moskva.ru/]частная скорая наркологическая помощь[/url]
Robertkix
16 Aug 25 at 11:18 am
Для максимальной эффективности и безопасности «Красмед» использует комбинированные подходы:
Подробнее – [url=https://medicinskij-vyvod-iz-zapoya.ru/]вывод из запоя на дому[/url]
RobertExevy
16 Aug 25 at 11:19 am
Наши специалисты всегда относятся к пациентам с уважением и вниманием, создавая атмосферу доверия и поддержки. Они проводят всестороннее обследование, выявляют причины зависимости и разрабатывают индивидуальные стратегии лечения. Профессионализм и компетентность врачей являются основой успешного восстановления наших пациентов.
Подробнее можно узнать тут – http://срочно-вывод-из-запоя.рф/
Elmerlar
16 Aug 25 at 11:20 am
купить диплом с занесением реестра [url=https://arus-diplom34.ru]купить диплом с занесением реестра[/url] .
Zakazat diplom o visshem obrazovanii!_cakn
16 Aug 25 at 11:20 am
Состав инфузии подбирается врачом индивидуально, с учётом состояния пациента, длительности запоя, возраста и хронических заболеваний.
Подробнее можно узнать тут – [url=https://kapelnica-ot-zapoya-krasnoyarsk6.ru/]поставить капельницу от запоя на дому[/url]
Bobbyunfig
16 Aug 25 at 11:23 am
betzula
LarryIdons
16 Aug 25 at 11:23 am
привод somfy [url=https://avtomatika-somfy.ru]https://avtomatika-somfy.ru[/url] .
avtomatika somfy_gwot
16 Aug 25 at 11:24 am
Hi just wanted to give you a quick heads up and let you know a few of the
pictures aren’t loading properly. I’m not sure why but I think its a linking issue.
I’ve tried it in two different internet browsers and both
show the same results.
idm full version
16 Aug 25 at 11:30 am
https://hoo.be/pudahiuic
Lonnienam
16 Aug 25 at 11:32 am
Refresh Renovation Southwest Charlotte
1251 Arrow Pine Ꭰr c121,
Charlotte, NC 28273, United Ꮪtates
+19803517882
Services condo renovation
Services condo renovation
16 Aug 25 at 11:34 am
Оптимально для пациентов в стабильном состоянии. Процедура начинается с приезда врача, осмотра и постановки капельницы с индивидуально подобранными растворами.
Ознакомиться с деталями – https://narko-zakodirovan2.ru/vyvod-iz-zapoya-kruglosutochno-novosibirsk/
MarvinGon
16 Aug 25 at 11:42 am
I think the admin of this web page is in fact working hard
for his web page, since here every data is quality
based material.
koitoto
16 Aug 25 at 11:47 am
see more
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
see more
16 Aug 25 at 11:50 am
https://www.metooo.io/u/689a3e88c8f3cb287e82c19d
JessieSic
16 Aug 25 at 11:50 am
https://www.themeqx.com/forums/users/viboduoc/
Lonnienam
16 Aug 25 at 11:52 am
Портал о строительстве https://juglans.com.ua свежие новости, статьи и советы. Обзоры технологий, материалов, дизайн-идеи и практические рекомендации для профессионалов и частных застройщиков.
DavidHauch
16 Aug 25 at 11:55 am
Строительный портал https://dki.org.ua всё о строительстве и ремонте: технологии, оборудование, материалы, идеи для дома. Новости отрасли и экспертные рекомендации.
Douglasgok
16 Aug 25 at 11:57 am
взлом телеграмм Мы помогаем взломать: Социальные сети. Узнайте, что скрывается за закрытыми профилями, раскройте тайны личной переписки, получите доступ к скрытым фотографиям и видео. Мы поможем вам получить полную картину интересующего вас человека.
Charlesroary
16 Aug 25 at 11:57 am
Hey there would you mind stating which blog platform
you’re working with? I’m looking to start my own blog soon but I’m having a hard time deciding
between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most
blogs and I’m looking for something unique. P.S My apologies for getting off-topic but I had to ask!
40ft shipping containers for sale
16 Aug 25 at 11:58 am
Оказывать медуслуги можно только при наличии [url=https://licenz.pro/med-litsenziya/]лицензия на осуществление медицинской деятельности[/url]. Мы подготовим документы, пройдём проверки и оформим всё по закону. Процесс займёт минимум времени с вашей стороны. Начните работать официально и привлекать клиентов, не опасаясь проверок или приостановки бизнеса.
лицензия на медицинские услуги
16 Aug 25 at 11:58 am
Онлайн строительный https://texha.com.ua портал о материалах, проектах и технологиях. Всё о ремонте, строительстве и обустройстве дома. Поддержка специалистов и вдохновение для новых идей.
RobertPrany
16 Aug 25 at 11:58 am
Всё о стройке https://mramor.net.ua полезные статьи, советы, обзоры материалов и технологий. Ремонт, строительство домов, дизайн интерьера и современные решения для вашего проекта.
PeterDog
16 Aug 25 at 12:01 pm
Портал о строительстве https://juglans.com.ua свежие новости, статьи и советы. Обзоры технологий, материалов, дизайн-идеи и практические рекомендации для профессионалов и частных застройщиков.
DavidHauch
16 Aug 25 at 12:01 pm
Сайт «Всё о стройке» https://sushico.com.ua подробные инструкции, советы экспертов, новости рынка. Всё о строительстве, ремонте и обустройстве жилья в одном месте.
AlbertJEOTS
16 Aug 25 at 12:03 pm
SildenaPeak: viagra pill where to buy – SildenaPeak
ElijahKic
16 Aug 25 at 12:03 pm