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!
Одним из ключевых преимуществ «КузбассМед» является современная материально-техническая база. В клинике задействованы устройства для точного мониторинга жизненных функций, автоматические инфузионные системы, экспресс-диагностические модули и оборудование для неотложной терапии. Врачи используют программируемые дозаторы, портативные анализаторы крови и аппараты для оценки дыхательной функции, что позволяет своевременно корректировать тактику лечения без потерь времени. Все процедуры соответствуют национальным стандартам безопасности и рекомендациям ВОЗ.
Получить дополнительные сведения – http://narkologicheskaya-klinika-novokuzneczk0.ru/narkologicheskij-czentr-novokuzneczk/https://narkologicheskaya-klinika-novokuzneczk0.ru
Dwayneavads
2 Oct 25 at 11:22 pm
Критерии оценки профессионального уровня сотрудников:
Детальнее – [url=https://lechenie-alkogolizma-yaroslavl0.ru/]lechenie-alkogolizma-yaroslavl0.ru/[/url]
SantosLip
2 Oct 25 at 11:22 pm
прогнозы на спорт с большими коэффициентами [url=https://prognozy-na-sport-12.ru]https://prognozy-na-sport-12.ru[/url] .
prognozi na sport_haMn
2 Oct 25 at 11:24 pm
My partner and I absolutely love your blog and find a lot of your post’s to be just what I’m looking
for. can you offer guest writers to write content for
you personally? I wouldn’t mind writing a post or elaborating
on a number of the subjects you write related to here.
Again, awesome web log!
santal 33 dupe
2 Oct 25 at 11:25 pm
lastminute-corporate – The site feels practical, perfect for quick business solutions anytime.
Keesha Kistle
2 Oct 25 at 11:29 pm
Hi there, i read your blog from time to time and i own a similar one and i was just wondering if you get a
lot of spam feedback? If so how do you protect against
it, any plugin or anything you can recommend?
I get so much lately it’s driving me mad so any support is very much
appreciated.
salt trick for men review
2 Oct 25 at 11:31 pm
прогнозы на спорт на сегодня экспрессы [url=www.prognozy-na-sport-12.ru]www.prognozy-na-sport-12.ru[/url] .
prognozi na sport_auMn
2 Oct 25 at 11:33 pm
прогноз ставки [url=https://www.stavka-10.ru]https://www.stavka-10.ru[/url] .
stavka_bxSi
2 Oct 25 at 11:33 pm
https://www.wildberries.ru/catalog/514992745/detail.aspx
Kevinsaush
2 Oct 25 at 11:33 pm
https://network-6598889.mn.co/members/36175497
Robertbiz
2 Oct 25 at 11:34 pm
Магазин 24/7 – купить закладку MEF GASH SHIHSKI
Jeromeliz
2 Oct 25 at 11:37 pm
прогноз на спорт [url=https://www.prognozy-na-sport-12.ru]прогноз на спорт[/url] .
prognozi na sport_iaMn
2 Oct 25 at 11:37 pm
Мы обратились в СтройСинтез для строительства дома под ключ в скандинавском стиле. Специалисты учли все наши пожелания по дизайну и планировке. Работы были выполнены в срок, а дом получился уютный и современный. Благодарим компанию за профессионализм https://stroysyntez.com/
Brianvop
2 Oct 25 at 11:38 pm
http://truevitalmeds.com/# sildenafil
Williamjib
2 Oct 25 at 11:40 pm
купить диплом в балашихе [url=https://rudik-diplom14.ru/]купить диплом в балашихе[/url] .
Diplomi_ezea
2 Oct 25 at 11:42 pm
ставки прогнозы [url=http://www.novosti-sporta-17.ru]http://www.novosti-sporta-17.ru[/url] .
novosti sporta_osOi
2 Oct 25 at 11:43 pm
cnsbiodesk – Everything loads smoothly, making navigation simple and efficient here.
Junie Dobrzykowski
2 Oct 25 at 11:44 pm
купить диплом в новошахтинске [url=www.rudik-diplom15.ru]www.rudik-diplom15.ru[/url] .
Diplomi_zgPi
2 Oct 25 at 11:45 pm
Компания СтройСинтез реализовала для нас проект коттеджа из кирпича в Ленинградской области. Работы выполнялись профессионально, а результат радует каждый день. Дом получился прочный и красивый. Больше информации можно найти здесь https://stroysyntez.com/
Brianvop
2 Oct 25 at 11:49 pm
It’s no secret how President Donald Trump feels about sports teams turning away from Native American mascots. He’s repeatedly called for the return of the Washington Redskins and Cleveland Indians, claiming their recent rebrands were part of a “woke” agenda designed to erase history.
But one surprising team has really gotten the president’s attention: the Massapequa Chiefs.
The Long Island school district has refused to change its logo and name under a mandate from New York state banning schools from using team mascots appropriating Indigenous culture. Schools were given two years to rebrand, but Massapequa is the lone holdout, having missed the June 30 deadline to debut a new logo.
[url=https://kra-40-at.net]kra40[/url]
The district lost an initial lawsuit it filed against the state but now has the federal government on its side. In May, Trump’s Department of Education intervened on the district’s behalf, claiming the state’s mascot ban is itself discriminatory.
Massapequa’s Chiefs logo — an American Indian wearing a yellow feathered headdress — is expected to still be prominently displayed when the fall sports season kicks off soon, putting the quiet Long Island hamlet at the center of a political firestorm.
[url=https://kra-40at.net]kra39 cc[/url]
The district is now a key “battleground,” said Oliver Roberts, a Massapequa alum and the lawyer representing the school board in its fresh lawsuit against New York claiming that the ban is unconstitutional and discriminatory.
The Trump administration claims New York’s mascot ban violates Title VI of the Civil Rights Act of 1964, which prohibits recipients of federal funds from engaging in discriminatory behavior based on race, color or national origin — teeing up a potentially precedent-setting fight.
The intervention on behalf of Massapequa follows a pattern for a White House that has aggressively applied civil rights protections to police “reverse discrimination” and coerced schools and universities into policy concessions by withholding federal funds.
“Our goal is to assist nationally,” Roberts said. “It’s us putting forward our time and effort to try and assist with this national movement and push back against the woke bureaucrats trying to cancel our country’s history and tradition.”
kra39
https://kra40—cc.ru
Brandonnot
2 Oct 25 at 11:49 pm
If you are going for finest contents like I do, just go to see this website
all the time since it presents feature contents, thanks
Read Full Report
2 Oct 25 at 11:50 pm
Buscas productos saludables para una vida plena en Mexico? Visita https://nagazi-shop.com/ y encontraras remedios homeopaticos y suplementos dieteticos populares disenados para complementar tu dieta. Explora nuestro catalogo y seguro encontraras los productos ideales para ti.
pykabllMoX
2 Oct 25 at 11:51 pm
Даже телефонный разговор с клиникой может многое сказать о её подходе. Если вам предлагают типовое лечение без уточнения подробностей или избегают вопросов о составе команды, это тревожный сигнал. Серьёзные учреждения в Мурманске обязательно предложат предварительную консультацию, зададут уточняющие вопросы и расскажут, как строится программа помощи.
Изучить вопрос глубже – [url=https://lechenie-alkogolizma-murmansk0.ru/]www.domen.ru[/url]
Jameshar
2 Oct 25 at 11:51 pm
lastminute-corporate – Very efficient vibe, looks like it saves a lot of time.
Mack Freyman
2 Oct 25 at 11:52 pm
диплом медсестры с аккредитацией купить [url=http://frei-diplom15.ru]диплом медсестры с аккредитацией купить[/url] .
Diplomi_tloi
2 Oct 25 at 11:54 pm
stavki prognozy [url=http://novosti-sporta-15.ru]http://novosti-sporta-15.ru[/url] .
novosti sporta_zkma
2 Oct 25 at 11:56 pm
прогнозы на спорт с высокой проходимостью бесплатно с большим коэффициентом [url=https://www.prognozy-na-sport-12.ru]https://www.prognozy-na-sport-12.ru[/url] .
prognozi na sport_jzMn
2 Oct 25 at 11:56 pm
J’eprouve une ivresse totale pour PepperMill Casino, ca exhale un jardin de defis parfumes. Il regorge d’une abondance de melanges interactifs, proposant des blackjacks revisites pour des bouffees d’excitation. Le service infuse en continu 24/7, accessible par infusion ou missive instantanee. Les courants financiers sont fortifies par des racines crypto, toutefois des herbes de recompense additionnelles epiceraient les alliances. En concluant l’infusion, PepperMill Casino revele un sentier de triomphes parfumes pour les maitres de victoires odorantes ! En sus l’interface est un sentier herbeux navigable avec art, instille une quintessence de mystere epice.
hotel peppermill reno|
CosmicForgeB3zef
2 Oct 25 at 11:56 pm
Generic tadalafil 20mg price: Buy Tadalafil online – tadalafil 5 mg tablet coupon
MartinJaive
2 Oct 25 at 11:58 pm
This design is wicked! You certainly know how to
keep a reader amused. Between your wit and your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job.
I really enjoyed what you had to say, and more
than that, how you presented it. Too cool!
top up murah
2 Oct 25 at 11:58 pm
You ought to be a part of a contest for one of the highest quality websites on the web.
I most certainly will recommend this site!
BDE Construction & Kitchen Cabinets
2 Oct 25 at 11:59 pm
все про спорт прогнозы [url=www.prognozy-na-sport-12.ru]все про спорт прогнозы[/url] .
prognozi na sport_tiMn
3 Oct 25 at 12:02 am
Магазин 24/7 – купить закладку MEF GASH SHIHSKI
Jeromeliz
3 Oct 25 at 12:02 am
прогнозы на футбол сегодня [url=https://www.prognozy-na-futbol-9.ru]прогнозы на футбол сегодня[/url] .
prognozi na fytbol_adea
3 Oct 25 at 12:04 am
экстренный вывод из запоя смоленск
vivod-iz-zapoya-smolensk021.ru
экстренный вывод из запоя смоленск
lecheniesmolenskNeT
3 Oct 25 at 12:06 am
1win blackjack uz [url=https://1win5507.ru]https://1win5507.ru[/url]
1win_otkr
3 Oct 25 at 12:06 am
ставки и прогнозы на спорт [url=http://www.prognozy-na-sport-12.ru]http://www.prognozy-na-sport-12.ru[/url] .
prognozi na sport_xnMn
3 Oct 25 at 12:07 am
Когда начали работать с Mihaylov Digital, сразу заметили серьёзный подход. Всё сделано поэтапно и с отчётами. Сайт вырос в поиске и приносит клиентов. Мы довольны результатом https://mihaylov.digital/
Steventob
3 Oct 25 at 12:08 am
Mighty Dog Roofing
Reimer Drive North 13768
Maple Grove, MN 55311 United Ⴝtates
(763) 280-5115
siding replacement team
siding replacement team
3 Oct 25 at 12:08 am
Закупки и официальный импорт из Китая
GeraldObedo
3 Oct 25 at 12:09 am
[url=https://madcasino.top]mad casino[/url]
Anthonyemime
3 Oct 25 at 12:10 am
Je suis captive par Fezbet Casino, on dirait un festival de sensations brulantes. La gamme de jeux est un veritable mirage de delices, proposant des paris sportifs qui font grimper la temperature. L’assistance est precise comme un rayon ardent, joignable a tout instant. Le processus est lisse comme un sable fin, mais des recompenses supplementaires seraient torrides. En conclusion, Fezbet Casino est une plateforme qui embrase les sens pour ceux qui cherchent des frissons enflammes ! En bonus la navigation est intuitive comme une flamme dansante, ajoute une touche de magie enflammee.
fezbet deposito minimo|
StarPulseK7zef
3 Oct 25 at 12:11 am
прогноз на футбол [url=http://prognozy-na-futbol-9.ru]прогноз на футбол[/url] .
prognozi na fytbol_btea
3 Oct 25 at 12:14 am
DragonMoney – онлайн-казино с лицензией, предлагает выгодные бонусы, разнообразные игры от ведущих провайдеров, мгновенные выплаты и круглосуточную поддержку https://dom-u-parka.ru/
Richardusags
3 Oct 25 at 12:18 am
themacallenbuilding – I’d recommend this to friends since it feels trustworthy and refined.
Bennie Morta
3 Oct 25 at 12:22 am
Hello, I read your blogs regularly. Your writing style is witty, keep doing what you’re
doing!
Hejx.space
3 Oct 25 at 12:22 am
диплом медсестры с аккредитацией купить [url=www.frei-diplom15.ru/]диплом медсестры с аккредитацией купить[/url] .
Diplomi_gqoi
3 Oct 25 at 12:24 am
Методическая база клиники опирается на доказательные подходы и стандартизированные протоколы. Комбинация инструментов подбирается индивидуально с учётом переносимости и клинической целесообразности.
Детальнее – https://narkologicheskaya-klinika-lugansk0.ru/luganskaya-narkologicheskaya-bolnicza
RussellWheew
3 Oct 25 at 12:25 am
— Растворы с глюкозой и витаминами для коррекции энергетического обмена. — Минеральные комплексы для нормализации электролитов. — Антиоксиданты и гепатопротекторы для защиты печени. — Спазмолитики для снятия болевого синдрома. — Противорвотные препараты при тошноте.
Углубиться в тему – http://narkologicheskaya-klinika-arkhangelsk0.ru/
Haroldsleek
3 Oct 25 at 12:25 am
купить диплом в крыму [url=http://rudik-diplom6.ru]купить диплом в крыму[/url] .
Diplomi_odKr
3 Oct 25 at 12:26 am