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://www.arenda-ekskavatora-pogruzchika-cena-2.ru]экскаватор погрузчик аренда москва[/url] .
arenda ekskavatora pogryzchika cena_mmst
14 Oct 25 at 9:09 am
алюминиевые электрожалюзи [url=https://www.zhalyuzi-s-elektroprivodom77.ru]https://www.zhalyuzi-s-elektroprivodom77.ru[/url] .
jaluzi na okna s elektroprivodom_kwpa
14 Oct 25 at 9:09 am
Tulisan ini sangat informatif! Penjelasan mengenai Situs Judi Bola, Situs Parlay
Gacor, dan situs parlay terasa lengkap dan padat.
Penulis juga mampu mengangkat KUBET dengan gaya bahasa yang ringan namun tetap profesional.
Ditambah lagi, informasi tentang toto macau
dan kubet login menjadikan artikel ini lebih berwarna dan tidak monoton.
Situs Mix Parlay
14 Oct 25 at 9:09 am
купить диплом повара-кондитера [url=http://www.rudik-diplom5.ru]купить диплом повара-кондитера[/url] .
Diplomi_nrma
14 Oct 25 at 9:10 am
карниз электроприводом штор купить [url=http://karniz-shtor-elektroprivodom.ru/]http://karniz-shtor-elektroprivodom.ru/[/url] .
karniz dlya shtor s elektroprivodom_wmer
14 Oct 25 at 9:12 am
В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
Откройте для себя больше – https://efectofuzz.com/el-sentimiento-fuzz
JerryHoach
14 Oct 25 at 9:12 am
карниз моторизованный [url=https://www.elektrokarnizy797.ru]https://www.elektrokarnizy797.ru[/url] .
elektrokarnizi_uuMl
14 Oct 25 at 9:12 am
Admiring the persistence you put into your website and detailed information you present.
It’s nice to come across a blog every once in a while that isn’t the same out of dzte rehashed material.
Excellent read! I’ve saved your site and I’m addinhg your RSS feeds to mmy Google account.
Have a look at my site :: JetBlack
JetBlack
14 Oct 25 at 9:13 am
купить диплом техникума с реестром [url=frei-diplom6.ru]купить диплом техникума с реестром[/url] .
Diplomi_rvOl
14 Oct 25 at 9:13 am
Мы предлагаем вам окунуться в океан любопытных фактов и вдохновляющих историй. Эта публикация поможет расширить горизонты, разбудить интерес к науке и истории и увидеть мир с новой стороны.
А что дальше? – http://stitcheryprojects.com/forums/topic/%D1%81%D1%82%D0%B0%D1%82%D1%8C%D1%8F-%D0%BE-%D0%B2%D0%BE%D1%81%D1%81%D1%82%D0%B0%D0%BD%D0%BE%D0%B2%D0%BB%D0%B5%D0%BD%D0%B8%D0%B8-%D0%BF%D0%BE%D1%81%D0%BB%D0%B5-%D0%B7%D0%B0%D0%B2%D0%B8%D1%81%D0%B8
ThomasFep
14 Oct 25 at 9:13 am
https://www.imdb.com/list/ls4155615607/
brhvhan
14 Oct 25 at 9:14 am
You actually make it appear so easy together
with your presentation however I in finding this matter to be really one thing which I believe I’d by no means understand.
It seems too complex and extremely broad for me.
I’m having a look ahead to your subsequent publish, I will try to get the cling of it!
Bergkraft Fluxor Erfahrungen
14 Oct 25 at 9:15 am
The trial of Bryan Kohberger – the man who brutally murdered four University of Idaho students inside their off-campus home – ended in July before it ever truly began when he accepted a plea deal that saw him sentenced to four consecutive life terms in prison without the possibility of an appeal or parole.
Kohberger sat impassively throughout the hearing as the loved ones of each of the four students whose lives he so callously ended repeatedly asked him the same question: Why?
[url=http://trip-skan45.cc]трипскан вход[/url]
And when he was finally given the opportunity to answer their questions, he said, “I respectfully decline.”
That decision further fueled the mystery around his motive for murdering Xana Kernodle, Madison Mogen, Ethan Chapin and Kaylee Goncalves.
“There’s no reason for these crimes that could approach anything resembling rationality,” Idaho District Judge Steven Hippler said during Kohberger’s sentencing. “The more we try to extract a reason, the more power and control we give to him.”
But, he added, investigators and researchers may wish to study his actions – if only to learn how to prevent similar crimes from occurring in the future.
http://trip-skan45.cc
трипскан
Indeed, academics and former FBI profilers told CNN the challenge of unravelling the criminal mind of a man like Bryan Kohberger is enticing. And while his trial may be over, in many ways, the story of what can be learned from his crimes may have only just begun.
“We want to squeeze any silver lining that we can out of these tragedies,” said Molly Amman, a retired profiler who spent years leading the FBI’s Behavioral Threat Assessment Center.
“The silver lining is anything we can use to prevent another crime. It starts with learning absolutely, positively everything about the person and the crime that we possibly can.”
CNN
Only Kohberger knows
Even seasoned police officers who arrived at 1122 King Road on November 13, 2022, struggled to process the brutality of the crime scene.
All four victims had been ruthlessly stabbed to death before the attacker vanished through the kitchen’s sliding glass door and into the night.
“The female lying on the left half of the bed … was unrecognizable,” one officer would later write of the attack that killed Kaylee Goncalves. “I was unable to comprehend exactly what I was looking at while trying to discern the nature of the injuries.”
Initial interviews with the two surviving housemates gave investigators a loose timeline and a general description of the killer – an athletic, White male who wore a mask that covered most of his face – but little else.
Police later found a Ka-Bar knife sheath next to Madison’s body that would prove to be critical in capturing her killer.
One of the surviving housemates told police about a month before the attacks, Kaylee saw “a dark figure staring at her from the tree line when she took her dog Murphy out to pee.”
“There has been lighthearted talk and jokes made about a stalker in the past,” the officer noted. “All the girls were slightly nervous about it being a fact, though.”
But after years of investigating the murders, detectives told CNN they were never able to establish a connection between Kohberger and any of the victims, or a motive.
Kohberger is far from the first killer to deny families and survivors the catharsis that comes with confessing, in detail, to his crimes. But that, former FBI profilers tell CNN, is part of what makes the prospect of studying him infuriating and intriguing.
Wesleyzep
14 Oct 25 at 9:15 am
карниз с приводом для штор [url=www.karniz-shtor-elektroprivodom.ru]www.karniz-shtor-elektroprivodom.ru[/url] .
karniz dlya shtor s elektroprivodom_xler
14 Oct 25 at 9:16 am
купить диплом в майкопе [url=rudik-diplom5.ru]rudik-diplom5.ru[/url] .
Diplomi_jnma
14 Oct 25 at 9:16 am