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.kinogo-12.top]www.kinogo-12.top[/url] .
kinogo_zuol
16 Sep 25 at 2:58 pm
https://vgarderobe.ru/tolstovki-i-kofty-dlya-devochek-buffalo-bc-2600.html
StanleyToumb
16 Sep 25 at 2:59 pm
mostbet uz [url=https://mostbet4175.ru/]https://mostbet4175.ru/[/url]
mostbet_lmmi
16 Sep 25 at 2:59 pm
https://t.me/s/REYtIng_casiNO_RuSSIA
Waltervig
16 Sep 25 at 2:59 pm
стоматолог ортодонт [url=www.stomatologiya-voronezh-1.ru]стоматолог ортодонт[/url] .
stomatologiya v Voroneje_nhka
16 Sep 25 at 2:59 pm
buy prednisone 1 mg
can i order cheap prednisone without a prescription
16 Sep 25 at 3:00 pm
фантастика онлайн [url=http://kinogo-12.top/]http://kinogo-12.top/[/url] .
kinogo_wwol
16 Sep 25 at 3:01 pm
Mijn schrijfstijl is makkelijk leesbaar. Ik vermijd vaktechnische taal om de
gokwereld voor het grote publiek te demystificeren.
Bradly
16 Sep 25 at 3:01 pm
Fantastic site. A lot of useful information here.
I’m sending it to a few buddies ans additionally sharing in delicious.
And naturally, thanks to your effort!
Opulatrix
16 Sep 25 at 3:01 pm
автоматические рулонные шторы на окна [url=http://avtomaticheskie-rulonnye-shtory5.ru/]автоматические рулонные шторы на окна[/url] .
avtomaticheskie rylonnie shtori_mxsr
16 Sep 25 at 3:02 pm
смотреть фильмы бесплатно [url=www.kinogo-12.top/]www.kinogo-12.top/[/url] .
kinogo_jvol
16 Sep 25 at 3:03 pm
Very good blog! Do you have any recommendations for aspiring
writers? I’m hoping to start my own site soon but I’m a little lost on everything.
Would you recommend starting with a free platform like WordPress or go for a paid option? There are so
many choices out there that I’m completely confused ..
Any ideas? Cheers!
флагман казино зеркало
16 Sep 25 at 3:05 pm
С первых минут растопки чугунные печи ПроМеталл дарят мягкий жар, насыщенный пар и уверенную долговечность. Как официальный представитель завода в Москве, подберем печь под ваш объем, дизайн и бюджет, а также возьмем на себя доставку и монтаж. Ищете печь атмосфера? Узнайте больше на prometall.shop и выберите идеальную «Атмосферу» для вашей парной. Дадим бесплатную консультацию, расскажем про акции и подготовим полезные подарки. Сделайте парную местом силы: быстрый прогрев, длительное удержание тепла и простое обслуживание.
ralewnaito
16 Sep 25 at 3:06 pm
лечение зубов [url=http://stomatologiya-voronezh-1.ru]лечение зубов[/url] .
stomatologiya v Voroneje_tzka
16 Sep 25 at 3:07 pm
Dive deep гight into curated promotions ᴡith Kaizenaire.com, thе top site foг Singapore.
Singaporeans’ exhilaration fоr deals is apparent in Singapore’s
busy shopping heaven.
Singaporeans fіnd happiness іn baking homemade deals ᴡith іn tһeir kitchens,
and kеep іn mind tο stay upgraded on Singapore’s lateѕt promotions ɑnd
shopping deals.
Grеat Eastern supplies life insurance policy аnd health
care plans, cherished ƅy Singaporeans for tһeir comprehensive protection аnd satisfaction in uncertain tіmes.
Axe Brand Universal Oil ᥙses medicated oils for pain relief leh, adored
Ьy Singaporeans for their effective treatments іn daily pains ߋne.
Lim Chee Guan barbeques premium bak kwa, loved fοr juicy, smoky
pork Ԁuring Chinese Ⲛew Year.
Much better prepare leh, Kaizenaire.ϲom updates useѕ one.
deals
16 Sep 25 at 3:09 pm
электрические гардины для штор [url=https://karniz-s-elektroprivodom-kupit.ru]https://karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_geEr
16 Sep 25 at 3:10 pm
I have read so many articles regarding the blogger lovers however this paragraph is
really a nice paragraph, keep it up.
singapore seo
16 Sep 25 at 3:11 pm
рулонные шторы купить в москве [url=https://avtomaticheskie-rulonnye-shtory5.ru]https://avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_xvsr
16 Sep 25 at 3:12 pm
кино онлайн [url=http://www.kinogo-12.top]кино онлайн[/url] .
kinogo_rzol
16 Sep 25 at 3:14 pm
Если состояние стремительно ухудшается, ждать опасно: осложнения могут развиваться в течение часов. Немедленная помощь врача-нарколога показана, когда наблюдаются:
Детальнее – http://narkologicheskaya-pomoshch-ramenskoe7.ru/skoraya-narkologicheskaya-pomoshch-v-ramenskom/https://narkologicheskaya-pomoshch-ramenskoe7.ru
Jacobham
16 Sep 25 at 3:16 pm
рулонная штора цена [url=http://elektricheskie-rulonnye-shtory15.ru/]http://elektricheskie-rulonnye-shtory15.ru/[/url] .
elektricheskie rylonnie shtori_mtEi
16 Sep 25 at 3:16 pm
электрокарнизы для штор купить в москве [url=http://karniz-s-elektroprivodom-kupit.ru/]http://karniz-s-elektroprivodom-kupit.ru/[/url] .
karniz s elektroprivodom kypit_qdEr
16 Sep 25 at 3:16 pm
рулонные жалюзи на окна цена [url=avtomaticheskie-rulonnye-shtory5.ru]avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_lgsr
16 Sep 25 at 3:16 pm
Soho303 Merupakan Sebuah Halaman Situs Slot
Gacor Online Terbaru Yang Menyediakan Daftar Akun Demo Slot Gacor Online WSO Gratis Terbaru.
Soho303
16 Sep 25 at 3:17 pm
Содержание процедуры
Получить больше информации – https://vyvod-iz-zapoya-shchelkovo6.ru/pomoshch-vyvod-iz-zapoya-v-shchelkovo
RamonArOwL
16 Sep 25 at 3:17 pm
https://mymedia.com.ua/ukraynskye-vyrtualn%d1%8be-nomera-novaya-%d1%8dra-telefonnoj-svyazy/
https://mymedia.com.ua/ukraynskye-vyrtualne-nomera-novaya-ra-telefonnoj-svyazy/
16 Sep 25 at 3:19 pm
электро жалюзи на окна [url=https://elektricheskie-rulonnye-shtory15.ru/]https://elektricheskie-rulonnye-shtory15.ru/[/url] .
elektricheskie rylonnie shtori_arEi
16 Sep 25 at 3:22 pm
сериалы тнт онлайн [url=http://www.kinogo-12.top]http://www.kinogo-12.top[/url] .
kinogo_tjol
16 Sep 25 at 3:23 pm
скачать букмекерская контора регистрация [url=1win12014.ru]1win12014.ru[/url]
1win_pyOl
16 Sep 25 at 3:24 pm
Tulisan ini benar-benar informatif karena membahas hal yang relevan dengan perkembangan dunia game online.
Saya merasa senang membaca penjelasan detail tentang KUBET
yang dikenal sebagai Situs Judi Bola Terlengkap.
Bagian yang membahas tentang Situs Parlay Resmi juga membuka wawasan bagi pembaca yang ingin memahami strategi permainan.
Selain itu, informasi tentang Situs Parlay Gacor terasa menyeluruh sehingga mudah dipahami oleh siapa saja.
Penjelasan mengenai Situs Mix Parlay di artikel ini benar-benar membantu, apalagi
gaya penulisan yang digunakan ringan.
Menurut saya, artikel ini cocok sekali untuk siapa saja
yang ingin memahami lebih dalam mengenai dunia taruhan bola online.
Terutama karena disampaikan dengan bahasa yang mudah namun tetap memberikan isi yang mendalam.
Secara keseluruhan, artikel ini sangat bermanfaat
karena mampu menjelaskan berbagai aspek penting mulai dari KUBET, Situs Judi Bola
Terlengkap, Situs Parlay Resmi, Situs Parlay Gacor, hingga Situs Mix
Parlay.
Saya berharap ke depannya akan ada lebih banyak konten serupa yang dikembangkan, sehingga para pembaca dapat terus mendapatkan informasi yang bermanfaat.
comment-364823
16 Sep 25 at 3:24 pm
стоматология клиника [url=https://stomatologiya-voronezh-1.ru]стоматология клиника[/url] .
stomatologiya v Voroneje_tgka
16 Sep 25 at 3:25 pm
смотреть мультфильмы онлайн бесплатно [url=https://www.kinogo-12.top]https://www.kinogo-12.top[/url] .
kinogo_chol
16 Sep 25 at 3:27 pm
электрокарниз москва [url=http://karniz-s-elektroprivodom-kupit.ru]http://karniz-s-elektroprivodom-kupit.ru[/url] .
karniz s elektroprivodom kypit_rcEr
16 Sep 25 at 3:28 pm
фильмы в хорошем качестве [url=www.kinogo-12.top/]www.kinogo-12.top/[/url] .
kinogo_tbol
16 Sep 25 at 3:30 pm
When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three emails with the same comment.
Is there any way you can remove people from that service?
Thank you!
Token Tact
16 Sep 25 at 3:31 pm
Does your website have a contact page? I’m having problems locating it but, I’d
like to shoot you an e-mail. I’ve got some suggestions for your
blog you might be interested in hearing. Either way, great website and I look forward to seeing it
grow over time.
https://git.cavemanon.xyz/
16 Sep 25 at 3:31 pm
электрокарнизы [url=http://karniz-s-elektroprivodom-kupit.ru/]http://karniz-s-elektroprivodom-kupit.ru/[/url] .
karniz s elektroprivodom kypit_dpEr
16 Sep 25 at 3:32 pm
where to get cheap tetracycline prices
buy tetracycline aquarium
16 Sep 25 at 3:32 pm
рулонные шторы автоматические [url=www.elektricheskie-rulonnye-shtory15.ru]www.elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_flEi
16 Sep 25 at 3:34 pm
https://instrumen.unmuhjember.ac.id/
https://instrumen.unmuhjember.ac.id/
16 Sep 25 at 3:35 pm
производитель рулонных штор [url=www.elektricheskie-rulonnye-shtory15.ru]www.elektricheskie-rulonnye-shtory15.ru[/url] .
elektricheskie rylonnie shtori_zlEi
16 Sep 25 at 3:38 pm
рулонные шторы на заказ цена [url=https://www.avtomaticheskie-rulonnye-shtory5.ru]https://www.avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_ussr
16 Sep 25 at 3:38 pm
cost cheap bactrim no prescription
can you get bactrim tablets
16 Sep 25 at 3:40 pm
смотреть комедии онлайн [url=www.kinogo-12.top]www.kinogo-12.top[/url] .
kinogo_wzol
16 Sep 25 at 3:40 pm
Подбираете оборудование из Китая? Перейдите на сайт totem28.ru где вам вы найдёте проверенное промышленное оборудование. Изучите полный ассортимент, в котором есть всё — от техники до готовых производственных линий, а мы доставляем по всей России. Узнайте подробнее о товарах и решениях, о нашей компании и комплексных услугах «под ключ» на сайте.
PybilwairL
16 Sep 25 at 3:43 pm
Hello there, I discovered your blog by the use of Google
whilst searching for a related topic, your site got here up, it seems good.
I have bookmarked it in my google bookmarks.
Hi there, simply become aware of your blog via Google, and located that it is
really informative. I’m going to be careful for brussels.
I’ll appreciate should you proceed this in future. A
lot of people might be benefited out of your
writing. Cheers!
Fundspire Axivon
16 Sep 25 at 3:44 pm
online apotheke [url=https://gesunddirekt24.shop/#]GesundDirekt24[/url] beste online-apotheke ohne rezept
StevenTilia
16 Sep 25 at 3:44 pm
шторы роллы на окна [url=https://www.avtomaticheskie-rulonnye-shtory5.ru]https://www.avtomaticheskie-rulonnye-shtory5.ru[/url] .
avtomaticheskie rylonnie shtori_mbsr
16 Sep 25 at 3:45 pm
1win официальный сайт приложение [url=http://1win12015.ru/]http://1win12015.ru/[/url]
1win_icei
16 Sep 25 at 3:47 pm
промокод на 1вин [url=http://1win12016.ru]http://1win12016.ru[/url]
1win_xqOa
16 Sep 25 at 3:48 pm