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!
1xbet g?ncel giri? [url=https://1xbet-16.com/]1xbet g?ncel giri?[/url] .
1xbet_gtOn
26 Oct 25 at 12:08 pm
kraken onion
кракен ссылка
JamesDaync
26 Oct 25 at 12:09 pm
birxbet giri? [url=1xbet-13.com]1xbet-13.com[/url] .
1xbet_bvKa
26 Oct 25 at 12:09 pm
1 x bet [url=http://1xbet-10.com/]http://1xbet-10.com/[/url] .
1xbet_szea
26 Oct 25 at 12:10 pm
Follow the platform’s withdrawal process to transfer your funds securely.
web site
26 Oct 25 at 12:10 pm
1xbet resmi [url=http://1xbet-14.com]http://1xbet-14.com[/url] .
1xbet_nget
26 Oct 25 at 12:12 pm
1x bet giri? [url=https://1xbet-10.com/]https://1xbet-10.com/[/url] .
1xbet_wrea
26 Oct 25 at 12:12 pm
медицинская техника [url=www.medicinskaya-tehnika.ru]медицинская техника[/url] .
medicinskaya tehnika_znEi
26 Oct 25 at 12:12 pm
поставщик медицинского оборудования [url=https://www.medoborudovanie-postavka.ru]поставщик медицинского оборудования[/url] .
postavka medicinskogo oborydovaniya_dvsn
26 Oct 25 at 12:12 pm
xbet [url=http://1xbet-12.com]xbet[/url] .
1xbet_xySr
26 Oct 25 at 12:14 pm
Ищу вывести тараканов с выездом в область.
обработка от клопов
KennethceM
26 Oct 25 at 12:17 pm
медсестра которая купила диплом врача [url=https://www.frei-diplom15.ru]https://www.frei-diplom15.ru[/url] .
Diplomi_bkoi
26 Oct 25 at 12:18 pm
madmadedesigns – For a niche audience looking for something “crafted” and unique, it’s a good candidate.
Hilton Mccaffrey
26 Oct 25 at 12:18 pm
1x giri? [url=https://1xbet-10.com]https://1xbet-10.com[/url] .
1xbet_xkea
26 Oct 25 at 12:24 pm
goedkope Viagra tabletten online: officiële Sildenafil webshop – erectiepillen discreet bestellen
RandySkync
26 Oct 25 at 12:24 pm
войти мостбет [url=www.mostbet12031.ru]www.mostbet12031.ru[/url]
mostbet_kg_knMa
26 Oct 25 at 12:25 pm
https://zumo-spin-games.com/
AlfredThath
26 Oct 25 at 12:26 pm
1xbet tr giri? [url=http://www.1xbet-13.com]http://www.1xbet-13.com[/url] .
1xbet_eaKa
26 Oct 25 at 12:27 pm
kraken onion
kraken вход
JamesDaync
26 Oct 25 at 12:27 pm
медтехника [url=http://medicinskaya-tehnika.ru]http://medicinskaya-tehnika.ru[/url] .
medicinskaya tehnika_zkEi
26 Oct 25 at 12:29 pm
You made some decent points there. I checked on the web for
more information about the issue and found most individuals will
go along with your views on this website.
dygest
26 Oct 25 at 12:29 pm
No matter if some one searches for his required thing, therefore he/she desires to be available that in detail,
thus that thing is maintained over here.
important source
26 Oct 25 at 12:30 pm
bahis siteler 1xbet [url=www.1xbet-17.com]bahis siteler 1xbet[/url] .
1xbet_ugpl
26 Oct 25 at 12:30 pm
mostbet bet [url=http://mostbet12032.ru]mostbet bet[/url]
mostbet_kg_ohmt
26 Oct 25 at 12:31 pm
медицинская аппаратура [url=https://www.medicinskoe–oborudovanie.ru]медицинская аппаратура[/url] .
medicinskoe oborydovanie_fcei
26 Oct 25 at 12:32 pm
мостбет. регистрация. [url=mostbet12031.ru]mostbet12031.ru[/url]
mostbet_kg_hqMa
26 Oct 25 at 12:33 pm
1xbwt giri? [url=http://www.1xbet-14.com]http://www.1xbet-14.com[/url] .
1xbet_foet
26 Oct 25 at 12:33 pm
mostbet skachat 2024 [url=www.mostbet12031.ru]mostbet skachat 2024[/url]
mostbet_kg_dwMa
26 Oct 25 at 12:34 pm
Hello, I enjoy reading through your article post. I wanted to
write a little comment to support you.
buôn bán nội tạng
26 Oct 25 at 12:35 pm
Hello to every one, the contents existing at this website are
genuinely awesome for people experience, well, keep up the nice work
fellows.
receptfria alternativ till Viagra
26 Oct 25 at 12:35 pm
1xbet resmi sitesi [url=https://www.1xbet-16.com]https://www.1xbet-16.com[/url] .
1xbet_gxOn
26 Oct 25 at 12:36 pm
войти мостбет [url=https://www.mostbet12032.ru]войти мостбет[/url]
mostbet_kg_ijmt
26 Oct 25 at 12:37 pm
Профессиональная уничтожение муравьев обязательна.
обработка от тараканов
KennethceM
26 Oct 25 at 12:37 pm
Поделитесь отзывами о уничтожение черных тараканов! Как качество и цена?
санэпидемстанция отзывы
KennethceM
26 Oct 25 at 12:39 pm
mostbet вход в личный кабинет [url=https://mostbet12032.ru]https://mostbet12032.ru[/url]
mostbet_kg_lzmt
26 Oct 25 at 12:39 pm
Где купить Бутират в Стрежевом?Посоветуйте, можно ли брать на https://Crimea-Guru.ru
? Цены привлекли, доставку обещают. Но сомневаюсь насчет чистоты.
Stevenref
26 Oct 25 at 12:40 pm
1xbet resmi giri? [url=https://1xbet-17.com/]1xbet resmi giri?[/url] .
1xbet_qzpl
26 Oct 25 at 12:41 pm
кракен Москва
kraken onion
JamesDaync
26 Oct 25 at 12:41 pm
1xbet giri? yapam?yorum [url=1xbet-13.com]1xbet-13.com[/url] .
1xbet_ybKa
26 Oct 25 at 12:42 pm
Thanks a bunch for sharing this with all people you actually know what you’re talking approximately! Bookmarked. Please additionally visit my web site =). We may have a link exchange arrangement among us
https://kra42c.com
Fobertsax
26 Oct 25 at 12:44 pm
1xbet resmi sitesi [url=https://1xbet-13.com/]https://1xbet-13.com/[/url] .
1xbet_kbKa
26 Oct 25 at 12:44 pm
Do not boh chap lah, elite primary schools ready kids fοr IPschemes, accelerating tߋ JC
and aspirational roles іn medicine oг tech.
Goodness, top schools celebrate innovation, motiivating neԝ ventures іn Singapore’s startup scene.
Eh eh, composed pom ρі рi, math proves part оf the hіghest topics in primary school,
building foundation fߋr A-Level calculus.
Aiyah, primary arithmetic educates practical implementations including
money management, tһerefore guarantee үoսr youngster ɡets thiѕ correctly fгom early.
Parents, fear tһе disparity hor, mathematics groundwork proves critical іn primary school fօr understanding іnformation, vital ѡithin today’s tech-driven market.
Guardians, competitive style activated lah, robust primary mathematics guides
іn improved STEM understanding аnd construction goals.
Βesides from establishment resources, concentrate սpon arithmetic іn orԁer to avօіd frequent mistakes ѕuch as careless mistakes ɑt assessments.
Ѕt. Anthony’ѕ Primary School cultivates ɑ positive neighborhood supporting student success.
Ƭhe school builds strong foundations tһrough
quality education.
Fuhua Primary School սѕes appealing knowing witһ modern centers.
Committed teachers promote оverall quality.
Momms ɑnd dads pick іt fоr thoгough development.
Feel free tο surf to my webpage: East Spring Secondary School
East Spring Secondary School
26 Oct 25 at 12:45 pm
one x bet [url=https://www.1xbet-10.com]https://www.1xbet-10.com[/url] .
1xbet_trea
26 Oct 25 at 12:49 pm
1xbet t?rkiye giri? [url=http://1xbet-17.com/]1xbet t?rkiye giri?[/url] .
1xbet_vdpl
26 Oct 25 at 12:49 pm
медицинская техника [url=www.medicinskaya-tehnika.ru/]медицинская техника[/url] .
medicinskaya tehnika_hiEi
26 Oct 25 at 12:50 pm
Я извиняюсь, но, по-моему, Вы не правы. Могу это доказать. Пишите мне в PM.
Mixing with read sources: Combine multiple video sources, including your physical web cam, media files, wecam[url=https://web-cam4.com/]cam4 login[/url] and computer screen.
Jillbolve
26 Oct 25 at 12:51 pm
{
Artikel yang luar biasa!
Penulis mampu menjelaskan topik tentang KUBET dan Situs Judi Bola Terlengkap
dengan sangat rinci dan mudah dimengerti.
Saya juga suka bagaimana pembahasan tentang Situs Parlay Resmi, Situs Parlay Gacor, dan Situs Mix Parlay
disusun dengan struktur yang rapi.
Tambahan informasi mengenai situs parlay, kubet login, dan toto macau membuat artikel
ini terasa sangat lengkap dan relevan.|
Tulisan ini benar-benar membuka wawasan baru.
Pembahasan tentang KUBET dan Situs Judi Bola disampaikan secara jelas dan informatif.
Saya suka bagian yang menjelaskan hubungan antara Situs Parlay Resmi,
Situs Parlay Gacor, dan Situs Mix Parlay.
Selain itu, kehadiran topik seperti situs parlay, kubet login, dan toto macau membuat isi artikel ini semakin menarik untuk diikuti.|
Saya kagum dengan artikel ini karena menyajikan informasi lengkap tentang KUBET dan Situs Judi Bola
Terlengkap.
Penulis menjelaskan dengan detail bagaimana perkembangan Situs Parlay Resmi dan Situs Mix
Parlay menjadi bagian pen
KUBET
26 Oct 25 at 12:51 pm
Спасибо за уничтожение клопов в общежитии! Всё чисто и безопасно.
профессиональная дератизация
KennethceM
26 Oct 25 at 12:52 pm
mostbet kg [url=mostbet12032.ru]mostbet kg[/url]
mostbet_kg_rzmt
26 Oct 25 at 12:52 pm
It is perfect time to make some plans for the future and
it’s time to be happy. I have read this put up and if I may just I want to counsel you few fascinating
things or tips. Maybe you can write next articles relating to this article.
I desire to read even more issues approximately it!
32win79.top
26 Oct 25 at 12:52 pm