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=https://rudik-diplom1.ru/]купить свидетельство о рождении[/url] .
Diplomi_oaer
14 Oct 25 at 2:45 am
На протяжении процедуры врач постоянно наблюдает за пациентом. Контролируются витальные показатели, корректируется скорость инфузии, дозировки и последовательность введения препаратов. При любых нестандартных реакциях схема лечения тут же адаптируется. Мы не используем «универсальных» капельниц: только персонализированные решения, основанные на состоянии конкретного человека.
Получить дополнительные сведения – https://narkolog-na-dom-krasnogorsk6.ru/vyzov-narkologa-na-dom-v-krasnogorske/
Danielunato
14 Oct 25 at 2:45 am
Tommy Gunn
Brentsek
14 Oct 25 at 2:46 am
диплом о среднем профессиональном образовании с занесением в реестр купить [url=https://frei-diplom1.ru/]диплом о среднем профессиональном образовании с занесением в реестр купить[/url] .
Diplomi_wfOi
14 Oct 25 at 2:48 am
карнизы для штор с электроприводом [url=http://www.karniz-shtor-elektroprivodom.ru]карнизы для штор с электроприводом[/url] .
karniz dlya shtor s elektroprivodom_lcer
14 Oct 25 at 2:49 am
buy viagra online: buy viagra online – viagra uk
Brettesofe
14 Oct 25 at 2:49 am
электрокарниз москва [url=http://karniz-elektroprivodom.ru]http://karniz-elektroprivodom.ru[/url] .
karniz elektroprivodom shtor kypit_ckei
14 Oct 25 at 2:50 am
можно ли купить диплом медсестры [url=frei-diplom13.ru]можно ли купить диплом медсестры[/url] .
Diplomi_ajkt
14 Oct 25 at 2:50 am
техникум диплом купить [url=https://frei-diplom9.ru]техникум диплом купить[/url] .
Diplomi_rcea
14 Oct 25 at 2:51 am
https://insightmaker.com/user/2wbP9QrGfLCrKYwx07HvOk
tpzpcfy
14 Oct 25 at 2:51 am
проект перепланировки нежилого помещения стоимость [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]http://pereplanirovka-nezhilogo-pomeshcheniya11.ru/[/url] .
pereplanirovka nejilogo pomesheniya_lher
14 Oct 25 at 2:52 am
купить диплом в калининграде [url=http://rudik-diplom9.ru]купить диплом в калининграде[/url] .
Diplomi_ajei
14 Oct 25 at 2:52 am
рулонные шторы на большие окна [url=https://rulonnaya-shtora-s-elektroprivodom.ru/]рулонные шторы на большие окна[/url] .
rylonnaya shtora s elektroprivodom_hoKt
14 Oct 25 at 2:53 am
купить диплом в евпатории [url=https://www.rudik-diplom7.ru]купить диплом в евпатории[/url] .
Diplomi_wyPl
14 Oct 25 at 2:54 am
купить легальный диплом техникума [url=https://www.frei-diplom8.ru]купить легальный диплом техникума[/url] .
Diplomi_fjsr
14 Oct 25 at 2:55 am
купить диплом в ростове-на-дону [url=http://www.rudik-diplom8.ru]купить диплом в ростове-на-дону[/url] .
Diplomi_eqMt
14 Oct 25 at 2:56 am
купить диплом в кунгуре [url=https://www.rudik-diplom11.ru]https://www.rudik-diplom11.ru[/url] .
Diplomi_ewMi
14 Oct 25 at 2:57 am
карниз электроприводом штор купить [url=https://karniz-elektroprivodom.ru]https://karniz-elektroprivodom.ru[/url] .
karniz elektroprivodom shtor kypit_ysei
14 Oct 25 at 2:59 am
В «Новом Пути» используются только научно обоснованные и одобренные Минздравом РФ технологии кодирования. К основным направлениям относятся:
Узнать больше – [url=https://kodirovanie-ot-alkogolizma-ehlektrostal6.ru/]кодирование от алкоголизма телефон[/url]
ScottCet
14 Oct 25 at 3:02 am
купить диплом электромонтера [url=http://rudik-diplom10.ru]купить диплом электромонтера[/url] .
Diplomi_ddSa
14 Oct 25 at 3:02 am
электрокарнизы [url=www.karniz-shtor-elektroprivodom.ru]электрокарнизы[/url] .
karniz dlya shtor s elektroprivodom_qper
14 Oct 25 at 3:02 am
согласование перепланировки нежилого помещения в нежилом здании [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru]http://pereplanirovka-nezhilogo-pomeshcheniya11.ru[/url] .
pereplanirovka nejilogo pomesheniya_hber
14 Oct 25 at 3:02 am
рулонные шторы на окна недорого [url=rulonnaya-shtora-s-elektroprivodom.ru]рулонные шторы на окна недорого[/url] .
rylonnaya shtora s elektroprivodom_ilKt
14 Oct 25 at 3:03 am
электрокарниз двухрядный [url=http://karniz-elektroprivodom.ru/]http://karniz-elektroprivodom.ru/[/url] .
karniz elektroprivodom shtor kypit_dfei
14 Oct 25 at 3:03 am
потолочник натяжные потолки отзывы [url=http://stretch-ceilings-samara.ru/]http://stretch-ceilings-samara.ru/[/url] .
natyajnie potolki samara_oukl
14 Oct 25 at 3:04 am
купить диплом о высшем с занесением в реестр [url=https://frei-diplom4.ru]купить диплом о высшем с занесением в реестр[/url] .
Diplomi_dgOl
14 Oct 25 at 3:04 am
куплю диплом цена [url=https://rudik-diplom7.ru]куплю диплом цена[/url] .
Diplomi_gmPl
14 Oct 25 at 3:05 am
купить диплом для иностранцев [url=http://www.rudik-diplom13.ru]купить диплом для иностранцев[/url] .
Diplomi_tfon
14 Oct 25 at 3:05 am
купить диплом о высшем образовании с занесением в реестр цены [url=https://frei-diplom2.ru]купить диплом о высшем образовании с занесением в реестр цены[/url] .
Diplomi_pfEa
14 Oct 25 at 3:06 am
купить диплом с занесением в реестр в спб [url=https://frei-diplom1.ru/]https://frei-diplom1.ru/[/url] .
Diplomi_ktOi
14 Oct 25 at 3:07 am
купил диплом легально [url=frei-diplom3.ru]купил диплом легально[/url] .
Diplomi_odKt
14 Oct 25 at 3:08 am
Scientists discovered something alarming seeping out from beneath the ocean around Antarctica
[url=https://otzovik.com/reviews/zhilischniy_kooperativ_best_way_russia_sankt-peterburg/]гей порно член[/url]
Planet-heating methane is escaping from cracks in the Antarctic seabed as the region warms, with new seeps being discovered at an “astonishing rate,” scientists have found, raising fears that future global warming predictions may have been underestimated.
Huge amounts of methane lie in reservoirs that have formed over millennia beneath the seafloor around the world. This invisible, climate-polluting gas can escape into the water through fissures in the sea floor, often revealing itself with a stream of bubbles weaving their way up to the ocean surface.
https://wap-tools.com/novosti/item/119517-gemcy-gem-cy-novaya-piramida-vasilenko
домашний анальный секс
Relatively little is known about these underwater seeps, how they work, how many there are, and how much methane reaches the atmosphere versus how much is eaten by methane-munching microbes living beneath the ocean.
But scientists are keen to better understand them, as this super-polluting gas traps around 80 times more heat than carbon dioxide in its first 20 years in the atmosphere.
Methane seeps in Antarctica are among the least understood on the planet, so a team of international scientists set out to find them. They used a combination of ship-based acoustic surveys, remotely operated vehicles and divers to sample a range of sites in the Ross Sea, a bay in Antarctica’s Southern Ocean, at depths between 16 and 790 feet.
What they found surprised them. They identified more than 40 methane seeps in the shallow water of the Ross Sea, according to the study published this month in Nature Communications.
Bubbles rising from a methane seep at Cape Evans, Antarctica. Leigh Tate, Earth Sciences New Zealand
Many of the seeps were found at sites that had been repeatedly studied before, suggesting they were new. This may indicate a “fundamental shift” in the methane released in the region, according to the report.
Methane seeps are relatively common globally, but previously there was only one confirmed active seep in the Antarctic, said Sarah Seabrook, a report author and a marine scientist at Earth Sciences New Zealand, a research organization. “Something that was thought to be rare is now seemingly becoming widespread,” she told CNN.
Every seep they discovered was accompanied by an “immediate excitement” that was “quickly replaced with anxiety and concern,” Seabrook said.
The fear is these seeps could rapidly transfer methane into the atmosphere, making them a source of planet-heating pollution that is not currently factored into future climate change predictions.
The scientists are also concerned the methane could have cascading impacts on marine life.
DonaldCix
14 Oct 25 at 3:10 am
купить диплом в чебоксарах [url=https://rudik-diplom10.ru]купить диплом в чебоксарах[/url] .
Diplomi_cpSa
14 Oct 25 at 3:12 am
рулонные шторы купить москва недорого [url=http://www.rulonnaya-shtora-s-elektroprivodom.ru]рулонные шторы купить москва недорого[/url] .
rylonnaya shtora s elektroprivodom_hpKt
14 Oct 25 at 3:12 am
диплом о среднем образовании купить легально [url=https://frei-diplom2.ru/]https://frei-diplom2.ru/[/url] .
Diplomi_ohEa
14 Oct 25 at 3:13 am
Форматы вывода из запоя в Пушкино
Исследовать вопрос подробнее – https://vyvod-iz-zapoya-pushkino7.ru/vyvod-iz-zapoya-kruglosutochno-v-pushkino
CharlesBoync
14 Oct 25 at 3:13 am
купить диплом в коврове [url=http://rudik-diplom4.ru/]купить диплом в коврове[/url] .
Diplomi_nlOr
14 Oct 25 at 3:14 am
Very nice article. I absolutely love this website.
Keep writing!
@SEO_LINKK
14 Oct 25 at 3:15 am
купить диплом с реестром цена [url=www.frei-diplom3.ru/]купить диплом с реестром цена[/url] .
Diplomi_nhKt
14 Oct 25 at 3:15 am
рулонные шторы на окна недорого [url=https://rulonnaya-shtora-s-elektroprivodom.ru/]рулонные шторы на окна недорого[/url] .
rylonnaya shtora s elektroprivodom_nnKt
14 Oct 25 at 3:16 am
I wanted to thank you for this good read!! I absolutely loved every little bit of it.
I’ve got you saved as a favorite to look at new things you post…
89BET
14 Oct 25 at 3:16 am
электрокарнизы москва [url=https://karniz-shtor-elektroprivodom.ru/]karniz-shtor-elektroprivodom.ru[/url] .
karniz dlya shtor s elektroprivodom_qper
14 Oct 25 at 3:16 am
карниз для штор с электроприводом [url=https://karniz-elektroprivodom.ru/]карниз для штор с электроприводом[/url] .
karniz elektroprivodom shtor kypit_yvei
14 Oct 25 at 3:16 am
как купить проведенный диплом отзывы [url=https://frei-diplom3.ru]https://frei-diplom3.ru[/url] .
Diplomi_poKt
14 Oct 25 at 3:19 am
как купить проведенный диплом отзывы [url=http://frei-diplom1.ru]http://frei-diplom1.ru[/url] .
Diplomi_gxOi
14 Oct 25 at 3:22 am
купить диплом в тамбове [url=https://www.rudik-diplom3.ru]купить диплом в тамбове[/url] .
Diplomi_hzei
14 Oct 25 at 3:23 am
натяжные потолки цена самара [url=https://www.stretch-ceilings-samara.ru]https://www.stretch-ceilings-samara.ru[/url] .
natyajnie potolki samara_tckl
14 Oct 25 at 3:24 am
тканевый натяжной потолок самара [url=www.natyazhnye-potolki-samara-1.ru/]www.natyazhnye-potolki-samara-1.ru/[/url] .
natyajnie potolki samara_mlor
14 Oct 25 at 3:25 am
электрокарниз [url=https://karniz-shtor-elektroprivodom.ru]электрокарниз[/url] .
karniz dlya shtor s elektroprivodom_qcer
14 Oct 25 at 3:25 am
рулонные шторы на пластиковые окна на кухню [url=rulonnaya-shtora-s-elektroprivodom.ru]рулонные шторы на пластиковые окна на кухню[/url] .
rylonnaya shtora s elektroprivodom_paKt
14 Oct 25 at 3:26 am