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!
перепланировка квартир [url=soglasovanie-pereplanirovki-kvartiry4.ru]перепланировка квартир[/url] .
soglasovanie pereplanirovki kvartiri _euOr
19 Oct 25 at 1:19 am
купить диплом о высшем образовании легально [url=https://frei-diplom6.ru]купить диплом о высшем образовании легально[/url] .
Diplomi_ymOl
19 Oct 25 at 1:19 am
купить диплом в техникуме [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_dhea
19 Oct 25 at 1:20 am
проектная организация для перепланировки квартиры [url=https://proekt-pereplanirovki-kvartiry17.ru/]https://proekt-pereplanirovki-kvartiry17.ru/[/url] .
proekt pereplanirovki kvartiri_upml
19 Oct 25 at 1:20 am
Thematic systems in OMT’s syllabus attach mathematics tⲟ rate оf іnterests ⅼike technology, firing սp inquisitiveness аnd drive
for leading exam scores.
Experience flexible learning anytime, аnywhere thrοugh OMT’s tһorough online е-learning platform, including endless access tο video lessons and interactive quizzes.
Ԍiven that mathematics plays a critical role іn Singapore’s economic development аnd development, investing іn specialized math tuition gears ᥙр students with tһe problem-solving skills neеded tߋ thrive in a competitive
landscape.
Tuition іn primary math iѕ key fοr PSLE preparation, as іt
introduces innovative methods fοr dealing with non-routine
problems that stump numerous candidates.
Detailed comments from tuition instructors on technique attempts aids secondary pupils pick ᥙp
from blunders, enhancing precision fⲟr the actual O Levels.
Ꮃith normal simulated examinations аnd detailed responses, tuition aids junior college trainees
determine ɑnd deal with weak points befоrе tһe actual А Levels.
Wһat makes OMT extraordinary іs its proprietary educational program tһat lines up with MOE
ѡhile introducing aesthetic һelp like bar modeling in ingenious methods
fоr primary learners.
OMT’s οn tһe internet community offers assistance leh, where yoս сan ask inquiries and enhance
youг discovering for muсh bettеr grades.
Singapore’s focus օn probⅼem-solving in mathematics
exams mаkes tuition importɑnt foг creating crucial thinking
abilities ƅeyond school һours.
Hеre is mү blog post: singapore Primary 4 math Tuition
singapore Primary 4 math Tuition
19 Oct 25 at 1:21 am
купить диплом с занесением в реестр в кемерово [url=www.frei-diplom4.ru/]www.frei-diplom4.ru/[/url] .
Diplomi_ewOl
19 Oct 25 at 1:21 am
купить диплом в кемерово [url=http://rudik-diplom8.ru/]купить диплом в кемерово[/url] .
Diplomi_ooMt
19 Oct 25 at 1:21 am
мелбет зеркало сайта [url=http://melbetbonusy.ru/]мелбет зеркало сайта[/url] .
melbet_crOi
19 Oct 25 at 1:21 am
If you wish for to take a good deal from this piece of writing then you have to apply such strategies to your
won webpage.
Chimney Flashing Seattle
19 Oct 25 at 1:21 am
узаконить перепланировку цена [url=https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru]https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_zdet
19 Oct 25 at 1:21 am
shopandshine – Packages arrived earlier than expected which was an awesome surprise.
Modesto Lazusky
19 Oct 25 at 1:22 am
купить диплом машиниста [url=rudik-diplom13.ru]купить диплом машиниста[/url] .
Diplomi_smon
19 Oct 25 at 1:23 am
купить диплом электрика [url=rudik-diplom5.ru]купить диплом электрика[/url] .
Diplomi_ckma
19 Oct 25 at 1:24 am
I’m gone to say to my little brother, that he should also pay a visit
this website on regular basis to obtain updated from newest reports.
유흥알바
19 Oct 25 at 1:24 am
купить диплом в кропоткине [url=http://rudik-diplom3.ru]http://rudik-diplom3.ru[/url] .
Diplomi_pnei
19 Oct 25 at 1:24 am
согласование перепланировки квартиры под ключ цена [url=https://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]https://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_zsPt
19 Oct 25 at 1:25 am
купить диплом в ревде [url=www.rudik-diplom4.ru/]купить диплом в ревде[/url] .
Diplomi_zeOr
19 Oct 25 at 1:26 am
купить диплом в тамбове [url=www.rudik-diplom1.ru]купить диплом в тамбове[/url] .
Diplomi_xber
19 Oct 25 at 1:26 am
поставка медоборудования [url=www.xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai]www.xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai[/url] .
oborydovanie medicinskoe_fuOn
19 Oct 25 at 1:26 am
диплом нефтяного техникума купить [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .
Diplomi_knea
19 Oct 25 at 1:27 am
купить диплом в ярославле [url=http://rudik-diplom11.ru]купить диплом в ярославле[/url] .
Diplomi_ivMi
19 Oct 25 at 1:27 am
сколько стоит согласовать перепланировку квартиры [url=www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/]www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_znPt
19 Oct 25 at 1:28 am
Spinrise
Angelolix
19 Oct 25 at 1:28 am
yourtradingmentor – Fantastic mentorship tips and real-world trading help, highly recommend.
Kendrick Jankowski
19 Oct 25 at 1:28 am
купить диплом медсестры с занесением в реестр [url=https://www.frei-diplom2.ru]купить диплом медсестры с занесением в реестр[/url] .
Diplomi_deEa
19 Oct 25 at 1:28 am
Стационар «Частного Медика 24» в Воронеже — место, где пациент, страдающий от длительного запоя, получает не просто деньги-стоимость услуги, а полноценную помощь: диагностику, детоксикацию, медикаментозную поддержку и психологическую помощь с уважением к личному пространству и анонимности.
Углубиться в тему – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh24.ru/]быстрый вывод из запоя в стационаре[/url]
Stuartbooms
19 Oct 25 at 1:29 am
купить диплом моториста [url=http://rudik-diplom3.ru/]купить диплом моториста[/url] .
Diplomi_ywei
19 Oct 25 at 1:29 am
проект перепланировки квартиры в москве [url=http://www.proekt-pereplanirovki-kvartiry17.ru]http://www.proekt-pereplanirovki-kvartiry17.ru[/url] .
proekt pereplanirovki kvartiri_abml
19 Oct 25 at 1:30 am
согласование перепланировок [url=http://soglasovanie-pereplanirovki-kvartiry3.ru/]http://soglasovanie-pereplanirovki-kvartiry3.ru/[/url] .
soglasovanie pereplanirovki kvartiri _xhPi
19 Oct 25 at 1:30 am
cjukfcjdfybt [url=https://soglasovanie-pereplanirovki-kvartiry14.ru]https://soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _xvEl
19 Oct 25 at 1:31 am
купить диплом в новочебоксарске [url=www.rudik-diplom5.ru]www.rudik-diplom5.ru[/url] .
Diplomi_nfma
19 Oct 25 at 1:32 am
купить диплом техникума в Днепре [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_xoea
19 Oct 25 at 1:32 am
согласование перепланировки цена в москве [url=https://zakazat-proekt-pereplanirovki-kvartiry11.ru]https://zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_kvet
19 Oct 25 at 1:34 am
Адекватное лечение, комфорт и забота — так проходят дни в стационаре «Частного Медика 24» во время вывода из запоя.
Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]стационар вывод из запоя в самаре[/url]
GilbertCoeby
19 Oct 25 at 1:35 am
купить диплом в владивостоке [url=https://rudik-diplom11.ru/]купить диплом в владивостоке[/url] .
Diplomi_tfMi
19 Oct 25 at 1:35 am
Добро пожаловать в удивительный мир природы России!
Кстати, если вас интересует Изучение ООПТ России: парки, заповедники, водоемы, посмотрите сюда.
Смотрите сами:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Что думаете о красоте природы России? Делитесь мнениями!
fixRow
19 Oct 25 at 1:37 am
купить диплом в нижнем тагиле [url=www.rudik-diplom5.ru]купить диплом в нижнем тагиле[/url] .
Diplomi_eama
19 Oct 25 at 1:37 am
проект перепланировки квартиры для согласования цена [url=https://www.proekt-pereplanirovki-kvartiry17.ru]https://www.proekt-pereplanirovki-kvartiry17.ru[/url] .
proekt pereplanirovki kvartiri_byml
19 Oct 25 at 1:37 am
купить диплом в анжеро-судженске [url=www.rudik-diplom10.ru]www.rudik-diplom10.ru[/url] .
Diplomi_agSa
19 Oct 25 at 1:37 am
Алкогольная зависимость требует правильного подхода. В новом материале Blogimam рассказывается о доступных методах кодирования в Саратове: от медикаментозных до психологических программ. Подробнее можно узнать тут – http://www.artlib.ru/index.php?id=26&idr=21&idt=52033
Crystaldum
19 Oct 25 at 1:37 am
мелбет вход в личный кабинет [url=http://www.melbetbonusy.ru]http://www.melbetbonusy.ru[/url] .
melbet_isOi
19 Oct 25 at 1:38 am
Minotaurus token’s DAO governance empowers users. Presale’s multi-crypto support widens access. Battling obstacles feels epic.
minotaurus coin
WilliamPargy
19 Oct 25 at 1:39 am
купить диплом с проводкой кого [url=https://www.frei-diplom6.ru]купить диплом с проводкой кого[/url] .
Diplomi_oyOl
19 Oct 25 at 1:39 am
купить диплом воспитателя [url=https://www.rudik-diplom11.ru]купить диплом воспитателя[/url] .
Diplomi_avMi
19 Oct 25 at 1:40 am
You can certainly see your expertise in the work you write.
The arena hopes for even more passionate writers such as you who aren’t afraid to say how they believe.
All the time follow your heart.
xóc đĩa
19 Oct 25 at 1:42 am
медицинское оборудование [url=http://xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai/]http://xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai/[/url] .
oborydovanie medicinskoe_xxOn
19 Oct 25 at 1:42 am
куплю диплом медсестры в москве [url=www.frei-diplom14.ru]куплю диплом медсестры в москве[/url] .
Diplomi_izoi
19 Oct 25 at 1:43 am
перепланировка квартиры в москве цена [url=https://www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]https://www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_nsPt
19 Oct 25 at 1:44 am
регистрация перепланировки [url=http://soglasovanie-pereplanirovki-kvartiry14.ru/]http://soglasovanie-pereplanirovki-kvartiry14.ru/[/url] .
soglasovanie pereplanirovki kvartiri _iwEl
19 Oct 25 at 1:44 am
купить диплом биолога [url=http://rudik-diplom1.ru]купить диплом биолога[/url] .
Diplomi_fher
19 Oct 25 at 1:44 am