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=www.rudik-diplom2.ru]купить диплом в кисловодске[/url] .
Diplomi_sjpi
3 Oct 25 at 8:18 pm
купить диплом о высшем образовании с занесением в реестр отзывы [url=http://frei-diplom5.ru]купить диплом о высшем образовании с занесением в реестр отзывы[/url] .
Diplomi_foPa
3 Oct 25 at 8:18 pm
где купить диплом [url=http://rudik-diplom3.ru/]где купить диплом[/url] .
Diplomi_hbei
3 Oct 25 at 8:20 pm
как купить диплом о высшем образовании с занесением в реестр [url=https://www.frei-diplom6.ru]как купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_ukOl
3 Oct 25 at 8:20 pm
прогноз футбол на сегодня [url=https://prognozy-na-futbol-10.ru]прогноз футбол на сегодня[/url] .
prognozi na fytbol_uxOi
3 Oct 25 at 8:20 pm
купить диплом о среднем профессиональном образовании с занесением в реестр [url=https://frei-diplom1.ru]купить диплом о среднем профессиональном образовании с занесением в реестр[/url] .
Diplomi_hhOi
3 Oct 25 at 8:20 pm
Купить диплом колледжа в Полтава [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .
Diplomi_slea
3 Oct 25 at 8:21 pm
медицинская техника [url=http://xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai]http://xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai[/url] .
oborydovanie medicinskoe_ynOn
3 Oct 25 at 8:21 pm
где купить настоящий диплом колледжа [url=https://frei-diplom8.ru/]https://frei-diplom8.ru/[/url] .
Diplomi_txsr
3 Oct 25 at 8:22 pm
I was wondering if you ever thought of changing the structure of your website?
Its very well written; I love what youve got to say. But maybe
you could a little more in the way of content so people
could connect with it better. Youve got an awful lot of text for only having 1 or 2 pictures.
Maybe you could space it out better?
online casino sign up bonus
3 Oct 25 at 8:22 pm
I all the time used to read article in news papers but now as I
am a user of internet thus from now I am using net for content, thanks to web.
89bet
3 Oct 25 at 8:24 pm
я купил диплом с проводкой [url=http://frei-diplom5.ru/]я купил диплом с проводкой[/url] .
Diplomi_mkPa
3 Oct 25 at 8:24 pm
купить диплом с занесением в реестр в калуге [url=http://frei-diplom2.ru]купить диплом с занесением в реестр в калуге[/url] .
Diplomi_qeEa
3 Oct 25 at 8:25 pm
купить диплом технического техникума [url=https://frei-diplom9.ru]купить диплом технического техникума[/url] .
Diplomi_rhea
3 Oct 25 at 8:25 pm
Hello it’s me, I am also visiting this website daily, this
website is genuinely fastidious and the visitors are truly sharing
nice thoughts.
canadian online pharmacies
3 Oct 25 at 8:25 pm
купить диплом в кургане занесением в реестр [url=frei-diplom6.ru]купить диплом в кургане занесением в реестр[/url] .
Diplomi_kiOl
3 Oct 25 at 8:25 pm
купить диплом в канске [url=http://rudik-diplom1.ru/]купить диплом в канске[/url] .
Diplomi_yzer
3 Oct 25 at 8:26 pm
купить диплом инженера по охране труда [url=www.rudik-diplom2.ru]купить диплом инженера по охране труда[/url] .
Diplomi_eipi
3 Oct 25 at 8:27 pm
Гибкий настенный обогреватель «Тепло Водопад» — компактная инфракрасно-плёночная панель 500 Вт для помещений до 15 м: тихо греет, направляет 95% тепла внутрь комнаты и экономит электроэнергию. Влагозащищённый элемент и алюминиевый корпус с заземлением повышают пожаробезопасность, а монтаж занимает минуты. Выберите расцветку под интерьер и подключите к терморегулятору для точного климата. Закажите на https://www.ozon.ru/product/gibkiy-nastennyy-obogrevatel-teplo-vodopad-dlya-pomeshcheniy-60h100-sm-644051427/?_bctx=CAQQ2pkC&at=NOtw7N9XWcpnz4lDCBEKww6I4y69OXsokq6yKhPqVKpL&hs=1 — отзывы подтверждают тёплый результат.
rewykndFlure
3 Oct 25 at 8:28 pm
https://bargrill-myaso.ru
PatrickGop
3 Oct 25 at 8:29 pm
купить диплом с реестром [url=www.rudik-diplom3.ru]купить диплом с реестром[/url] .
Diplomi_hjei
3 Oct 25 at 8:29 pm
Купить диплом колледжа в Чернигов [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_jdea
3 Oct 25 at 8:29 pm
онлайн-казино с лицензией Curacao. Предлагает щедрые бонусы, топовые игры от ведущих провайдеров, быстрые выплаты и круглосуточную поддержку
драгон мани рабочее зеркало
BrittGor
3 Oct 25 at 8:30 pm
купить диплом в геленджике [url=http://www.rudik-diplom11.ru]http://www.rudik-diplom11.ru[/url] .
Diplomi_viMi
3 Oct 25 at 8:31 pm
купить диплом легально [url=http://www.frei-diplom3.ru]купить диплом легально[/url] .
Diplomi_omKt
3 Oct 25 at 8:31 pm
купить диплом с занесением в реестр в москве [url=frei-diplom4.ru]купить диплом с занесением в реестр в москве[/url] .
Diplomi_swOl
3 Oct 25 at 8:33 pm
Thanks on your marvelous posting! I truly enjoyed reading it, you
may be a great author.I will be sure to bookmark your blog and may come back in the future.
I want to encourage that you continue your great writing, have
a nice weekend!
Lucent Markbit
3 Oct 25 at 8:33 pm
купить диплом с занесением в реестр [url=http://www.rudik-diplom7.ru]купить диплом с занесением в реестр[/url] .
Diplomi_xoPl
3 Oct 25 at 8:33 pm
прогнозы на сегодня футбол [url=https://prognozy-na-futbol-10.ru/]прогнозы на сегодня футбол[/url] .
prognozi na fytbol_fgOi
3 Oct 25 at 8:34 pm
Gelee Royal играть в Кет казино
Matthewbox
3 Oct 25 at 8:34 pm
купить бланк диплома [url=http://www.rudik-diplom1.ru]купить бланк диплома[/url] .
Diplomi_aber
3 Oct 25 at 8:35 pm
купить диплом техникума в самаре [url=http://frei-diplom9.ru]купить диплом техникума в самаре[/url] .
Diplomi_zqea
3 Oct 25 at 8:35 pm
купить диплом в златоусте [url=http://rudik-diplom8.ru]купить диплом в златоусте[/url] .
Diplomi_fjMt
3 Oct 25 at 8:35 pm
куплю диплом младшей медсестры [url=frei-diplom13.ru]frei-diplom13.ru[/url] .
Diplomi_sukt
3 Oct 25 at 8:36 pm
Наркологическая клиника «Возрождение» в Уфе предоставляет полный спектр услуг по лечению зависимости от психоактивных веществ и алкоголя. Мы сочетаем проверенные временем медицинские методики с инновационными технологиями, сохраняя полную анонимность пациентов. В любом случае вы можете рассчитывать на круглосуточную поддержку, комфортные условия пребывания и индивидуальный план терапии, составленный опытными специалистами.
Получить дополнительную информацию – http://narkologicheskaya-klinika-ufa9.ru
Mariofep
3 Oct 25 at 8:36 pm
футбол ставки [url=https://prognozy-na-futbol-10.ru/]prognozy-na-futbol-10.ru[/url] .
prognozi na fytbol_moOi
3 Oct 25 at 8:37 pm
купить диплом энергетика [url=http://www.rudik-diplom15.ru]купить диплом энергетика[/url] .
Diplomi_pxPi
3 Oct 25 at 8:38 pm
купить диплом пту в реестре [url=www.frei-diplom3.ru/]купить диплом пту в реестре[/url] .
Diplomi_ipKt
3 Oct 25 at 8:39 pm
точный прогнозы на футбол [url=http://prognozy-na-futbol-10.ru]http://prognozy-na-futbol-10.ru[/url] .
prognozi na fytbol_moOi
3 Oct 25 at 8:39 pm
OMT’ѕ interactive quizzes gamify knowing, mаking math habit forming fⲟr Singapore trainees ɑnd motivating them tο promote superior examination qualities.
Dive into ѕelf-paced math mastery ѡith OMT’s 12-month е-learning courses, totɑl ᴡith practice
worksheets and taped sessions f᧐r th᧐rough modification.
Ꮤith students іn Singapore beginning formal math education from day one and
dealing ᴡith һigh-stakes evaluations, math tuition սses the additional edge required to accomplish t᧐p performance іn thiѕ vital topic.
Math tuition helps primary students master PSLE
ƅy strengthening thе Singapore Math curriculum’ѕ bar
modeling technique for visual analytical.
Secondary math tuition ցets rid of the constraints of
big classroom dimensions, providing concentrated
focus tһat improves understanding fоr Ο Level prep ᴡork.
Junior college math tuition іs imрortant foг A Degrees as it deepens understanding
օf innovative calculus topics lіke integration strategies
and differential equations, ѡhich ɑrе central tο tһe test syllabus.
OMT’ѕ special mathematics program complements tһe MOE
educational program by including exclusive instance studies tһat apply math
tߋ actual Singaporean contexts.
OMT’ѕ systеm іs mobile-friendly ⲟne, so research оn the go and ѕee your math
qualities boost ԝithout missing ߋut on a beat.
Math tuition aids Singapore pupils overcome usual challenges іn computations, leading t᧐ lеss reckless errors іn tests.
my pɑge: top jc math tuition
top jc math tuition
3 Oct 25 at 8:39 pm
OMT’ѕ emphasis on foundational abilities constructs unshakeable confidence, permitting Singapore trainees tⲟ drop in love ԝith mathematics’ѕ beauty and feel
influenced for exams.
Transform mathematics obstacles іnto triumphs with
OMT Math Tuition’ѕ blend of online and on-site alternatives, Ƅacked Ƅү a track
record οf trainee excellence.
Pгovided thаt mathematics plays ɑ critical role іn Singapore’sfinancial development аnd progress, buying specialized math tuitioon equips trainees ᴡith the
analytical abilities required tо thrive іn a competitive landscape.
With PSLE mathematics evolving tߋ incⅼude mоre interdisciplinary components,
tuition ҝeeps trainees upgraded оn incorporated
questions mixing math ᴡith science contexts.
Math tuition ѕhows effective time management methods,helping secondary pupils fսll O Level exams
ᴡithin tһe assigned duration ᴡithout hurrying.
Junior college tuition provides access tߋ extra resources liҝe worksheets аnd video clip descriptions, enhancing Ꭺ Level syllabus insurance coverage.
OMT’ѕ proprietary syllabus boosts MOE criteria Ьy giving scaffolded
discovering courses tһаt slowly enhance іn complexity, constructing student
confidence.
Selection οf practice concerns ѕia, preparing yоu thoroughlү for
any math examination ɑnd much better scores.
Singapore’s meritocratic ѕystem rewards һigh up-and-comers, mаking math tuition а critical financial investment for examination prominence.
Ηere iѕ mmy blog :: bigtits student fuck math tutor
bigtits student fuck math tutor
3 Oct 25 at 8:40 pm
купить диплом в березниках [url=www.rudik-diplom7.ru]купить диплом в березниках[/url] .
Diplomi_pkPl
3 Oct 25 at 8:41 pm
Thaat iis very fascinating, You’re an excessivwly skilled blogger.
I’ve joined your feed and stay up ffor looking for more of your wonderful
post. Additionally, I’ve shared your site iin my
social networks
Vape Kits
3 Oct 25 at 8:42 pm
купить диплом в мурманске [url=https://rudik-diplom1.ru/]купить диплом в мурманске[/url] .
Diplomi_dzer
3 Oct 25 at 8:43 pm
Ahaa, its nice conversation concerning this article here at this website, I
have read all that, so now me also commenting here.
pocket wifi
3 Oct 25 at 8:44 pm
купить диплом учителя [url=http://rudik-diplom11.ru/]купить диплом учителя[/url] .
Diplomi_xvMi
3 Oct 25 at 8:45 pm
Первичный контакт — короткий, но точный скрининг: длительность эпизода, лекарства и аллергии, сон, аппетит, переносимость нагрузок, возможность обеспечить тишину на месте. На основе этих фактов врач предлагает безопасную точку входа: выезд на дом, приём без очередей или госпитализацию под наблюдением 24/7. На месте мы сразу исключаем «красные флажки», фиксируем давление/пульс/сатурацию/температуру, при показаниях выполняем ЭКГ и запускаем детокс. Параллельно выдаём «карту суток»: режим отдыха и питья, лёгкое питание, перечень нормальных ощущений и момент, когда нужно связаться внепланово. Если домашнего формата становится мало, переводим в стационар без пауз — все назначения и наблюдения «переезжают» вместе с пациентом.
Исследовать вопрос подробнее – [url=https://narkologicheskaya-klinika-odincovo0.ru/]narkologicheskaya-klinika-ceny[/url]
FidelDob
3 Oct 25 at 8:46 pm
x3137 – A simple and straightforward site, very user-friendly overall experience.
Liana Meder
3 Oct 25 at 8:46 pm
Купить диплом колледжа в Хмельницкий [url=https://educ-ua7.ru/]https://educ-ua7.ru/[/url] .
Diplomi_lkea
3 Oct 25 at 8:46 pm
купить диплом программиста [url=https://rudik-diplom7.ru/]купить диплом программиста[/url] .
Diplomi_kgPl
3 Oct 25 at 8:51 pm