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!
1 x bet [url=https://1xbet-giris-9.com]1 x bet[/url] .
1xbet giris_ihon
24 Oct 25 at 6:30 am
Курируют процесс от начала до конца, что очень удобно: таможенный брокер для юридических лиц
NathanDax
24 Oct 25 at 6:31 am
birxbet [url=https://1xbet-giris-10.com/]birxbet[/url] .
1xbet giris_tika
24 Oct 25 at 6:31 am
1xbet guncel [url=https://www.1xbet-giris-1.com]https://www.1xbet-giris-1.com[/url] .
1xbet giris_cukt
24 Oct 25 at 6:32 am
Этот обзорный материал предоставляет информационно насыщенные данные, касающиеся актуальных тем. Мы стремимся сделать информацию доступной и структурированной, чтобы читатели могли легко ориентироваться в наших выводах. Познайте новое с нашим обзором!
Раскрыть тему полностью – https://koka.lt/kodel-kanalizacijai-reikia-bakteriju
Robertmam
24 Oct 25 at 6:34 am
kraken
кракен актуальная ссылка
JamesDaync
24 Oct 25 at 6:34 am
1x bet [url=1xbet-giris-10.com]1x bet[/url] .
1xbet giris_pfka
24 Oct 25 at 6:35 am
1xbet com giri? [url=http://1xbet-giris-8.com]http://1xbet-giris-8.com[/url] .
1xbet giris_xqPn
24 Oct 25 at 6:37 am
купить диплом в асбесте [url=http://rudik-diplom14.ru/]купить диплом в асбесте[/url] .
Diplomi_gxea
24 Oct 25 at 6:37 am
kraken client
кракен вход
kraken darknet market
24 Oct 25 at 6:37 am
1xbet mobil giri? [url=https://1xbet-giris-7.com/]1xbet-giris-7.com[/url] .
1xbet giris_hrKn
24 Oct 25 at 6:38 am
1xbet g?ncel adres [url=https://www.1xbet-giris-4.com]1xbet g?ncel adres[/url] .
1xbet giris_epSa
24 Oct 25 at 6:38 am
купить медицинский диплом медсестры [url=www.frei-diplom14.ru]купить медицинский диплом медсестры[/url] .
Diplomi_rcoi
24 Oct 25 at 6:43 am
kraken market
кракен сайт
JamesDaync
24 Oct 25 at 6:45 am
1xbetgiri? [url=http://1xbet-giris-1.com/]http://1xbet-giris-1.com/[/url] .
1xbet giris_fmkt
24 Oct 25 at 6:45 am
birxbet giri? [url=http://1xbet-giris-8.com/]http://1xbet-giris-8.com/[/url] .
1xbet giris_tgPn
24 Oct 25 at 6:46 am
1x giri? [url=1xbet-giris-10.com]1x giri?[/url] .
1xbet giris_hoka
24 Oct 25 at 6:47 am
Sildenafil zonder recept bestellen: erectiepillen discreet bestellen – veilige online medicijnen Nederland
RandySkync
24 Oct 25 at 6:47 am
When someone writes an paragraph he/she retains the plan of a user in his/her brain that how a user can understand it.
Thus that’s why this post is great. Thanks!
spotify mod premium 9.0.92.241 apk
24 Oct 25 at 6:48 am
I’ve been exploring for a little bit for any high quality articles or weblog posts on this sort of space .
Exploring in Yahoo I ultimately stumbled upon this web site.
Reading this information So i am glad to convey that I have an incredibly
just right uncanny feeling I came upon just what I needed.
I such a lot indubitably will make sure to do not forget this website and give it a look regularly.
casinox
24 Oct 25 at 6:48 am
diseño web en puebla
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
diseño web en puebla
24 Oct 25 at 6:48 am
1xbet turkey [url=1xbet-giris-9.com]1xbet turkey[/url] .
1xbet giris_zqon
24 Oct 25 at 6:48 am
1xbet spor bahislerinin adresi [url=https://www.1xbet-4.com]https://www.1xbet-4.com[/url] .
1xbet_shol
24 Oct 25 at 6:49 am
1win мобильная версия [url=https://1win5518.ru/]https://1win5518.ru/[/url]
1win_kg_azkl
24 Oct 25 at 6:49 am
1 x bet [url=https://1xbet-giris-4.com/]1xbet-giris-4.com[/url] .
1xbet giris_xjSa
24 Oct 25 at 6:51 am
Как купить A-PVP мука в Жирновске?Обратил внимание на сайт https://rejting-kapperov13.ru
– по отзывам неплохо. Цены адекватные, доставка быстрая. Кто-то брал? Интересует качество товара?
Stevenref
24 Oct 25 at 6:51 am
кракен даркнет
кракен android
кракен ios
24 Oct 25 at 6:52 am
1xbwt giri? [url=http://1xbet-giris-8.com]http://1xbet-giris-8.com[/url] .
1xbet giris_zrPn
24 Oct 25 at 6:52 am
кракен
kraken tor
кракен зеркало
24 Oct 25 at 6:53 am
1xbet turkiye [url=https://1xbet-giris-7.com/]1xbet-giris-7.com[/url] .
1xbet giris_dhKn
24 Oct 25 at 6:56 am
Процесс асфальтирования начинается с тщательной подготовки основания. Независимо от того, новое это строительство или ремонт старого покрытия, важно создать устойчивую и ровную базу.
Снимается старое покрытие, выравнивается грунт, создается щебеночная подушка, и все это тщательно утрамбовывается для обеспечения необходимой несущей способности. Помогите выбрать подрядчика под [url=https://airlady.forum24.ru/?1-4-0-00000157-000-0-0-1759139944]асфальтирование спб[/url]
Eugenefer
24 Oct 25 at 6:57 am
1xbet yeni adresi [url=https://1xbet-giris-1.com/]1xbet-giris-1.com[/url] .
1xbet giris_nzkt
24 Oct 25 at 6:57 am
1xbet ?yelik [url=www.1xbet-giris-9.com]1xbet ?yelik[/url] .
1xbet giris_cdon
24 Oct 25 at 6:58 am
Awesome blog you have here but I was curious about if you knew of any
discussion boards that cover the same topics discussed here?
I’d really love to be a part of community where I can get responses
from other experienced individuals that share the same interest.
If you have any recommendations, please let me know.
Cheers!
Foot tickle reactions
24 Oct 25 at 6:58 am
kraken СПб
кракен vk3
JamesDaync
24 Oct 25 at 6:59 am
Порошковая покраска — это метод нанесения покрытия на поверхность с использованием сухого порошка, который не содержит растворителей. Порошок (чаще всего на основе эпоксидных, полиэфирных или полиуретановых смол) распыляется на поверхность, а затем закрепляется при высокой температуре в печи, где происходит плавление и отверждение покрытия.
В результате получается прочное, устойчивое к воздействию внешних факторов покрытие. Где используется [url=https://crimeaguide.com/forum/viewtopic.php?f=5&t=16142]порошковая покраска металлических изделий в Москве?[/url]
DarylCal
24 Oct 25 at 7:00 am
1 x bet giri? [url=https://1xbet-giris-10.com]1 x bet giri?[/url] .
1xbet giris_wlka
24 Oct 25 at 7:02 am
1xbet resmi sitesi [url=https://1xbet-9.com/]https://1xbet-9.com/[/url] .
1xbet_ttSn
24 Oct 25 at 7:02 am
кракен Россия
kraken онлайн
кракен vpn
24 Oct 25 at 7:02 am
промокод 1xBet все актуальные акции и бонусы собраны на одной странице
CollinDwets
24 Oct 25 at 7:03 am
1xbet ?ye ol [url=https://1xbet-giris-9.com]https://1xbet-giris-9.com[/url] .
1xbet giris_nzon
24 Oct 25 at 7:05 am
Как юридическое лицо, работаем с брокером на постоянной основе. Всегда всё чётко, в срок и без проблем с таможней. Настоящие профессионалы своего дела: https://tamozhenniiy-broker-moskva11.ru/
NathanDax
24 Oct 25 at 7:08 am
I’ve learn several just right stuff here. Definitely price bookmarking for revisiting.
I wonder how much effort you put to create this sort of great informative web site.
dewascatter link alternatif
24 Oct 25 at 7:08 am
1xbet [url=http://1xbet-giris-4.com]1xbet[/url] .
1xbet giris_ehSa
24 Oct 25 at 7:08 am
kraken РФ
kraken официальный
JamesDaync
24 Oct 25 at 7:09 am
1xbet ?ye ol [url=http://www.1xbet-giris-8.com]http://www.1xbet-giris-8.com[/url] .
1xbet giris_imPn
24 Oct 25 at 7:10 am
Nominated in several sections at the SBC Awards Europe 2025, including “Marketing Campaign of the Year”, “Operator of the Year”, “[url=https://kokoro.stz-sibg-d5.net/2025/10/12/explore-the-official-site-of-1xbet-for-unmatched/]https://kokoro.stz-sibg-d5.net/2025/10/12/explore-the-official-site-of-1xbet-for-unmatched/[/url]” and “Betting Operator of the Year”.
RyanWrile
24 Oct 25 at 7:13 am
Откройте для себя скрытые страницы истории и малоизвестные научные открытия, которые оказали колоссальное влияние на развитие человечества. Статья предлагает свежий взгляд на события, которые заслуживают большего внимания.
Изучить вопрос глубже – https://tarakaninfo.com/mantapkan-persiapan-kunker-presiden-menko-marves-akan-kunjungi-kaltara
Stevenhog
24 Oct 25 at 7:13 am
кракен qr код
кракен тор
kraken vk5
24 Oct 25 at 7:14 am
1xbetgiri? [url=https://1xbet-giris-1.com/]1xbet-giris-1.com[/url] .
1xbet giris_itkt
24 Oct 25 at 7:14 am