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!
рейтинг площадок накрутки 2025
Robertexart
2 Sep 25 at 6:03 am
Je suis fan de le casino TonyBet, ca offre une aventure palpitante. Il y a une tonne de jeux differents, offrant des options de casino en direct. Le support est toujours la, avec des reponses claires. Le processus de retrait est efficace, neanmoins j’aimerais plus de bonus. En resume, TonyBet ne decoit pas pour les joueurs passionnes ! En bonus, le design est attractif, renforcant le plaisir de jouer.
tonybet bonusbedingungen|
Abobus4zef
2 Sep 25 at 6:03 am
где купить аттестат о среднем образовании [url=educ-ua5.ru]где купить аттестат о среднем образовании[/url] .
Diplomi_ciKl
2 Sep 25 at 6:05 am
Keep on working, great job!
رشته های تاپ گروه ریاضی
2 Sep 25 at 6:06 am
кашпо для цветов напольное пластик [url=http://kashpo-napolnoe-krasnodar.ru/]кашпо для цветов напольное пластик[/url] .
kashpo napolnoe _urma
2 Sep 25 at 6:06 am
купить дубликат аттестата за 11 класс [url=https://www.arus-diplom23.ru]https://www.arus-diplom23.ru[/url] .
Diplomi_cySr
2 Sep 25 at 6:08 am
https://postheaven.net/viliagupvb/how-contractors-can-boost-reputation-through-national-rankings
Every homeowner dreams of having a high-quality countertop that elevates their kitchen or bathroom.
Did you know that in the latest ranking, only just a fraction companies earned a spot in the Top Countertop Contractors Ranking out of over ten thousand evaluated? That’s because at we only recognize excellence.
Our ranking is independent, updated regularly, and built on more than 20 criteria. These include reviews from Google, Yelp, and other platforms, pricing, customer service, and craftsmanship. On top of that, we conduct 5,000+ phone calls and over two thousand estimate requests through our mystery shopper program.
The result is a standard that benefits both homeowners and fabricators. Homeowners get a safe way to choose contractors, while listed companies gain recognition, SEO visibility, and even new business opportunities.
The Top 500 Awards spotlight categories like Veteran Companies, Best Young Companies, and Most Affordable Contractors. Winning one of these honors means a company has achieved rare credibility in the industry.
If you’re looking for a countertop contractor—or your company wants to be listed among the best—this site is where quality meets opportunity.
JuniorShido
2 Sep 25 at 6:10 am
I was able to find good information from your articles.
독학기숙학원
2 Sep 25 at 6:12 am
прогнозы на спорт бесплатно от профессионалов на сегодня [url=https://prognozy-na-sport-8.ru/]https://prognozy-na-sport-8.ru/[/url] .
prognozi na sport_chmi
2 Sep 25 at 6:12 am
москва купить диплом о высшем образовании с занесением в реестр [url=https://www.arus-diplom34.ru]москва купить диплом о высшем образовании с занесением в реестр[/url] .
Diplomi_zker
2 Sep 25 at 6:12 am
можно ли купить диплом о среднем образовании [url=educ-ua4.ru]можно ли купить диплом о среднем образовании[/url] .
Diplomi_kyPl
2 Sep 25 at 6:12 am
buy antibiotics: buy antibiotics online – antibiotics over the counter
Frankelova
2 Sep 25 at 6:14 am
https://mgbk-avtomost.ru
Garthtoild
2 Sep 25 at 6:15 am
ПРОДАЖИ ТУТ – ПРИОБРЕСТИ MEFEDRON (MEF) GASHISH BOSHK1
JosephFer
2 Sep 25 at 6:17 am
трансформаторная подстанция купить цена [url=https://transformatornye-podstancii-kupit1.ru]https://transformatornye-podstancii-kupit1.ru[/url] .
transformatornie podstancii kypit_xtor
2 Sep 25 at 6:18 am
медицинское оборудование узи [url=http://www.kupit-uzi-apparat25.ru]http://www.kupit-uzi-apparat25.ru[/url] .
kypit yzi apparat_uzSa
2 Sep 25 at 6:18 am
купить аттестат про середню школе 11 класс [url=http://arus-diplom21.ru/]купить аттестат про середню школе 11 класс[/url] .
Priobresti diplom lubogo VYZa!_nepn
2 Sep 25 at 6:25 am
Приобрести диплом под заказ возможно используя официальный сайт компании. [url=http://finansi.5nx.ru/viewtopic.php?f=2&t=2014/]finansi.5nx.ru/viewtopic.php?f=2&t=2014[/url]
Sazrtzj
2 Sep 25 at 6:25 am
диплом купить проведенный [url=http://arus-diplom32.ru]диплом купить проведенный[/url] .
Diplomi_fqpi
2 Sep 25 at 6:33 am
Even during his days off, Raul Morales gets spotted by fans. On a recent visit to Universal Studios Hollywood, Morales, owner of Taqueria Vista Hermosa in Los Angeles, was waiting in line when he heard shouting.
“People called out ‘Chef Al Pastor! Chef Al Pastor!’” Morales said, laughing. Morales, who was born in Mexico City, came by the nickname through decades of hard work.
[url=https://trip-scan39.org]трип скан[/url]
He’s the third generation of his family to make al pastor tacos, their fresh tortillas filled with richly seasoned pork shaved from a rotating vertical spit.
“My recipe is very special, and very old,” he said.
Yet while Morales’ family recipes go back generations, and similar spit-roasted meats like shawarma and doner have been around for hundreds of years, his tacos represent a kind of cuisine that’s as contemporary and international as it is ancient and traditional. When you thread meat onto a spinning spit to roast it, it turns out, it doesn’t stay in one place for long.
https://trip-scan39.org
трипскан вход
‘Any place you have a pointy stick or a sword’
Roasting meat on a spit or stick is likely among humans’ most ancient cooking techniques, says food historian Ken Albala, a professor of history at the University of the Pacific.
Feasts of spit-roasted meat appear in the Homeric epics The Iliad and The Odyssey, writes Susan Sherratt, emeritus professor of East Mediterranean archaeology at the University of Sheffield, in the journal Hesperia.
Iron spits that might have been used for roasting appear in the Aegean starting in the 10th century BCE. Such spits have been unearthed in tombs associated with male warriors, Sherratt writes, noting that roasting meat may have been a practice linked to male bonding and masculinity.
“I think the reason that it’s associated with men is partly because of hunting, and the tools, or weapons, that replicated what you would do in war,” Albala said. “When you celebrated a victory, you would go out and sacrifice an animal to the gods, which would basically be like a big barbecue.”
Roasting meat is not as simple as dangling a hunk of meat over the flames. When roasting, meat is not cooked directly on top of the heat source, Albala says, but beside it, which can generate richer flavors.
“Any place you have a pointy stick or a sword, people are going to figure out very quickly … if you cook with it off to the side of the fire, it’s going to taste much more interesting,” Albala said.
CarlosBrulk
2 Sep 25 at 6:34 am
купить диплом с регистрацией [url=arus-diplom34.ru]купить диплом с регистрацией[/url] .
Diplomi_ther
2 Sep 25 at 6:34 am
купить диплом о полном среднем образовании [url=http://www.educ-ua4.ru]купить диплом о полном среднем образовании[/url] .
Diplomi_qaPl
2 Sep 25 at 6:34 am
Hey would you mind letting me know which webhost you’re utilizing?
I’ve loaded your blog in 3 different web browsers and I must say
this blog loads a lot quicker then most. Can you recommend a good hosting provider at a
fair price? Kudos, I appreciate it!
lật đổ việt cộng
2 Sep 25 at 6:36 am
бесплатные прогнозы на спорт с высокой проходимостью [url=www.prognozy-na-sport-8.ru/]www.prognozy-na-sport-8.ru/[/url] .
prognozi na sport_mpmi
2 Sep 25 at 6:36 am
Купить диплом на заказ в Москве возможно через официальный сайт компании. [url=http://promintern.listbb.ru/viewtopic.php?f=16&t=1819/]promintern.listbb.ru/viewtopic.php?f=16&t=1819[/url]
Sazrzut
2 Sep 25 at 6:37 am
купить аттестат за 11 класс москва [url=https://arus-diplom21.ru]купить аттестат за 11 класс москва[/url] .
Zakazat diplom o visshem obrazovanii!_afpn
2 Sep 25 at 6:38 am
Купить mef(mefedron) gashish boshki kokain alfa-pvp
JosephFer
2 Sep 25 at 6:40 am
купить диплом с реестром красноярск [url=https://arus-diplom34.ru/]купить диплом с реестром красноярск[/url] .
Diplomi_yuer
2 Sep 25 at 6:40 am
купить диплом института [url=educ-ua4.ru]купить диплом института[/url] .
Diplomi_nqPl
2 Sep 25 at 6:40 am
Link Pyramid Backlinks SEO Pyramid Backlink For Google
Inbound links to your site on a wide range of platforms.
We use exclusively resources from which there will be no complaints from the moderator!!!
Generating backlinks in three steps
Step 1 – Links to blog posts (Posting an article on a topic with an anchor and non-anchored link)
Step 2 – Backlinks through redirects of highly reliable sites with page rank PR 9-10, e.g.
Stage 3 – Posting an entry on backlink analysis tools –
Analysis platforms show the sitemap to the search crawlers, and this is very important.
Explanation for stage 3 – only the homepage of the site is placed on the analysis tools; subsequent pages can’t be submitted.
I execute these 3 stages sequentially, in all there will be 20,000-30,000 backlinks from three stages.
This backlink strategy is the top-performing.
I will provide the link data on indexing platforms in a document.
Catalog of SEO platforms hundreds of tools.
Provide a progress report via majestic, semrush , or ahrefs If one of the platforms shows less backlinks, I submit the report using the tool with more links because why wait for the latency?
SEO
2 Sep 25 at 6:40 am
купить диплом с внесением в реестр [url=https://www.arus-diplom32.ru]купить диплом с внесением в реестр[/url] .
Diplomi_ccpi
2 Sep 25 at 6:44 am
В Нижнем Новгороде решение есть — наркологическая клиника. Здесь помогают людям выйти из запоя без страха и осуждения. Всё анонимно, грамотно и с заботой о каждом пациенте.
Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-stacionare14.ru/]вывод из запоя цена[/url]
Andrewsnaws
2 Sep 25 at 6:44 am
Even during his days off, Raul Morales gets spotted by fans. On a recent visit to Universal Studios Hollywood, Morales, owner of Taqueria Vista Hermosa in Los Angeles, was waiting in line when he heard shouting.
“People called out ‘Chef Al Pastor! Chef Al Pastor!’” Morales said, laughing. Morales, who was born in Mexico City, came by the nickname through decades of hard work.
[url=https://trip-scan39.org]tripscan войти[/url]
He’s the third generation of his family to make al pastor tacos, their fresh tortillas filled with richly seasoned pork shaved from a rotating vertical spit.
“My recipe is very special, and very old,” he said.
Yet while Morales’ family recipes go back generations, and similar spit-roasted meats like shawarma and doner have been around for hundreds of years, his tacos represent a kind of cuisine that’s as contemporary and international as it is ancient and traditional. When you thread meat onto a spinning spit to roast it, it turns out, it doesn’t stay in one place for long.
https://trip-scan39.org
tripscan войти
‘Any place you have a pointy stick or a sword’
Roasting meat on a spit or stick is likely among humans’ most ancient cooking techniques, says food historian Ken Albala, a professor of history at the University of the Pacific.
Feasts of spit-roasted meat appear in the Homeric epics The Iliad and The Odyssey, writes Susan Sherratt, emeritus professor of East Mediterranean archaeology at the University of Sheffield, in the journal Hesperia.
Iron spits that might have been used for roasting appear in the Aegean starting in the 10th century BCE. Such spits have been unearthed in tombs associated with male warriors, Sherratt writes, noting that roasting meat may have been a practice linked to male bonding and masculinity.
“I think the reason that it’s associated with men is partly because of hunting, and the tools, or weapons, that replicated what you would do in war,” Albala said. “When you celebrated a victory, you would go out and sacrifice an animal to the gods, which would basically be like a big barbecue.”
Roasting meat is not as simple as dangling a hunk of meat over the flames. When roasting, meat is not cooked directly on top of the heat source, Albala says, but beside it, which can generate richer flavors.
“Any place you have a pointy stick or a sword, people are going to figure out very quickly … if you cook with it off to the side of the fire, it’s going to taste much more interesting,” Albala said.
CarlosBrulk
2 Sep 25 at 6:47 am
накрутка живых участников ТГ
Robertexart
2 Sep 25 at 6:48 am
прогнозы на спорт от экспертов [url=https://prognozy-na-sport-8.ru/]прогнозы на спорт от экспертов[/url] .
prognozi na sport_sxmi
2 Sep 25 at 6:54 am
купить кашпо для цветов напольное высокое пластиковое [url=www.kashpo-napolnoe-krasnodar.ru]купить кашпо для цветов напольное высокое пластиковое[/url] .
kashpo napolnoe _kjma
2 Sep 25 at 7:03 am
Сноуборды в нашем прокате отличаются высоким качеством и современным дизайном, а обслуживание гарантирует идеальное состояние: прокат лыж красная поляна
JosephHub
2 Sep 25 at 7:03 am
Казино Leonbets слот Akn Of Providence
Marvinawasp
2 Sep 25 at 7:03 am
Заказать mefedron gash kokain alfa-pvp
JosephFer
2 Sep 25 at 7:03 am
https://depooptics.ru
Garthtoild
2 Sep 25 at 7:04 am
J’apprecie enormement Banzai Casino, ca ressemble a une plongee dans le divertissement intense. Les options de jeu sont epoustouflantes, incluant des slots dynamiques. Le support est ultra-reactif, joignable 24/7. Les retraits sont rapides comme l’eclair, par moments davantage de recompenses seraient un plus. Pour faire court, Banzai Casino ne decoit jamais pour les joueurs en quete de frissons ! En prime le site est concu avec dynamisme, ajoutant une touche d’elegance et d’energie.
casino banzai slots|
Quauco4zef
2 Sep 25 at 7:13 am
купить диплом в ивано франковске [url=https://educ-ua4.ru/]https://educ-ua4.ru/[/url] .
Diplomi_siPl
2 Sep 25 at 7:14 am
как купить легальный диплом о среднем образовании [url=http://arus-diplom34.ru]http://arus-diplom34.ru[/url] .
Diplomi_xeer
2 Sep 25 at 7:14 am
Je suis completement seduit par Betclic Casino, on dirait une experience de jeu electrisante. Il y a une profusion de titres varies, offrant des sessions de casino en direct immersives. Les agents sont toujours disponibles et professionnels, repondant instantanement. Les retraits sont ultra-rapides, occasionnellement j’aimerais plus d’offres promotionnelles. Dans l’ensemble, Betclic Casino ne decoit jamais pour les adeptes de sensations fortes ! Notons egalement que l’interface est fluide et intuitive, facilite chaque session de jeu.
freebet betclic|
Dieona8zef
2 Sep 25 at 7:14 am
платные прогнозы на спорт бесплатно [url=https://prognozy-na-sport-8.ru/]платные прогнозы на спорт бесплатно[/url] .
prognozi na sport_ismi
2 Sep 25 at 7:26 am
Заказать mefedron gash kokain alfa-pvp
JosephFer
2 Sep 25 at 7:26 am
Nice post. I was checking constantly this blog and I am impressed!
Extremely useful information particularly the last part :
) I care for such info much. I was looking for this certain information for a very
long time. Thank you and best of luck.
Fatvim Weight Loss Formula
2 Sep 25 at 7:28 am
купить аттестат за 11 класс вечерней школы [url=arus-diplom24.ru]купить аттестат за 11 класс вечерней школы[/url] .
Diplomi_vgsa
2 Sep 25 at 7:29 am
анонимный наркологический центр [url=https://narkologicheskaya-klinika-14.ru/]https://narkologicheskaya-klinika-14.ru/[/url] .
narkologicheskaya klinika_ynsn
2 Sep 25 at 7:30 am
бесплатные точные прогнозы [url=https://www.prognozy-na-sport-8.ru]бесплатные точные прогнозы[/url] .
prognozi na sport_lemi
2 Sep 25 at 7:31 am