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.kuhni-spb-4.ru]кухни на заказ спб[/url] .
kyhni spb_bqer
7 Oct 25 at 2:54 pm
My coder is trying to convince me to move to .net from PHP.
I have always disliked the idea because of the costs. But he’s tryiong none the less.
I’ve been using WordPress on various websites for about a year and
am worried about switching to another platform. I have heard very good things about blogengine.net.
Is there a way I can import all my wordpress posts
into it? Any help would be greatly appreciated!
turkey visa for australian
7 Oct 25 at 2:54 pm
sportbets [url=https://sportivnye-novosti-1.ru]sportbets[/url] .
sportivnie novosti_gkpi
7 Oct 25 at 2:54 pm
Mediverm Online: Stromectol ivermectin tablets for humans USA – Stromectol ivermectin tablets for humans USA
Morrisluh
7 Oct 25 at 2:56 pm
новости киберспорта [url=www.sportivnye-novosti-1.ru]новости киберспорта[/url] .
sportivnie novosti_tjpi
7 Oct 25 at 2:56 pm
двигатель дымит Проблемы с двигателем – общий запрос на поиск информации о возможных неисправностях двигателя и способах их устранения. Важно предоставить полезные статьи и советы по диагностике и ремонту двигателя.
JamesMig
7 Oct 25 at 2:58 pm
клиника наркология [url=http://narkologicheskaya-klinika-20.ru/]http://narkologicheskaya-klinika-20.ru/[/url] .
narkologicheskaya klinika _csPr
7 Oct 25 at 2:58 pm
где купить диплом мед колледжа [url=http://frei-diplom8.ru/]http://frei-diplom8.ru/[/url] .
Diplomi_njsr
7 Oct 25 at 3:00 pm
https://mart-media.ru
DonaldtiEls
7 Oct 25 at 3:00 pm
новости футбола [url=http://sportivnye-novosti-1.ru]новости футбола[/url] .
sportivnie novosti_wbpi
7 Oct 25 at 3:05 pm
спорт онлайн [url=novosti-sporta-8.ru]спорт онлайн[/url] .
novosti sporta_rfMa
7 Oct 25 at 3:05 pm
новости хоккея [url=https://sport-novosti-2.ru/]новости хоккея[/url] .
sport novosti_shmn
7 Oct 25 at 3:06 pm
глория мебель [url=https://kuhni-spb-4.ru/]kuhni-spb-4.ru[/url] .
kyhni spb_imer
7 Oct 25 at 3:06 pm
Everyone loves it when folks get together and share views.
Great blog, continue the good work!
go99
7 Oct 25 at 3:07 pm
купить диплом в северске [url=http://rudik-diplom6.ru]http://rudik-diplom6.ru[/url] .
Diplomi_haKr
7 Oct 25 at 3:07 pm
Стационар «Частного Медика?24» обеспечивает комфорт и безопасность при лечении запоя.
Подробнее тут – https://vyvod-iz-zapoya-v-stacionare-voronezh22.ru
Stevennom
7 Oct 25 at 3:07 pm
спортивные аналитики [url=www.novosti-sporta-7.ru]www.novosti-sporta-7.ru[/url] .
novosti sporta_epOt
7 Oct 25 at 3:08 pm
Стационар «Частного Медика 24» — это круглосуточная помощь при запое, современные капельницы и заботливый уход.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-v-stacionare22.ru/]наркология вывод из запоя в стационаре[/url]
GordonGok
7 Oct 25 at 3:08 pm
You could definitely see your enthusiasm in the article you write.
The sector hopes for more passionate writers like you who
aren’t afraid to mention how they believe. Always go after your heart.
memewars.gg caution crypto scam
7 Oct 25 at 3:09 pm
Great blog here! Also your web site loads up fast!
What web host are you using? Can I get your affiliate link to your host?
I wish my site loaded up as quickly as yours lol
https://jilliankaulpeterson.com/
Ilustrasi Digital
7 Oct 25 at 3:09 pm
последние новости спорта [url=www.novosti-sporta-8.ru/]последние новости спорта[/url] .
novosti sporta_whMa
7 Oct 25 at 3:11 pm
стационар на дому нарколог [url=http://narkolog-na-dom-1.ru/]http://narkolog-na-dom-1.ru/[/url] .
narkolog na dom_jfkt
7 Oct 25 at 3:11 pm
частные наркологические клиники в москве [url=www.narkologicheskaya-klinika-20.ru]www.narkologicheskaya-klinika-20.ru[/url] .
narkologicheskaya klinika _qkPr
7 Oct 25 at 3:11 pm
Buy marijuana online in Europe from a reliable Holland weed shop.
Experience top-grade weed, THC vapes, cannabis edibles, and others.
The online weed delivery across Europe offers speedy,
safe, and private shipping. Enjoy top-grade weed products with guaranteed satisfaction and professional
service throughout EU nations.
Buy Premium Cannabis in Europe
7 Oct 25 at 3:12 pm
Программы вывода из запоя в Самаре включают детоксикацию, медикаментозную поддержку и работу с психотерапевтом.
Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]наркология вывод из запоя в стационаре самара[/url]
Davidcar
7 Oct 25 at 3:12 pm
кухни на заказ спб каталог [url=www.kuhni-spb-4.ru/]кухни на заказ спб каталог[/url] .
kyhni spb_dker
7 Oct 25 at 3:12 pm
Just desire to say your article is as amazing. The clearness in your post is simply cool and i can assume
you are an expert on this subject. Fine with your permission let me to
grab your RSS feed to keep up to date with forthcoming
post. Thanks a million and please keep up the gratifying
work.
Alpha Wearable
7 Oct 25 at 3:12 pm
Hi, I do think this is a great site. I stumbledupon it 😉 I may come back once again since i have book-marked it.
Money and freedom is the best way to change, may you be rich and continue to
guide others.
Scatto Bitrail Reseña
7 Oct 25 at 3:13 pm
I think that is among the such a lot important information for me.
And i’m glad studying your article. But want to commentary
on few common things, The website taste is great, the articles is in point of fact nice :
D. Excellent task, cheers
https://y3g7ii.za.com/
7 Oct 25 at 3:13 pm
Ich finde es unglaublich Snatch Casino, es bietet einen einzigartigen Thrill. Der Katalog ist einfach gigantisch, mit Tausenden von Crypto-freundlichen Spielen. Der Kundenservice ist erstklassig, mit tadellosem Follow-up. Der Prozess ist einfach und reibungslos, trotzdem mehr Freispiele waren ein Plus. Kurz gesagt Snatch Casino garantiert eine top Spielerfahrung fur Online-Wetten-Enthusiasten ! Au?erdem die Plattform ist visuell top, fugt Komfort zum Spiel hinzu.
snatch casino gutscheincode|
Hichititan8H8zef
7 Oct 25 at 3:13 pm
новости киберспорта [url=sportivnye-novosti-1.ru]новости киберспорта[/url] .
sportivnie novosti_afpi
7 Oct 25 at 3:13 pm
новости хоккея [url=http://novosti-sporta-7.ru/]новости хоккея[/url] .
novosti sporta_osOt
7 Oct 25 at 3:13 pm
прогноз на сегодня на спорт [url=https://www.prognozy-ot-professionalov4.ru]https://www.prognozy-ot-professionalov4.ru[/url] .
prognozi ot professionalov_zwOr
7 Oct 25 at 3:13 pm
В Сочи клиника «Детокс» предлагает полный курс вывода из запоя в стационаре. Круглосуточный медицинский контроль гарантирует безопасность и эффективность лечения.
Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-sochi24.ru/]вывод из запоя цена в сочи[/url]
RobertoToott
7 Oct 25 at 3:16 pm
свежие новости спорта [url=https://sportivnye-novosti-1.ru]свежие новости спорта[/url] .
sportivnie novosti_lvpi
7 Oct 25 at 3:16 pm
новости тенниса [url=http://novosti-sporta-7.ru]новости тенниса[/url] .
novosti sporta_kkOt
7 Oct 25 at 3:17 pm
домашний нарколог помощь [url=http://narkolog-na-dom-1.ru]http://narkolog-na-dom-1.ru[/url] .
narkolog na dom_bzkt
7 Oct 25 at 3:17 pm
В больничных условиях «Частного Медика 24» врачи контролируют давление, сердце и функции жизненно важных органов при выводе из запоя.
Подробнее – [url=https://vyvod-iz-zapoya-v-stacionare-samara23.ru/]наркология вывод из запоя в стационаре самара[/url]
Carlosquold
7 Oct 25 at 3:18 pm
кухни под заказ спб [url=kuhni-spb-4.ru]кухни под заказ спб[/url] .
kyhni spb_irer
7 Oct 25 at 3:18 pm
Discover Singapore’ѕ top deals at Kaizenaire.ϲom,
the leading curator of shopping promotions.
Singapore’ѕ shopping paradise standing іs a magnet for citizens whօ love discovering hidden promotions ɑnd racking uр wonderful deals.
Organizing chess tournaments challenges tactical minds ɑmong
Singaporeans, and remember tⲟ гemain updated оn Singapore’s
moѕt recent promotions ɑnd shopping deals.
Strip and Browhyaus provide beauty treatments ⅼike waxing аnd eyebrow pet grooming, appreciated
ƅy brushing enthusiasts іn Singapore for their specialist solutions.
SK Jewellery crafts ɡreat gold ɑnd diamond pieces mah, valued ƅy Singaporeans
for their stunning designs ⅾuring joyful events sia.
Lot Seng Leong protects vintage kopitiam feelings ԝith
butter kopi, favored Ьy nostalgics fоr tһe
same practices.
Auntie love leh, Kaizenaire.сom’ѕ shopping discount rates оne.
Feel free to surf tߋ my web pаge clinique promotions
clinique promotions
7 Oct 25 at 3:19 pm
Продажа велосипедов через интернет-магазин kra 40 at кракен darknet кракен onion кракен ссылка onion
RichardPep
7 Oct 25 at 3:20 pm
Круглосуточная выездная служба клиники «Медлайн Надежда» — это возможность получить профессиональную наркологическую помощь дома, без поездок и без огласки. Мы работаем по всему Красногорску и ближайшим локациям, приезжаем оперативно, соблюдаем полную конфиденциальность и не ставим на учёт. Выезд осуществляют врачи-наркологи с клиническим опытом, укомплектованные инфузионными системами, пульсоксиметром, тонометром, средствами для ЭКГ по показаниям и набором сертифицированных препаратов. Наша задача — быстро стабилизировать состояние, снять интоксикацию и тревогу, вернуть сон и предложить понятный план дальнейшей терапии.
Получить дополнительные сведения – [url=https://narkolog-na-dom-krasnogorsk6.ru/]вызов врача нарколога на дом[/url]
MichaelBef
7 Oct 25 at 3:21 pm
прогнозы на спорт бесплатно от профессионалов на сегодня [url=https://www.prognozy-ot-professionalov4.ru]https://www.prognozy-ot-professionalov4.ru[/url] .
prognozi ot professionalov_rsOr
7 Oct 25 at 3:22 pm
клиника наркологическая платная [url=https://narkologicheskaya-klinika-20.ru/]narkologicheskaya-klinika-20.ru[/url] .
narkologicheskaya klinika _hePr
7 Oct 25 at 3:23 pm
Капельница от запоя в Нижнем Новгороде — процедура, направленная на детоксикацию организма и восстановление нормального самочувствия. Она включает в себя введение препаратов, способствующих выведению токсинов и восстановлению функций органов.
Узнать больше – [url=https://vyvod-iz-zapoya-nizhnij-novgorod11.ru/]вывод из запоя капельница на дому[/url]
Georgefaw
7 Oct 25 at 3:23 pm
https://eiforiyavkusa.ru
DonaldtiEls
7 Oct 25 at 3:27 pm
Hey there! I just would like to offer you a big thumbs up for
the excellent info you have right here on this post. I am
coming back to your web site for more soon.
app kkwin
7 Oct 25 at 3:28 pm
please click the following webpage
PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog
please click the following webpage
7 Oct 25 at 3:28 pm
наркологический частный центр [url=https://narkologicheskaya-klinika-20.ru]https://narkologicheskaya-klinika-20.ru[/url] .
narkologicheskaya klinika _uePr
7 Oct 25 at 3:29 pm
Hi there! I just wanted to ask if you ever have any problems with hackers?
My last blog (wordpress) was hacked and I ended up losing months of hard
work due to no backup. Do you have any solutions to stop
hackers?
LucroX AI
7 Oct 25 at 3:30 pm