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!
comprar barato ozempic
DavidNaike
13 Sep 25 at 11:13 pm
Hmm is anyone else experiencing problems with the images on this blog loading?
I’m trying to determine if its a problem on my end or if it’s the blog.
Any suggestions would be greatly appreciated.
The Water Heater Warehouse water heater filtration
13 Sep 25 at 11:18 pm
Estou alucinado com SupaBet Casino, da uma energia de cassino que e um trovao supersonico. A selecao de titulos do cassino e uma onda de diversao, com jogos de cassino perfeitos pra criptomoedas. Os agentes do cassino sao rapidos como um relampago cosmico, respondendo mais rapido que uma explosao estelar. Os pagamentos do cassino sao lisos e blindados, mesmo assim queria mais promocoes de cassino que abalam o planeta. Resumindo, SupaBet Casino garante uma diversao de cassino que e uma explosao total para os apaixonados por slots modernos de cassino! E mais a interface do cassino e fluida e reluz como uma aurora vulcanica, faz voce querer voltar ao cassino como um meteoro em orbita.
supabet soccer fixture pdf 04 08 2018|
sparklyjellyrhino5zef
13 Sep 25 at 11:20 pm
купить диплом занесением реестр украины [url=arus-diplom33.ru]arus-diplom33.ru[/url] .
Diplomi_dzSa
13 Sep 25 at 11:20 pm
https://brookspqxq424.trexgame.net/los-errores-mas-comunes-antes-de-un-examen-antidoping
Enfrentar un control sorpresa puede ser complicado. Por eso, se desarrollo una solucion cientifica probada en laboratorios.
Su composicion eficaz combina carbohidratos, lo que ajusta tu organismo y enmascara temporalmente los metabolitos de toxinas. El resultado: una prueba sin riesgos, lista para entregar tranquilidad.
Lo mas destacado es su ventana de efectividad de 4 a 5 horas. A diferencia de metodos caseros, no promete milagros, sino una solucion temporal que responde en el momento justo.
Miles de trabajadores ya han comprobado su efectividad. Testimonios reales mencionan resultados exitosos en pruebas preocupacionales.
Si quieres proteger tu futuro, esta solucion te ofrece seguridad.
JuniorShido
13 Sep 25 at 11:22 pm
купить диплом занесением реестр украины [url=https://shkval.forum24.ru/?1-1-0-00001022-000-0-0-1752571227]купить диплом занесением реестр украины[/url] .
Bistro kypit diplom instityta!_drkt
13 Sep 25 at 11:23 pm
generic cipro price
can i purchase cipro without dr prescription
13 Sep 25 at 11:23 pm
Bluewaters Island
MichaelGomia
13 Sep 25 at 11:23 pm
купить дипломы техникума старого образца [url=www.educ-ua2.ru]купить дипломы техникума старого образца[/url] .
Diplomi_hmOt
13 Sep 25 at 11:23 pm
Этот комплекс мер позволяет оказывать помощь пациентам на всех стадиях зависимости.
Получить дополнительную информацию – [url=https://narkologicheskaya-klinika-sankt-peterburg14.ru/]наркологическая клиника вывод из запоя[/url]
Romanronse
13 Sep 25 at 11:25 pm
купить диплом стоит [url=http://educ-ua4.ru]купить диплом стоит[/url] .
Diplomi_ewPl
13 Sep 25 at 11:26 pm
WOW just what I was searching for. Came here by searching for independent Mumbai call girls
independent Mumbai call girls
13 Sep 25 at 11:27 pm
подключить интернет
inernetvkvartiru-spb004.ru
домашний интернет тарифы
internetelini
13 Sep 25 at 11:27 pm
купить диплом университета с занесением в реестр [url=www.play.ntop.tv/user/vadyymemelnvv/]купить диплом университета с занесением в реестр[/url] .
Zakazat diplom instityta!_zwkt
13 Sep 25 at 11:27 pm
We are a group of volunteers and opening a new scheme in our community.
Your site provided us with valuable information to work
on. You have done an impressive job and our whole community will be grateful to you. https://www.kamayuq.io/employer/flybb/
проститутки пермь
13 Sep 25 at 11:29 pm
can i order generic isordil without dr prescription
how to buy cheap isordil without rx
13 Sep 25 at 11:30 pm
https://bpr-work.ru/
Charlesbor
13 Sep 25 at 11:31 pm
http://verleih-service.eu/
AndrewKem
13 Sep 25 at 11:34 pm
Привет всем!
Долго думал как встать в топ поисковиков и узнал от крутых seo,
профи ребят, именно они разработали недорогой и главное продуктивный прогон Xrumer – https://imap33.site
Линкбилдинг или покупка ссылок – частый вопрос веб-мастеров. Xrumer позволяет автоматизировать размещение ссылок на форумах и блогах. Массовый прогон ускоряет рост DR. Автоматизация экономит силы специалистов. Линкбилдинг или покупка ссылок – выбирайте стратегию с умом.
что такое seo оптимизация карточки товара, михаил seo, что такое линкбилдинг
Генерация внешних ссылок быстро, как называются специалисты по продвижению сайтов, раскрутка сайта в яндексе услуги
!!Удачи и роста в топах!!
JeromeNow
13 Sep 25 at 11:34 pm
купить диплом о среднем специальном образовании с занесением в реестр [url=https://educ-ua13.ru]купить диплом о среднем специальном образовании с занесением в реестр[/url] .
Diplomi_fapn
13 Sep 25 at 11:39 pm
http://verleih-service.eu/
AndrewKem
13 Sep 25 at 11:40 pm
купить диплом в запорожье [url=www.educ-ua2.ru]купить диплом в запорожье[/url] .
Diplomi_hwOt
13 Sep 25 at 11:44 pm
Выездной нарколог в владимире — это оптимальное решение для людей‚ которые испытывают необходимость в помощи нарколога‚ но не могут посетить лечебное заведение. Профессиональная помощь в борьбе с зависимостями доступна прямо на дому‚ что обеспечивает комфорт и анонимность.Обращение к наркологу даёт возможность оценить ситуацию и выбрать оптимальную программу реабилитации‚ включая лечение в стационаре или выезд на дом. Наши эксперты предлагают психотерапию зависимостей и медицинские процедуры‚ что помогает успешному лечению зависимостей. Поддержка семьи играет важную роль в процессе‚ помогая пациентам преодолеть сложности. Обратитесь на vivod-iz-zapoya-vladimir016.ru для подробной информации о наших услугах.
alkogolizmvladimirNeT
13 Sep 25 at 11:45 pm
легальный диплом купить [url=http://www.educ-ua12.ru]легальный диплом купить[/url] .
Diplomi_idMt
13 Sep 25 at 11:51 pm
SaludFrontera: mexico prescription online – purple pharmacy mexico
Charlesdyelm
13 Sep 25 at 11:55 pm
купить диплом проведенный москва [url=www.starterkit.ru/html/index.php?name=account&op=info&uname=iliaanisimov/]купить диплом проведенный москва[/url] .
Vigodno zakazat diplom o visshem obrazovanii!_jrkt
13 Sep 25 at 11:56 pm
как купить диплом о высшем образовании с занесением в реестр отзывы [url=http://educ-ua13.ru/]http://educ-ua13.ru/[/url] .
Diplomi_aipn
14 Sep 25 at 12:00 am
купить диплом о высшем киев [url=educ-ua2.ru]купить диплом о высшем киев[/url] .
Diplomi_anOt
14 Sep 25 at 12:05 am
Bluewaters Island
MichaelGomia
14 Sep 25 at 12:06 am
Hello there! This blog post couldn’t be written much better!
Looking at this article reminds me of my previous roommate!
He constantly kept preaching about this. I
will forward this article to him. Fairly certain he will have a great
read. I appreciate you for sharing!
Finovantrex
14 Sep 25 at 12:08 am
Backlinks SEO Google Websites Analyzers Redirects PR 8-10
Backlinks from Polish domains constitute an efficient strategy to enhance your website’s ranking as well as authority within Google.
Links are placed exclusively on SEO links on authentic Polish forums, blogs, plus comment areas. This is a natural linking strategy that not only boosts search engine optimization, but additionally generates supplemental traffic from referrals through authentic user engagement.
Why choose this SEO solution?
Full Polish domain coverage
Blend of forums, topic-specific blogs, along with relevant comments
Authentic linking profile that Google values
Following the work, of our services, you will receive a clear as well as thorough written report
BacklinksSic
14 Sep 25 at 12:10 am
купить диплом об образовании [url=http://educ-ua4.ru]купить диплом об образовании[/url] .
Diplomi_tqPl
14 Sep 25 at 12:10 am
Business Bay
Josephrew
14 Sep 25 at 12:13 am
Добрый день!
Долго обмозговывал как поднять сайт и свои проекты и нарастить CF cituation flow и узнал от гуру в seo,
отличных ребят, именно они разработали недорогой и главное продуктивный прогон Xrumer – https://imap33.site
Линкбилдинг seo помогает достигать лучших результатов. Он включает создание ссылок и работу с трастовыми площадками. Программы для автоматизации ускоряют процесс. Чем больше качественных ссылок, тем выше позиции. Линкбилдинг seo – залог успешного продвижения.
пример seo оптимизация, шаблон seo сайта, линкбилдинг статьи
Автоматическое размещение ссылок, traffic seo, расчет продвижения сайтов
!!Удачи и роста в топах!!
JeromeNow
14 Sep 25 at 12:15 am
Hi there, yes this piece of writing is genuinely pleasant and I have learned lot of things from it
about blogging. thanks.
AI Arbitrage
14 Sep 25 at 12:17 am
https://business-bay-dubai.ae/
Josephrew
14 Sep 25 at 12:18 am
City Walk
JamesDiota
14 Sep 25 at 12:18 am
Oh my goodness! Incredible article dude!
Thank you so much, However I am experiencing difficulties with your RSS.
I don’t know the reason why I can’t join it. Is there anyone else having identical RSS issues?
Anyone that knows the solution can you kindly
respond? Thanx!!
texas holdem poker
14 Sep 25 at 12:20 am
диплом внесенный в реестр купить [url=https://forum.wowcircle.com/member.php?u=613658]https://forum.wowcircle.com/member.php?u=613658[/url] .
Priobresti diplom VYZa!_ywkt
14 Sep 25 at 12:21 am
Pills information. Effects of Drug Abuse.
benadryl seroquel
Actual information about medicament. Get now.
benadryl seroquel
14 Sep 25 at 12:21 am
купить диплом занесением в реестр [url=https://www.educ-ua13.ru]купить диплом занесением в реестр[/url] .
Diplomi_rapn
14 Sep 25 at 12:22 am
https://city-walk-central-park.ae/
JamesDiota
14 Sep 25 at 12:23 am
купить диплом в харькове [url=https://www.educ-ua2.ru]купить диплом в харькове[/url] .
Diplomi_bgOt
14 Sep 25 at 12:26 am
Единая панель оценки помогает действовать быстро и безошибочно. Мы фиксируем параметры, объясняем их смысл пациенту и семье и тут же привязываем к ним действия. Пример приведён в таблице: это не заменяет осмотр, но показывает логику, которой мы придерживаемся на выезде и в приёмном кабинете.
Получить дополнительную информацию – [url=https://narkologicheskaya-klinika-ryazan14.ru/]лечение в наркологической клинике[/url]
AnthonyRah
14 Sep 25 at 12:26 am
купить проведенный диплом Украина [url=https://educ-ua13.ru]https://educ-ua13.ru[/url] .
Diplomi_gwpn
14 Sep 25 at 12:28 am
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.
[url=https://kra35.org]kra39 at [/url]
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-40cc.ru]kra39[/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://kra40—at.ru]kra39[/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
kra38 at
ScottZib
14 Sep 25 at 12:30 am
купить диплом специалиста дешево [url=http://educ-ua2.ru/]купить диплом специалиста дешево[/url] .
Diplomi_xtOt
14 Sep 25 at 12:31 am
pharmacy in mexico online: buying prescription drugs in mexico – can i buy meds from mexico online
Teddyroowl
14 Sep 25 at 12:32 am
купить диплом с занесением в реестр в Украине [url=www.educ-ua12.ru/]купить диплом с занесением в реестр в Украине[/url] .
Diplomi_gmMt
14 Sep 25 at 12:32 am
купить диплом о высшем киев [url=http://www.educ-ua4.ru]купить диплом о высшем киев[/url] .
Diplomi_toPl
14 Sep 25 at 12:32 am