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!
I’ve been browsing online more than 3 hours today, yet I never found any interesting
article like yours. It’s pretty worth enough for me.
In my opinion, if all website owners and bloggers made good content as you did, the web
will be a lot more useful than ever before.
PINK SALT TRICK
3 Oct 25 at 11:33 pm
купить диплом в белгороде [url=https://rudik-diplom2.ru/]купить диплом в белгороде[/url] .
Diplomi_eipi
3 Oct 25 at 11:35 pm
купить диплом в комсомольске-на-амуре [url=http://rudik-diplom3.ru/]купить диплом в комсомольске-на-амуре[/url] .
Diplomi_yuei
3 Oct 25 at 11:35 pm
Very nice post. I just stumbled upon your blog and wanted to say that I’ve really enjoyed browsing your blog posts.
After all I’ll be subscribing to your rss feed and I hope
you write again very soon!
персональное обучение
3 Oct 25 at 11:37 pm
диплом с реестром купить [url=www.frei-diplom2.ru]диплом с реестром купить[/url] .
Diplomi_bdEa
3 Oct 25 at 11:37 pm
легально купить диплом [url=https://www.frei-diplom1.ru]легально купить диплом[/url] .
Diplomi_noOi
3 Oct 25 at 11:38 pm
You can certainly see your enthusiasm within the work you write.
The world hopes for more passionate writers such as you who aren’t afraid to say
how they believe. Always follow your heart.
68 game bai
3 Oct 25 at 11:39 pm
OMT’ѕ focus on error evaluation transforms errors іnto finding oᥙt
journeys, aiding trainees fall for math’s flexible
nature аnd objective high in examinations.
Experience versatile knowing anytime, аnywhere through OMT’s extensive online е-learning platform, including unrestricted access tߋ
video lessons ɑnd interactive tests.
Singapore’s focus ⲟn critical analyzing mathematics highlights tһe impoгtance ⲟf math tuition, ԝhich assists students establish tһe analyticxal
skills demanded Ƅʏ thе nation’ѕ forward-thinking curriculum.
Ultimately, primary school math tuition іs imрortant for PSLE excellence,
аs it gears ᥙp students wіtһ the tools t᧐ attain toρ bands аnd protect preferred secondary school placements.
Comprehensive protection ߋf thе whole O Level syllabus in tuition mɑkes certain no subjects,
frߋm sets tо vectors, агe neglected in a trainee’ѕ
alteration.
Attending to individual understanding designs, math tuition mɑkes ⅽertain junior college students grasp topics ɑt their own pace fοr A Level success.
OMT’ѕ personalized curriculum uniquely lines սp with MOE framework by providing
linking components fоr smooth chаnges betweеn primary, secondary, and JC mathematics.
Parental accessibility tο advance reports ߋne, allowing support іn the house fⲟr
continual grade enhancement.
Singapore’ѕ incorporated math curriculum tɑke advantage ᧐f tuition thɑt attaches topics
thгoughout degrees fоr natural test preparedness.
Feel free tⲟ visit mу webpage; secondary 1 math tuition
secondary 1 math tuition
3 Oct 25 at 11:41 pm
What’s Happening i’m new to this, I stumbled upon this I’ve discovered
It absolutely useful and it has helped me out loads. I hope to
contribute & help different customers like its aided me.
Good job.
Stäbel Gainetra
3 Oct 25 at 11:41 pm
Minotaurus token’s security priority wins trust. Presale’s low min buy accessible. Battles engaging.
mtaur token
WilliamPargy
3 Oct 25 at 11:42 pm
Каждый пациент проходит три основные стадии терапии, начиная с момента первого обращения.
Разобраться лучше – [url=https://narkologicheskaya-klinika-ufa9.ru/]частная наркологическая клиника[/url]
Mariofep
3 Oct 25 at 11:42 pm
купить диплом о высшем образовании легально [url=frei-diplom3.ru]купить диплом о высшем образовании легально[/url] .
Diplomi_ihKt
3 Oct 25 at 11:43 pm
Врач устанавливает внутривенную капельницу, через которую вводятся специально подобранные препараты для очищения организма от алкоголя, восстановления баланса жидкости и нормализации работы всех органов и систем. В течение всей процедуры специалист следит за состоянием пациента и, при необходимости, корректирует терапию.
Узнать больше – [url=https://kapelnica-ot-zapoya-sochi00.ru/]капельницы от запоя на дому цена[/url]
VictorApevy
3 Oct 25 at 11:43 pm
купить диплом в комсомольске-на-амуре [url=www.rudik-diplom2.ru]купить диплом в комсомольске-на-амуре[/url] .
Diplomi_qjpi
3 Oct 25 at 11:43 pm
купить диплом моряка [url=http://rudik-diplom1.ru]купить диплом моряка[/url] .
Diplomi_iwer
3 Oct 25 at 11:44 pm
можно ли купить диплом в реестре [url=http://www.frei-diplom2.ru]можно ли купить диплом в реестре[/url] .
Diplomi_lbEa
3 Oct 25 at 11:45 pm
купить диплом в мурманске [url=rudik-diplom10.ru]купить диплом в мурманске[/url] .
Diplomi_ofSa
3 Oct 25 at 11:49 pm
Buy Tadalafil 20mg: tadalafil – buy tadalafil online paypal
MartinJaive
3 Oct 25 at 11:49 pm
диплом купить с проводкой [url=http://frei-diplom3.ru/]диплом купить с проводкой[/url] .
Diplomi_tqKt
3 Oct 25 at 11:50 pm
купить диплом с реестром киев [url=https://frei-diplom2.ru/]https://frei-diplom2.ru/[/url] .
Diplomi_ljEa
3 Oct 25 at 11:50 pm
диплом педагогического колледжа купить [url=http://www.frei-diplom8.ru]http://www.frei-diplom8.ru[/url] .
Diplomi_sssr
3 Oct 25 at 11:51 pm
Michelle Pfeiffer shares she’s now a grandmother
[url=https://m-bs2web-at.ru/m-bs2web-at]m bs2best at[/url]
Hollywood star Michelle Pfeiffer has announced that she has become a grandmother, and spoken about how it has affected her working life.
Speaking on the “Smartless” podcast on Monday, three-time Oscar nominee Pfeiffer told hosts Jason Bateman, Sean Hayes and Will Arnett that having a grandchild was “heaven.”
“I’ve been very quiet about it and it is – it’s heaven. It’s ridiculous,” said Pfeiffer, 67, who has an adopted daughter Claudia Rose and a son named John Henry.
“And if I had known that I was going to be a grandmother, I wouldn’t have taken on so much work, but I’ve enjoyed everything and I’m really grateful,” she said.
https://bc01.ru/
bs2best at
“I love each of these projects,” said Pfeiffer, referencing her recent work on projects including “Yellowstone” spin-off series “The Madison” on Paramount+, Christmas comedy “Oh. What. Fun” and the TV adaptation of Rufi Thorpe’s novel “Margo’s Got Money Troubles.”
“I’m so grateful. I’m so grateful because I love acting… in fact, I probably, enjoy it more now than I ever have because I’m sort of more relaxed with it,” said Pfeiffer.
The Hollywood star has had a long and storied career both in movies and on TV, including appearances in “Scarface” (1983), “Batman Returns” (1992) and Showtime series “The First Lady” (2022).
“I don’t really have time to be thinking about anything but the task at hand,” she said, highlighting the fact that she also set up a fragrance company a few years ago.
Related article
LOS ANGELES, CALIFORNIA – APRIL 14: Michelle Pfeiffer arrives at Showtime’s FYC event and premiere for ‘The First Lady’ at DGA Theater Complex on April 14, 2022 in Los Angeles, California. (Photo by Emma McIntyre/WireImage)
Michelle Pfeiffer would consider playing Catwoman again
“But when I had all these acting jobs coming up, I thought, ‘Okay, okay, how are you going to manage this and have a life?’ Because that hasn’t always been easy for me. I’m an all or nothing kind of girl,” added Pfeiffer.
“I always like taking on challenges and then I get into it and it’s sort of sink or swim and for whatever reason I kind of feed on that,” she said, before going on to suggest that her priorities have shifted recently.
“I don’t have the time nor the desire to go that deep for that long and not be present,” said Pfeiffer.
GregoryHob
3 Oct 25 at 11:52 pm
купить диплом в усолье-сибирском [url=rudik-diplom3.ru]купить диплом в усолье-сибирском[/url] .
Diplomi_uyei
3 Oct 25 at 11:52 pm
https://barcelona-stylist.ru
PatrickGop
3 Oct 25 at 11:52 pm
I’m not sure where you are getting your information,
but great topic. I needs to spend some time learning much
more or understanding more. Thanks for excellent info I was looking for this information for my mission.
CASAS CONTENEDORES: FOTOS Y MODELOS EN PR
3 Oct 25 at 11:53 pm
The hype around $MTAUR presale is justified—over 1M USDT in days. Unlocking boosts and outfits with tokens adds depth to gameplay. This is crypto meeting casual gaming perfectly.
mtaur token
WilliamPargy
3 Oct 25 at 11:54 pm
купить диплом в перми [url=https://rudik-diplom2.ru]купить диплом в перми[/url] .
Diplomi_vlpi
3 Oct 25 at 11:54 pm
купить диплом легальный [url=https://frei-diplom3.ru/]купить диплом легальный[/url] .
Diplomi_maKt
3 Oct 25 at 11:54 pm
My partner and I stumbled over here different page and thought I may as well check
things out. I like what I see so now i’m
following you. Look forward to finding out about your web page yet again.
fairly well
3 Oct 25 at 11:55 pm
Cabnet IQ Austin
2419 Ѕ Bell Blvd, Cedar Park,
TX 78613, United Տtates
+12543183528
Projectservice
Projectservice
3 Oct 25 at 11:56 pm
Экономия до 50% при аренде VPS в Нидерландах http://grot.getbb.ru/viewtopic.php?f=24&t=3938
http://grot.getbb.ru/viewtopic.php?f=24&t=3938
3 Oct 25 at 11:56 pm
Купить диплом техникума в Николаев [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .
Diplomi_qnea
3 Oct 25 at 11:57 pm
купить диплом в курске [url=http://rudik-diplom11.ru]купить диплом в курске[/url] .
Diplomi_ncMi
3 Oct 25 at 11:59 pm
купить речной диплом [url=http://rudik-diplom1.ru]купить речной диплом[/url] .
Diplomi_xser
3 Oct 25 at 11:59 pm
купить диплом хореографа [url=www.rudik-diplom3.ru]купить диплом хореографа[/url] .
Diplomi_ccei
4 Oct 25 at 12:00 am
хоккей прогноз сегодня [url=prognozy-na-khokkej4.ru]prognozy-na-khokkej4.ru[/url] .
prognozi na hokkei_lvOl
4 Oct 25 at 12:01 am
유흥알바는 술집, 클럽, 노래방 등 유흥업소에서
하는 다양한 아르바이트를 통칭합니다. 주로 야간에
이뤄지며 룸알바, 밤알바, 여성알바 등 여러 이름으로 불립니다.
유흥알바
4 Oct 25 at 12:01 am
It is appropriate time to make some plans for the future and
it’s time to be happy. I’ve read this publish and if I could I wish to suggest you few fascinating things or suggestions.
Maybe you can write next articles relating to this article.
I want to read more issues about it!
Redwood Fundrelix
4 Oct 25 at 12:02 am
Diese Homepage ist eine der wertvollsten, die ich je gesehen habe.
Coolste CleanAlpin Services
4 Oct 25 at 12:03 am
Michelle Pfeiffer shares she’s now a grandmother
[url=https://m-bs2web-at.shop/bs2web.at]bs2web at[/url]
Hollywood star Michelle Pfeiffer has announced that she has become a grandmother, and spoken about how it has affected her working life.
Speaking on the “Smartless” podcast on Monday, three-time Oscar nominee Pfeiffer told hosts Jason Bateman, Sean Hayes and Will Arnett that having a grandchild was “heaven.”
“I’ve been very quiet about it and it is – it’s heaven. It’s ridiculous,” said Pfeiffer, 67, who has an adopted daughter Claudia Rose and a son named John Henry.
“And if I had known that I was going to be a grandmother, I wouldn’t have taken on so much work, but I’ve enjoyed everything and I’m really grateful,” she said.
https://m-bs2web-at.shop/bs2web.at
bs2web at
“I love each of these projects,” said Pfeiffer, referencing her recent work on projects including “Yellowstone” spin-off series “The Madison” on Paramount+, Christmas comedy “Oh. What. Fun” and the TV adaptation of Rufi Thorpe’s novel “Margo’s Got Money Troubles.”
“I’m so grateful. I’m so grateful because I love acting… in fact, I probably, enjoy it more now than I ever have because I’m sort of more relaxed with it,” said Pfeiffer.
The Hollywood star has had a long and storied career both in movies and on TV, including appearances in “Scarface” (1983), “Batman Returns” (1992) and Showtime series “The First Lady” (2022).
“I don’t really have time to be thinking about anything but the task at hand,” she said, highlighting the fact that she also set up a fragrance company a few years ago.
Related article
LOS ANGELES, CALIFORNIA – APRIL 14: Michelle Pfeiffer arrives at Showtime’s FYC event and premiere for ‘The First Lady’ at DGA Theater Complex on April 14, 2022 in Los Angeles, California. (Photo by Emma McIntyre/WireImage)
Michelle Pfeiffer would consider playing Catwoman again
“But when I had all these acting jobs coming up, I thought, ‘Okay, okay, how are you going to manage this and have a life?’ Because that hasn’t always been easy for me. I’m an all or nothing kind of girl,” added Pfeiffer.
“I always like taking on challenges and then I get into it and it’s sort of sink or swim and for whatever reason I kind of feed on that,” she said, before going on to suggest that her priorities have shifted recently.
“I don’t have the time nor the desire to go that deep for that long and not be present,” said Pfeiffer.
Michaelanymn
4 Oct 25 at 12:03 am
Капельницы при запое, это важный этап в лечении алкоголизма. Вызов нарколога на дом в владимире позволяет получить профессиональную медицинскую помощь. При симптомах запоя, таких как тремор, потливость и беспокойство, важно незамедлительно получить помощь. Наркологи проводят диагностику алкоголизма и назначают медикаментозное лечение алкоголизма, включая капельницы для выведения токсинов. вызов нарколога на дом владимир Восстановление после запоя включает семейную поддержку, что значительно увеличивает шансы на эффективное лечение. Профилактика алкогольной зависимости тоже играет ключевую роль. Услуги нарколога, включая вызов врача на дом, помогают решить проблемы, связанные с алкогольной зависимостью, и гарантировать безопасную терапию.
zapojvladimirNeT
4 Oct 25 at 12:03 am
купить диплом электромонтера [url=https://rudik-diplom10.ru]купить диплом электромонтера[/url] .
Diplomi_rvSa
4 Oct 25 at 12:04 am
Mexican pharmacy price list: MedicExpress MX – Mexican pharmacy price list
BruceMaivy
4 Oct 25 at 12:04 am
диплом техникума купить цены [url=http://www.frei-diplom8.ru]диплом техникума купить цены[/url] .
Diplomi_musr
4 Oct 25 at 12:04 am
В Кухни в Дом заказали кухню на заказ для семьи из пяти человек. Проект был тщательно продуман, чтобы у каждого было удобно готовить и хранить продукты. Кухня получилась просторной и уютной, https://kuhni-v-dom.ru/
Eugeniostync
4 Oct 25 at 12:06 am
Купить диплом техникума в Запорожье [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_esea
4 Oct 25 at 12:07 am
диплом колледжа купить с занесением в реестр [url=www.frei-diplom2.ru/]диплом колледжа купить с занесением в реестр[/url] .
Diplomi_szEa
4 Oct 25 at 12:08 am
Когда подходит
Подробнее можно узнать тут – [url=https://narkologicheskaya-klinika-lyubercy0.ru/]narkologicheskaya-klinika-stacionar[/url]
Jorgesmusy
4 Oct 25 at 12:09 am
где купить диплом техникума в екатеринбурге [url=http://frei-diplom9.ru/]где купить диплом техникума в екатеринбурге[/url] .
Diplomi_qaea
4 Oct 25 at 12:10 am
купить диплом в междуреченске [url=https://rudik-diplom3.ru/]https://rudik-diplom3.ru/[/url] .
Diplomi_yuei
4 Oct 25 at 12:12 am