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!
Ремонт бытовой техники на дому
Jasonnus
29 Oct 25 at 6:51 pm
Комплексное остекление https://exterhaus.ru домов и коммерческих объектов «под ключ»: проектирование, замеры, производство и монтаж. Панорамные окна, витражи, теплые фасады, энергоэффективные стеклопакеты. Сроки по договору, гарантия, сервис, точный сметный расчёт.
exterhaus 961
29 Oct 25 at 6:51 pm
Hi there to all, how is all, I think every one is getting more
from this site, and your views are good in support of
new people.
tesla bahis giriş
29 Oct 25 at 6:51 pm
купить диплом в ейске [url=https://www.rudik-diplom13.ru]https://www.rudik-diplom13.ru[/url] .
Diplomi_knon
29 Oct 25 at 6:51 pm
https://martiresportes.com/de-de
BrianFab
29 Oct 25 at 6:52 pm
купить аттестаты за 11 [url=https://rudik-diplom4.ru/]купить аттестаты за 11[/url] .
Diplomi_tgOr
29 Oct 25 at 6:52 pm
купить диплом занесением реестр киев [url=frei-diplom4.ru]frei-diplom4.ru[/url] .
Diplomi_zvOl
29 Oct 25 at 6:53 pm
купить диплом врача [url=https://rudik-diplom8.ru]купить диплом врача[/url] .
Diplomi_sbMt
29 Oct 25 at 6:54 pm
купить диплом в северодвинске [url=https://www.rudik-diplom5.ru]купить диплом в северодвинске[/url] .
Diplomi_ozma
29 Oct 25 at 6:54 pm
https://martiresportes.com/de-de
BrianFab
29 Oct 25 at 6:55 pm
купить диплом в бузулуке [url=www.rudik-diplom3.ru]купить диплом в бузулуке[/url] .
Diplomi_dyei
29 Oct 25 at 6:56 pm
купить диплом об окончании техникума спб [url=http://frei-diplom7.ru]купить диплом об окончании техникума спб[/url] .
Diplomi_ixei
29 Oct 25 at 6:56 pm
купить диплом средне техническое [url=https://rudik-diplom4.ru/]купить диплом средне техническое[/url] .
Diplomi_pdOr
29 Oct 25 at 6:56 pm
где купить диплом с занесением реестр [url=http://frei-diplom6.ru/]где купить диплом с занесением реестр[/url] .
Diplomi_usOl
29 Oct 25 at 6:58 pm
купить диплом в ростове-на-дону [url=rudik-diplom2.ru]купить диплом в ростове-на-дону[/url] .
Diplomi_qnpi
29 Oct 25 at 6:58 pm
Купить диплом колледжа в Херсон [url=educ-ua7.ru]educ-ua7.ru[/url] .
Diplomi_cdea
29 Oct 25 at 6:59 pm
Interesantísima guía sobre los juegos de casino online más populares en Pin Up México.
Sorprende lo bien que han evolucionado las tragamonedas más
famosas dentro del catálogo de Pin-Up Casino. La información sobre
los multiplicadores, rondas de bonificación y pagos en cascada fue muy útil.
Recomiendo leer el artículo completo si quieres descubrir qué juegos están marcando tendencia
en Pin Up Casino.
Además, me encantó que también mencionaran títulos como Plinko
y Fruit Cocktail, que ofrecen algo diferente al jugador
tradicional.
No dudes en leer la nota completa y descubrir por qué
estos juegos son tendencia en los casinos online de México.
read more
29 Oct 25 at 6:59 pm
купить диплом в ачинске [url=http://rudik-diplom14.ru/]купить диплом в ачинске[/url] .
Diplomi_gtea
29 Oct 25 at 7:00 pm
купить диплом в белгороде [url=https://rudik-diplom8.ru/]купить диплом в белгороде[/url] .
Diplomi_qkMt
29 Oct 25 at 7:01 pm
купить диплом в волжском [url=https://rudik-diplom10.ru]купить диплом в волжском[/url] .
Diplomi_dvSa
29 Oct 25 at 7:01 pm
диплом купить с занесением в реестр рязань [url=https://www.frei-diplom5.ru]https://www.frei-diplom5.ru[/url] .
Diplomi_blPa
29 Oct 25 at 7:02 pm
В Ростове-на-Дону клиника «ЧСП№1» предоставляет услуги по выводу из запоя. Вы можете заказать выезд нарколога на дом или пройти лечение в стационаре. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Подробнее тут – [url=https://vyvod-iz-zapoya-rostov18.ru/]вывод из запоя в стационаре в ростове-на-дону[/url]
CharlesNof
29 Oct 25 at 7:02 pm
https://martiresportes.com/de-de
BrianFab
29 Oct 25 at 7:02 pm
купить диплом логиста [url=https://rudik-diplom13.ru/]купить диплом логиста[/url] .
Diplomi_jzon
29 Oct 25 at 7:02 pm
куплю диплом с занесением [url=http://rudik-diplom6.ru/]куплю диплом с занесением[/url] .
Diplomi_piKr
29 Oct 25 at 7:03 pm
купить диплом строительного техникума [url=https://educ-ua7.ru/]https://educ-ua7.ru/[/url] .
Diplomi_isea
29 Oct 25 at 7:04 pm
рейтинг агентств по seo [url=https://luchshie-digital-agencstva.ru]рейтинг агентств по seo[/url] .
lychshie digital agentstva_vioi
29 Oct 25 at 7:04 pm
купить диплом университета с занесением в реестр [url=www.frei-diplom6.ru/]купить диплом университета с занесением в реестр[/url] .
Diplomi_gpOl
29 Oct 25 at 7:04 pm
сколько стоит купить диплом медсестры [url=frei-diplom13.ru]сколько стоит купить диплом медсестры[/url] .
Diplomi_kxkt
29 Oct 25 at 7:05 pm
купить диплом железнодорожника [url=http://rudik-diplom3.ru]купить диплом железнодорожника[/url] .
Diplomi_egei
29 Oct 25 at 7:05 pm
купить диплом в буйнакске [url=http://www.rudik-diplom11.ru]http://www.rudik-diplom11.ru[/url] .
Diplomi_awMi
29 Oct 25 at 7:05 pm
купить диплом врача с занесением в реестр [url=http://www.frei-diplom1.ru]купить диплом врача с занесением в реестр[/url] .
Diplomi_gyOi
29 Oct 25 at 7:05 pm
купить диплом в ставрополе [url=http://rudik-diplom14.ru/]купить диплом в ставрополе[/url] .
Diplomi_bxea
29 Oct 25 at 7:06 pm
Good post. I learn something new and challenging on websites
I stumbleupon everyday. It will always be useful to read through articles from other authors and
practice a little something from their sites.
ankara kürtaj
29 Oct 25 at 7:06 pm
купить диплом с занесением в реестр барнаул [url=https://frei-diplom4.ru]купить диплом с занесением в реестр барнаул[/url] .
Diplomi_puOl
29 Oct 25 at 7:07 pm
диплом внесенный в реестр купить [url=www.frei-diplom5.ru/]диплом внесенный в реестр купить[/url] .
Diplomi_pbPa
29 Oct 25 at 7:07 pm
купить диплом механика [url=http://rudik-diplom5.ru/]купить диплом механика[/url] .
Diplomi_jqma
29 Oct 25 at 7:08 pm
купить диплом в ессентуках [url=http://rudik-diplom13.ru/]купить диплом в ессентуках[/url] .
Diplomi_xron
29 Oct 25 at 7:08 pm
В Ростове-на-Дону клиника «ЧСП№1» предоставляет услуги по выводу из запоя. Вы можете заказать выезд нарколога на дом или пройти лечение в стационаре. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
Углубиться в тему – [url=https://vyvod-iz-zapoya-rostov17.ru/]нарколог на дом вывод из запоя в ростове-на-дону[/url]
PrestonNaivy
29 Oct 25 at 7:08 pm
Ꮃith heuristic methods instructed ɑt OMT, pupils discover tօ bеlieve like mathematicians,
firing սp intereѕt and drive foг exceptional test efficiency.
Сhange math difficulties into triumphs ѡith OMT Math
Tuition’ѕ blend οf online and on-site options,
ƅacked by a track record оf student excellence.
Ӏn a system ԝhere math education haѕ actually progressed tߋ cultivate innovation аnd worldwide competitiveness, registering іn math tuition ensures trainees stay ahead by
deepening their understanding and application of crucial concepts.
Tuition programs fоr primary school math concentrate ᧐n mistake
analysis frօm past PSLE documents, teaching trainees tо avoid repeating errors іn computations.
Detеrmining аnd correcting details weaqk рoints, ⅼike in likelihood օr coordinate geometry, mɑkes secondary tuition іmportant for
Ο Level quality.
Junior college math tuition promotes collaborative discovering іn little teams, boosting peer discussions ߋn complex A Level concepts.
OMT sticks οut with its exclusive mathematics curriculum, diligently developed tօ match the Singapore MOE syllabus by completing theoretical voids
tһat typical school lessons migһt overlook.
OMT’ѕ online quizzes provide instant comments ѕia, so you
can deal ԝith errors quіckly ɑnd see your
grades improve ⅼike magic.
By integrating innovation, online math tuition involves digital-native Singapore trainees fоr interactive exam alteration.
Ꮋere is my һomepage singapore primary 2 math tuition
singapore primary 2 math tuition
29 Oct 25 at 7:08 pm
Clearance $10 & Under
clearance sale
29 Oct 25 at 7:09 pm
Latest adult websites bring innovative content for adult entertainment.
Explore safe new platforms for a modern experience.
Feel free to visit my web page … Online Oxycodone Pharmacy
Online Oxycodone Pharmacy
29 Oct 25 at 7:10 pm
Good respond in return of this difficulty with real arguments and describing the whole thing on the topic of
that.
Finaurex
29 Oct 25 at 7:10 pm
купить диплом колледжа [url=rudik-diplom8.ru]купить диплом колледжа[/url] .
Diplomi_fqMt
29 Oct 25 at 7:10 pm
Helpful info. Lucky me I discovered your web site accidentally, and I am stunned why
this accident did not happened in advance! I bookmarked it.
سمساری سیار غرب تهران
29 Oct 25 at 7:11 pm
можно купить диплом медсестры [url=https://frei-diplom13.ru]можно купить диплом медсестры[/url] .
Diplomi_amkt
29 Oct 25 at 7:11 pm
купить диплом мастера маникюра и педикюра [url=www.rudik-diplom4.ru/]купить диплом мастера маникюра и педикюра[/url] .
Diplomi_vxOr
29 Oct 25 at 7:11 pm
купить диплом в иваново [url=www.rudik-diplom10.ru/]купить диплом в иваново[/url] .
Diplomi_hnSa
29 Oct 25 at 7:11 pm
купить диплом в спб техникума [url=https://frei-diplom7.ru]купить диплом в спб техникума[/url] .
Diplomi_hdei
29 Oct 25 at 7:12 pm
диплом купить с проводкой [url=www.frei-diplom1.ru/]диплом купить с проводкой[/url] .
Diplomi_loOi
29 Oct 25 at 7:12 pm