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!
Joined the $MTAUR ICO raffle—$100K prize pool is tempting. Unlocking special zones with tokens enhances strategy. This is crypto gaming evolved.
mtaur coin
WilliamPargy
21 Oct 25 at 2:13 am
купить диплом с занесением в реестр в украине [url=http://www.frei-diplom3.ru]http://www.frei-diplom3.ru[/url] .
Diplomi_sjKt
21 Oct 25 at 2:13 am
можно купить легальный диплом [url=https://www.frei-diplom1.ru]https://www.frei-diplom1.ru[/url] .
Diplomi_jyOi
21 Oct 25 at 2:14 am
cd player alarm [url=www.alarm-radio-clocks.com]www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_ihOa
21 Oct 25 at 2:16 am
купить диплом средне техническое [url=http://rudik-diplom3.ru/]купить диплом средне техническое[/url] .
Diplomi_peei
21 Oct 25 at 2:18 am
«СХТ» реализует автоматизированные весовые комплексы с интеграцией программного обеспечения и оборудования на одном подрядчике. Собственные сервисные бригады и метрологическая лаборатория обеспечивают ремонт и поверку в кратчайшие сроки. Подробности, примеры реализованных объектов и запрос коммерческого предложения — на https://xn--q1aci.xn--p1ai/ Поставки и строительство ведутся по всей РФ: от монтажа до сдачи комплекса в промышленную эксплуатацию.
yisonSnity
21 Oct 25 at 2:19 am
купить диплом о высшем образовании реестр [url=www.frei-diplom1.ru/]купить диплом о высшем образовании реестр[/url] .
Diplomi_qeOi
21 Oct 25 at 2:19 am
We’re a gaggle of volunteers and opening a brand new scheme in our community.
Your web site offered us with valuable information to work on. You have performed
an impressive activity and our entire group shall be thankful to you.
situs scam
21 Oct 25 at 2:19 am
купить диплом высшего образования с занесением в реестр [url=http://frei-diplom4.ru]купить диплом высшего образования с занесением в реестр[/url] .
Diplomi_jfOl
21 Oct 25 at 2:20 am
Затянувшийся запой — это не просто «перебор накануне», а состояние, при котором страдают сердечно-сосудистая система, печень, нервная регуляция и обмен электролитов. В наркологической клинике «ДонЗдрав» (Ростов-на-Дону) экстренный вывод из запоя организован как непрерывная цепочка помощи: диспетчер 24/7 — дежурный врач — мобильная бригада — последующее наблюдение и психотерапевтическая поддержка. Мы приезжаем на дом в гражданской одежде, без опознавательных знаков, проводим экспресс-диагностику, запускаем индивидуально подобранные капельницы и даём чёткий план на ближайшие 72 часа. Такой формат позволяет безопасно стабилизировать состояние, не нарушая приватность и привычный уклад семьи.
Изучить вопрос глубже – https://vivod-iz-zapoya-rostov14.ru/vyvod-iz-zapoya-na-domu-rostov-na-donu
Thomaszique
21 Oct 25 at 2:20 am
куплю диплом цена [url=https://rudik-diplom10.ru]куплю диплом цена[/url] .
Diplomi_orSa
21 Oct 25 at 2:20 am
купить диплом в элисте [url=http://rudik-diplom11.ru]купить диплом в элисте[/url] .
Diplomi_ueMi
21 Oct 25 at 2:21 am
купить диплом о среднем образовании в реестр [url=https://frei-diplom3.ru]купить диплом о среднем образовании в реестр[/url] .
Diplomi_xwKt
21 Oct 25 at 2:22 am
купить диплом колледжа [url=rudik-diplom1.ru]купить диплом колледжа[/url] .
Diplomi_yrer
21 Oct 25 at 2:23 am
купить диплом в перми [url=rudik-diplom4.ru]купить диплом в перми[/url] .
Diplomi_rmOr
21 Oct 25 at 2:23 am
купить диплом с занесением в реестр в иркутске [url=frei-diplom5.ru]купить диплом с занесением в реестр в иркутске[/url] .
Diplomi_pwPa
21 Oct 25 at 2:23 am
купить диплом электромонтажника [url=rudik-diplom8.ru]купить диплом электромонтажника[/url] .
Diplomi_ycMt
21 Oct 25 at 2:23 am
Бонусы также варьируются по типу. Часть бонусов предлагаются новичкам. Во время регистрации на 1xBet, активируйте код и оформите 100% приветственный бонус на сумму до 32500 рублей.Букмекерская контора 1xBet предлагает своим клиентам участвовать в спортивных ставках и казино с использованием акционных предложений. Это увеличивает вовлечённость к играм и обеспечивает максимальную безопасность игры.Промокод 2026 года можно активировать на странице регистрации: где промокод 1xbet.
Jasonbrado
21 Oct 25 at 2:25 am
диплом автодорожного техникума купить [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .
Diplomi_jyea
21 Oct 25 at 2:26 am
лучшие seo компании [url=http://reiting-seo-kompanii.ru]http://reiting-seo-kompanii.ru[/url] .
reiting seo kompanii_ppsn
21 Oct 25 at 2:26 am
Правильный Промо-Код ХБЕТ на 2026 год. На нашем сайте вы найдете промокоды на разные суммы: на депозит, пополнение и простой. Букмекерская контора 1xBet только новым людям дарит подарки. промокод на фриспины 1xbet. Активируйте промокоды и делайте ставки на футбол, хоккей и самые яркие состязания – Лиги Европы ?? и Лиги Чемпионов. Где найти промокод 1xBet на сегодня бесплатно? Использовав промокод казино 1xBet, игрок получает денежные средства на бонусный счет. Это значит, что он может использовать их только для игры в слоты и другие азартные развлечения на сайте. Вывести деньги, выигранные с бонуса, игрок сможет только тогда, когда отыграет их согласно вейджеру. Зарабатывайте баллы и меняйте на купоны или пользуйтесь халявными бонусами.
Stanleyvonna
21 Oct 25 at 2:27 am
купить диплом с занесением в реестр [url=https://www.frei-diplom3.ru]купить диплом с занесением в реестр[/url] .
Diplomi_jiKt
21 Oct 25 at 2:27 am
financialgrowthplan.cfd – The design is clean and professional, which gives a good first impression.
Riva Cantrelle
21 Oct 25 at 2:28 am
купить диплом в россоши [url=http://rudik-diplom10.ru]купить диплом в россоши[/url] .
Diplomi_zgSa
21 Oct 25 at 2:28 am
pin up uz [url=https://pinup5007.ru/]pin up uz[/url]
pin_up_uz_uasr
21 Oct 25 at 2:29 am
купить диплом в старом осколе [url=www.rudik-diplom1.ru/]купить диплом в старом осколе[/url] .
Diplomi_uier
21 Oct 25 at 2:29 am
купить диплом в туапсе [url=www.rudik-diplom8.ru/]купить диплом в туапсе[/url] .
Diplomi_ujMt
21 Oct 25 at 2:30 am
What’s Going down i’m new to this, I stumbled upon this I have
discovered It absolutely helpful and it has aided
me out loads. I am hoping to give a contribution & help other customers like its aided me.
Good job.
Learn more
21 Oct 25 at 2:30 am
как купить диплом с занесением в реестр в екатеринбурге [url=https://frei-diplom4.ru/]https://frei-diplom4.ru/[/url] .
Diplomi_kdOl
21 Oct 25 at 2:31 am
купить диплом монтажника [url=www.rudik-diplom15.ru]купить диплом монтажника[/url] .
Diplomi_cgPi
21 Oct 25 at 2:32 am
купить диплом в новороссийске [url=www.rudik-diplom10.ru]купить диплом в новороссийске[/url] .
Diplomi_jlSa
21 Oct 25 at 2:33 am
как купить проведенный диплом отзывы [url=https://frei-diplom6.ru]https://frei-diplom6.ru[/url] .
Diplomi_gsOl
21 Oct 25 at 2:35 am
Today, I went to the beachfront with my kids. I found a sea shell and gave
it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and
screamed. There was a hermit crab inside and it pinched her
ear. She never wants to go back! LoL I know this is totally off topic but I had to tell
someone!
Optima Fundrelix
21 Oct 25 at 2:36 am
Здесь работают не только профессиональные мастерицы, но и удивительно красивые девушки, каждая словно из рекламы. Их движения лёгкие, уверенные и чувственные, всё продумано до мелочей. После сеанса ощущение полного расслабления и гармонии. Крайне советую, индивидуалки заказать Новосибирск – https://sibirka.com/. Вечер удался, девушки шикарные.
Bobbyham
21 Oct 25 at 2:37 am
купить диплом в элисте [url=http://rudik-diplom3.ru]купить диплом в элисте[/url] .
Diplomi_okei
21 Oct 25 at 2:37 am
топ интернет агентств москвы [url=http://luchshie-digital-agencstva.ru/]топ интернет агентств москвы[/url] .
lychshie digital agentstva_suoi
21 Oct 25 at 2:39 am
услуги по раскрутке сайта [url=http://reiting-runeta-seo.ru/]http://reiting-runeta-seo.ru/[/url] .
reiting ryneta seo_wgma
21 Oct 25 at 2:41 am
head to Naturespirit
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
head to Naturespirit
21 Oct 25 at 2:41 am
Где купить Атаракс в Пикалёвое?Всем привет, ищу где брать – нашел https://ProHedge.ru
. Цены нормальные, доставляют. Кто-нибудь знаком их услугами? Как у них с чистотой?
Stevenref
21 Oct 25 at 2:41 am
pin up bonus olish [url=https://pinup5008.ru/]pin up bonus olish[/url]
pin_up_uz_krSt
21 Oct 25 at 2:42 am
Купить диплом колледжа в Николаев [url=http://educ-ua7.ru/]http://educ-ua7.ru/[/url] .
Diplomi_hlea
21 Oct 25 at 2:43 am
купить диплом о высшем образовании с занесением в реестр в ижевске [url=http://frei-diplom6.ru/]купить диплом о высшем образовании с занесением в реестр в ижевске[/url] .
Diplomi_ipOl
21 Oct 25 at 2:43 am
Heya i’m for the primary time here. I found this board and I to find It truly helpful &
it helped me out a lot. I’m hoping to give something back
and help others such as you aided me.
Linode account for sale
21 Oct 25 at 2:43 am
Oi oi, Singapore moms аnd dads, mathematics proves ⲣerhaps thе most important primary topic, promoting creativity tһrough challenge-tackling іn creative jobs.
Ꭰon’t play play lah, combine а reputable Junior College ԝith mathematics excellence to guarantee һigh A
Levels scores ɑnd seamless shifts.
St. Andrew’ѕ Junior College promotes Anglican worths ɑnd
holistic growth, developing principled people ᴡith
strong character. Modern features support quality іn academics, sports, аnd arts.
Social wоrk and management programs instill compassion ɑnd obligation. Diverse co-curricular activities promote
team effort аnd self-discovery. Alumni emmerge ɑs ethical leaders,contributing meaningfully tо society.
Victoria Junior College fires ᥙp creativity and cultivates visionary management, empowering
trainees tⲟ develop positive modification tһrough а curriculum
that sparks passions and encourages vibrant thinking іn a
attractive seaside school setting. The school’ѕ comprehensive
facilities, consisting оf humanities discussion spaces, science гesearch suites, and
arts efficiency locations, assistance enriched programs іn arts, humanities, ɑnd sciences that promote interdisciplinary insights аnd academic proficiency.
Strategic alliances ѡith secondary schools tһrough integrated
programs make sre a smooth instructional journey, ᥙsing sped ᥙⲣ finding оut paths аnd specialized electives tһat accommodate individual strengths ɑnd іnterests.
Service-learning efforts аnd worldwide outreach tasks, ѕuch aѕ international volunteer expeditions ɑnd
leadership online forums, develop caring personalities, resilience, ɑnd a commitment
to community weⅼl-being. Graduates lead with
steadfast conviction ɑnd accomplish amazing success
іn universities and professions, embodying Victoria Junior College’ѕ legacy of nurturing creative, principled, аnd
transformative individuals.
Eh eh, calm pom рі pi, mathematics proves part of tһe leading disciplines аt Junior College, laying foundation tօ Ꭺ-Level advanced math.
Ᏼesides from institution resources, focus ᴡith math fοr
stߋp typical mistakes sսch as sloppy mistakes at exams.
Ⅾo not tаke lightly lah, pair a excellent Junior College ԝith maths superiority tо assure higһ
A Levels scores аs wepl aѕ smooth chɑnges.
Mums ɑnd Dads, fearful оf losing approach activated lah, solid primary
mathematics гesults іn superior scientific understanding aѕ well aѕ
construction goals.
Kiasu Singaporeans қnow Math A-levels unlock global opportunities.
Aiyo, lacking strong maths іn Junior College, гegardless prestigious school children сould struggle ԝith secondary calculations, therefoгe build it immеdiately leh.
Feell free to visit mү web paցe – Anderson Serangoon Junior College
Anderson Serangoon Junior College
21 Oct 25 at 2:45 am
купить диплом штукатура [url=http://rudik-diplom3.ru]http://rudik-diplom3.ru[/url] .
Diplomi_ufei
21 Oct 25 at 2:45 am
Магазин супер.от души мужики все как всегда оплатил поехал забрал 5+
Онлайн магазин – купить мефедрон, кокаин, бошки
в розницу работаете?
ArturoIcedy
21 Oct 25 at 2:47 am
cd player alarm clock radio [url=www.alarm-radio-clocks.com]www.alarm-radio-clocks.com[/url] .
Cd Player Radio Alarm Clocks_ynOa
21 Oct 25 at 2:47 am
Do not boh chap lah, leading institutions prepare youngsters fⲟr IP courses, speeding ᥙρ to JC and dream positions іn medical field oor engineering.
Οh, a elite primary school ρrovides doors to enhanced tools and educators, positioning уour kid uρ fߋr educational excellence аnd upcoming lucrative careers.
Ꭺvoid play play lah, link а reputable primary school alongside mathematics excellence
fоr ensure high PSLE results plus smooth changes.
Wah lao, eνen ѡhether school proves һigh-end, mathematics іs the
mɑke-or-break subject in developing assurance ᴡith calculations.
Aiyo, lacking robust mathematics ԁuring primary school, regardless tоp institution youngsters mɑу falter with next-level algebra, tһerefore
develop thi prօmptly leh.
Alas, primary mathematics teaches practical implementations
ѕuch aas financial planning, ѕo ensure yоur child grasps іt гight ƅeginning early.
Aiyah, primary arithmetic teaches practical implementations including
budgeting, ѕo guarantee your youngster gets this properly Ьeginning yoᥙng.
CHIJ Our Lady Queen Ⲟf Peace ᥙses a values-based education that balances mind and heart.
Ꮤith engaging activities ɑnd committed instructors, іt supports compassionate leaders.
Nanyang Primary School ρrovides elite education ᴡith strong scholastic focus.
Tһe school prepares trainees fоr high achievement.
Іt’s ideal foг enthusiastic households.
Feel free tо visit mу website: Hougang Secondary School
Hougang Secondary School
21 Oct 25 at 2:48 am
диплом техникума союзных республик купить [url=http://educ-ua7.ru/]http://educ-ua7.ru/[/url] .
Diplomi_zrea
21 Oct 25 at 2:49 am
купить диплом парикмахера [url=https://rudik-diplom3.ru]купить диплом парикмахера[/url] .
Diplomi_umei
21 Oct 25 at 2:51 am