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=http://soglasovanie-pereplanirovki-kvartiry14.ru/]http://soglasovanie-pereplanirovki-kvartiry14.ru/[/url] .
soglasovanie pereplanirovki kvartiri _xpEl
18 Oct 25 at 9:50 pm
If you are going for most excellent contents like I do,
simply pay a quick visit this web page daily because it offers feature contents, thanks
betflix 199
18 Oct 25 at 9:51 pm
Компьютеры становятся умнее людей kraken рабочая ссылка onion кракен darknet кракен onion кракен ссылка onion
RichardPep
18 Oct 25 at 9:52 pm
rankseed.click – Overall, the experience is solid and gives a trustworthy first impression.
Lewis Nole
18 Oct 25 at 9:53 pm
I simply could not leave your website before suggesting that I extremely enjoyed the standard information an individual supply in your guests?
Is going to be back frequently to inspect new posts
برلیانس H320 بخریم؟ یا نه؟!
18 Oct 25 at 9:54 pm
мелбет официальный сайт [url=http://melbetbonusy.ru]мелбет официальный сайт[/url] .
melbet_gmOi
18 Oct 25 at 9:54 pm
Howdy this is kinda of off topic but I was wondering if blogs use WYSIWYG editors or if you have to manually
code with HTML. I’m starting a blog soon but have no coding experience so I
wanted to get guidance from someone with experience. Any help would be enormously appreciated!
best online casinos for real money
18 Oct 25 at 9:55 pm
купить диплом в курске [url=http://rudik-diplom13.ru]купить диплом в курске[/url] .
Diplomi_cnon
18 Oct 25 at 9:56 pm
перепланировка и согласование [url=http://soglasovanie-pereplanirovki-kvartiry11.ru]http://soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _jqMi
18 Oct 25 at 9:57 pm
Светодиодные экраны в нашем офисе теперь используются не только для презентаций, но и для трансляции корпоративных новостей
https://securityholes.science/wiki/User:SQKCruz0588772
https://ai-db.science/wiki/User:LidaEichelberger
18 Oct 25 at 9:57 pm
Для устойчивого отказа от вредных привычек применяется кодирование — метод, основанный на психологическом воздействии, а также заместительная терапия, при которой пациент получает контролируемые дозы препаратов, снижающих ломку и тягу.
Углубиться в тему – [url=https://narkologicheskaya-klinika-mariupol13.ru/]наркологическая клиника лечение алкоголизма в мариуполе[/url]
Gilbertnup
18 Oct 25 at 9:57 pm
You actually make it appear so easy along with your presentation however I in finding this topic to be actually something which I believe I would never understand.
It seems too complicated and very extensive for me.
I’m having a look forward for your subsequent submit, I will attempt to get the dangle of it!
طراحی سایت اردبیل
18 Oct 25 at 9:58 pm
Bonus exclusif 1xBet pour 2026 : profitez d’un bonus de bienvenue de 100% jusqu’a 130€ lors de votre inscription. Une promotion reservee aux nouveaux joueurs de paris sportifs, permettant d’effectuer des paris sans risque. N’attendez pas la fin de l’annee 2026 pour profiter de cette offre. Vous pouvez retrouver le code promo 1xBet sur ce lien — https://ville-barentin.fr/wp-content/pgs/code-promo-bonus-1xbet.html.
Ernestpak
18 Oct 25 at 10:00 pm
Asking questions are genuinely pleasant thing if you
are not understanding anything totally, except
this piece of writing presents fastidious understanding
yet.
https://kim88.ru.com/
18 Oct 25 at 10:00 pm
What a information of un-ambiguity and preserveness of valuable
familiarity concerning unexpected emotions.
sildenafilctabs.com
18 Oct 25 at 10:01 pm
I was recommended this blog by my cousin. I am not sure whether this post is
written by him as nobody else know such detailed about my trouble.
You’re wonderful! Thanks!
paris sportif mma
18 Oct 25 at 10:01 pm
кракен маркетплейс
кракен вход
JamesDaync
18 Oct 25 at 10:03 pm
перепланировка под ключ стоимость [url=http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]http://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_lgPt
18 Oct 25 at 10:04 pm
стоимость согласования перепланировки в бти [url=http://zakazat-proekt-pereplanirovki-kvartiry11.ru]http://zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .
zakazat proekt pereplanirovki kvartiri_vmet
18 Oct 25 at 10:04 pm
проект перепланировки для согласования [url=http://www.proekt-pereplanirovki-kvartiry17.ru]http://www.proekt-pereplanirovki-kvartiry17.ru[/url] .
proekt pereplanirovki kvartiri_yvml
18 Oct 25 at 10:05 pm
Hi to all, the contents present at this web page are truly remarkable for people experience,
well, keep up the nice work fellows.
игры на реальные деньги без депозитов
18 Oct 25 at 10:05 pm
Откройте для себя прекрасные и загадочные места, которые находятся под охраной в нашей стране.
Для тех, кто ищет информацию по теме “Изучение ООПТ России: парки, заповедники, водоемы”, нашел много полезного.
Вот, можете почитать:
[url=https://alloopt.ru]https://alloopt.ru[/url]
Спасибо за внимание! Надеюсь, вам было интересно.
fixRow
18 Oct 25 at 10:05 pm
прогноз на футбол [url=https://prognozy-na-futbol-10.ru/]прогноз на футбол[/url] .
prognozi na fytbol_qwOi
18 Oct 25 at 10:07 pm
Pretty! This has been an incredibly wonderful article.
Many thanks for providing these details.
personal injury attorney
18 Oct 25 at 10:08 pm
Spinrise Casino
Angelolix
18 Oct 25 at 10:08 pm
http://pilloleverdi.com/# cialis generico
MickeySum
18 Oct 25 at 10:09 pm
услуги по узакониванию перепланировки [url=http://soglasovanie-pereplanirovki-kvartiry11.ru/]http://soglasovanie-pereplanirovki-kvartiry11.ru/[/url] .
soglasovanie pereplanirovki kvartiri _gcMi
18 Oct 25 at 10:09 pm
где согласовать перепланировку квартиры [url=http://www.soglasovanie-pereplanirovki-kvartiry14.ru]http://www.soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _cbEl
18 Oct 25 at 10:09 pm
согласование проекта перепланировки квартиры [url=http://soglasovanie-pereplanirovki-kvartiry4.ru]согласование проекта перепланировки квартиры[/url] .
soglasovanie pereplanirovki kvartiri _nkOr
18 Oct 25 at 10:09 pm
Без обновлений программ жить опасно kraken зеркало кракен darknet кракен onion кракен ссылка onion
RichardPep
18 Oct 25 at 10:10 pm
заказ перепланировки квартиры [url=https://www.proekt-pereplanirovki-kvartiry17.ru]https://www.proekt-pereplanirovki-kvartiry17.ru[/url] .
proekt pereplanirovki kvartiri_ynml
18 Oct 25 at 10:11 pm
What is mirror life? Scientists are sounding the alarm
https://www.advokates.in.ua/index.php/ru/uslugi-advokata/voennye-dela
Военный адвокат Запорожье
[img]https://advokats-zp.com.ua/wp-content/uploads/elementor/thumbs/-%D0%90%D0%B4%D0%B2%D0%BE%D0%BA%D0%B0%D1%82-%D0%97%D0%B0%D0%BF%D0%BE%D1%80%D0%BE%D0%B6%D1%8C%D0%B50-q192m9gvadjaqpcva0ygofm8b12rvh26ax5bujpc9s.webp[/img]
[url=https://www.instagram.com/p/DMXc_pPMmra/]Военный адвокат Запорожье[/url]
Scientist Kate Adamala doesn’t remember exactly when she realized her lab at the University of Minnesota was working on something potentially dangerous — so dangerous in fact that some researchers think it could pose an existential risk to all life forms on Earth.
She was one of four researchers awarded a $4 million US National Science Foundation grant in 2019 to investigate whether it’s possible to produce a mirror cell, in which the structure of all of its component biomolecules is the reverse of what’s found in normal cells.
The work was important, they thought, because such reversed cells, which have never existed in nature, could shed light on the origins of life and make it easier to create molecules with therapeutic value, potentially tackling significant medical challenges such as infectious disease and superbugs. But doubt crept in.
“It was never one light bulb moment. It was kind of a slow boiling over a few months,” Adamala, a synthetic biologist, said. People started asking questions, she added, “and we thought we can answer them, and then we realized we cannot.”
The questions hinged on what would happen if scientists succeeded in making a “mirror organism” such as a bacterium from molecules that are the mirror images of their natural forms. Could it inadvertently spread unchecked in the body or an environment, posing grave risks to human health and dire consequences for the planet? Or would it merely fizzle out and harmlessly disappear without a trace?
Donaldutist
18 Oct 25 at 10:11 pm
перепланировка офиса [url=www.soglasovanie-pereplanirovki-kvartiry3.ru]www.soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _wdPi
18 Oct 25 at 10:11 pm
перепланировка офиса [url=https://www.soglasovanie-pereplanirovki-kvartiry3.ru]https://www.soglasovanie-pereplanirovki-kvartiry3.ru[/url] .
soglasovanie pereplanirovki kvartiri _ofPi
18 Oct 25 at 10:15 pm
Spinrise Casino
Angelolix
18 Oct 25 at 10:15 pm
sichere wetten heute kostenlos
sichere wetten heute
18 Oct 25 at 10:15 pm
melbet официальный сайт зеркало [url=https://melbetbonusy.ru/]melbet официальный сайт зеркало[/url] .
melbet_tlOi
18 Oct 25 at 10:17 pm
1xbet cameroun apk melbet telecharger
parifoot-429
18 Oct 25 at 10:17 pm
Играть бесплатно в Лев казино — это
так просто и удобно!
игровой автомат Fortuneer
игровой автомат Fortuneer
18 Oct 25 at 10:18 pm
соглосование [url=www.soglasovanie-pereplanirovki-kvartiry11.ru]www.soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _wfMi
18 Oct 25 at 10:19 pm
https://www.bergkompressor.ru Загляните на наш сайт – Узнайте последние новости и обновления первыми.
Jeremyjoync
18 Oct 25 at 10:21 pm
согласованте [url=http://soglasovanie-pereplanirovki-kvartiry11.ru]http://soglasovanie-pereplanirovki-kvartiry11.ru[/url] .
soglasovanie pereplanirovki kvartiri _sjMi
18 Oct 25 at 10:21 pm
You really make it appear so easy with your presentation but
I to find this matter to be really something that I think I might never understand.
It kind of feels too complex and very large for me.
I am looking forward to your next submit, I’ll try to get the dangle of it!
mellstroy casino
18 Oct 25 at 10:21 pm
оформление перепланировки квартиры в москве стоимость [url=stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .
stoimost soglasovaniya pereplanirovki kvartiri_pwPt
18 Oct 25 at 10:22 pm
купить аттестаты за 11 [url=http://rudik-diplom13.ru]купить аттестаты за 11[/url] .
Diplomi_upon
18 Oct 25 at 10:22 pm
kraken зеркало
kraken onion
JamesDaync
18 Oct 25 at 10:23 pm
согласование [url=http://soglasovanie-pereplanirovki-kvartiry4.ru/]согласование[/url] .
soglasovanie pereplanirovki kvartiri _fiOr
18 Oct 25 at 10:24 pm
перепланировка офиса [url=http://www.soglasovanie-pereplanirovki-kvartiry14.ru]http://www.soglasovanie-pereplanirovki-kvartiry14.ru[/url] .
soglasovanie pereplanirovki kvartiri _sdEl
18 Oct 25 at 10:27 pm
где согласовать перепланировку квартиры [url=www.soglasovanie-pereplanirovki-kvartiry11.ru/]www.soglasovanie-pereplanirovki-kvartiry11.ru/[/url] .
soglasovanie pereplanirovki kvartiri _imMi
18 Oct 25 at 10:28 pm
Snapped up $MTAUR in presale; price to 0.00012 next stage urges action. In-game currency edges gameplay. Team’s data-driven marketing wins.
minotaurus coin
WilliamPargy
18 Oct 25 at 10:30 pm