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!
Экстренное вмешательство необходимо, когда самостоятельное прекращение употребления алкоголя или наркотиков становится невозможным, а состояние пациента ухудшается. Основные показания включают:
Подробнее – нарколог на дом стоимость уфа
Покупка дипломов ВУЗов в Москве — с печатями, подписями, приложением и возможностью архивной записи (по запросу).
Документ максимально приближен к оригиналу и проходит визуальную проверку.
Мы гарантируем, что в случае проверки документа, подозрений не возникнет.
– Конфиденциально
– Доставка 3–7 дней
– Любая специальность
Уже более 1979 клиентов воспользовались услугой — теперь ваша очередь.
[url=http://spbrcom5.ru/]Пишите[/url] — ответим быстро, без лишних формальностей.
отчет по практике сколько стоит заказать отчет по учебной практике
Наркологический центр “Новый Взгляд” расположен по адресу: г. Самара, ул. Ленина 9. Мы открыты для пациентов круглосуточно. Также доступны онлайн-консультации, что делает наши услуги более доступными для всех нуждающихся.
Разобраться лучше – http://тайный-вывод-из-запоя.рф/vyvod-iz-zapoya-na-domu-v-samare.xn--p1ai/
Swapping SOL, USDC, or memecoins? Jupiter supports hundreds of tokens on Solana.
https://the-jupiter-app.com/
написать отчет по практике заказать купить отчет по преддипломной практике
дипломная работа на заказ стоимость https://diplomsdayu.ru
Having read this I believed it was extremely informative.
I appreciate you finding the time and energy to put this content together.
I once again find myself personally spending a lot of time both reading and commenting.
But so what, it was still worthwhile!
I think this is one of the most vital info for me. And i
am glad reading your article. But want to remark on few general things,
The site style is great, the articles is really nice : D.
Good job, cheers
Have you ever considered about adding a little bit more than just your articles?
I mean, what you say is fundamental and everything.
But imagine if you added some great photos or video clips to give your posts more, “pop”!
Your content is excellent but with pics and video clips, this blog could certainly be one of the
greatest in its field. Amazing blog!
Мы также уделяем большое внимание социальной адаптации. Пациенты учатся восстанавливать навыки общения и обретать уверенность в себе, что помогает в будущем избежать рецидивов и успешно вернуться к полноценной жизни, будь то работа или учеба.
Получить дополнительные сведения – http://быстро-вывод-из-запоя.рф/vyvod-iz-zapoya-anonimno-v-volgograde.xn--p1ai/
Excellent beat ! I wish to apprentice even as you amend your web site, how
could i subscribe for a blog website? The account helped me a applicable deal.
I had been tiny bit acquainted of this your broadcast provided shiny transparent idea
mostbet скачат mostbet скачат
Greetings! Very helpful advice in this particular post!
It is the little changes that make the largest changes.
Thanks for sharing!
про спорт для детей Кайт лагерь – это формат отдыха, сочетающий обучение кайтсерфингу, проживание и развлечения в компании единомышленников.
Thanks for finally writing about > PHP hook, building
hooks in your application – Sjoerd Maessen blog < Loved it!
мостбет ком mostbet4016.ru
Экстренная установка капельницы необходима, если пациент находится в состоянии запоя более 2–3 дней или испытывает симптомы тяжелой интоксикации алкоголем:
Разобраться лучше – http://kapelnica-ot-zapoya-sochi00.ru
Find real stories and advice from people in recovery on this forum.
Expand your knowledge – https://forum4rehab.com/
Экстренное вмешательство необходимо, когда самостоятельное прекращение употребления алкоголя или наркотиков становится невозможным, а состояние пациента ухудшается. Основные показания включают:
Получить дополнительные сведения – http://narcolog-na-dom-ufa000.ru/narkolog-na-dom-czena-ufa/
You can definitely see your enthusiasm in the work you
write. The sector hopes for even more passionate writers such as you who
are not afraid to say how they believe. At all times follow your heart.
Форум AntiNarcoForum — место, где зависимые и их близкие могут анонимно получить помощь профессионалов и участников сообщества. Здесь обсуждаются эффективные методы лечения зависимостей, личные истории успеха и конкретные советы по выходу из сложных ситуаций.
Детальнее – реабилитационный центр наркомании
is 1win bet legit https://1win3008.com/
Hello, I do think your web site could be having browser compatibility problems.
Whenever I look at your web site in Safari, it
looks fine but when opening in IE, it has some overlapping
issues. I simply wanted to provide you with a quick heads
up! Besides that, excellent blog!
Greetings, I’m Piotr from Poland. I wanna tell you about my insane experience with this new
online casino I stumbled on a few weeks ago.
To be honest, I was struggling badly, and now I can’t believe it myself
— I won $1,500,000 playing mostly live roulette!
Now I’m thinking of taking my dream vacation and buying a house here in Cluj-Napoca, and investing a serious chunk of my
winnings into Cardano.
Later I’ll probably move to a better neighborhood and start a small business.
Now I’m going by Luka from Croatia because I honestly feel like a new person. My life is flipping upside down in the best way.
No cap, what would you guys do if you had this kinda luck?
Are you feeling curious right now?
For real, I never thought I’d have a shot at investing.
It’s all happening so fast!
Let’s talk crypto too!
Hey are using WordPress for your site platform?
I’m new to the blog world but I’m trying to get started and create
my own. Do you require any coding knowledge to make your own blog?
Any help would be really appreciated!
https://www.shkolazhizni.ru/market/articles/111488/
El codigo de promocion de 1xBet “https://coryn.club/forum/pgs/?c_digo_promocional_166.html” le permite recibir hasta $130 en bono cuando realiza su primer deposito en 2025. 1xBet es una popular casa de apuestas en linea que ofrece una amplia seleccion de apuestas deportivas y juegos de azar. Para los nuevos usuarios, 1xbet ofrece un regalo de bienvenida especial en forma de codigo promocional. Los codigos promocionales son codigos especiales que le permiten obtener bonos adicionales al registrarse o realizar apuestas en el sitio.
После процедуры пациент чувствует значительное облегчение состояния, улучшение самочувствия и снижение тяги к алкоголю.
Получить больше информации – врач на дом капельница от запоя сочи
Алкогольная и наркотическая зависимость являются серьёзными заболеваниями, требующими оперативного и квалифицированного вмешательства. Когда речь идёт о критическом состоянии пациента, особенно после длительного употребления алкоголя или наркотических веществ, время играет ключевую роль. Клиника «РеабилитАльянс» в Краснодаре предлагает услугу нарколога на дом, обеспечивая пациентам необходимую помощь в любой момент дня и ночи. Наши специалисты готовы оперативно выехать по указанному адресу и предоставить все необходимые медицинские процедуры на месте.
Узнать больше – нарколог на дом срочно в краснодаре
залог под птс авто
infoavtolombard-pts65.ru/kazan.html
займ денег под залог автомобиля
После процедуры пациент чувствует значительное облегчение состояния, улучшение самочувствия и снижение тяги к алкоголю.
Изучить вопрос глубже – http://kapelnica-ot-zapoya-sochi00.ru/kapelnicza-ot-zapoya-czena-sochi/
Услуга “Нарколог на дом” в Уфе охватывает широкий спектр лечебных мероприятий, направленных как на устранение токсической нагрузки, так и на работу с психоэмоциональным состоянием пациента. Комплексная терапия включает в себя медикаментозную детоксикацию, корректировку обменных процессов, а также психотерапевтическую поддержку, что позволяет не только вывести пациента из состояния запоя, но и помочь ему справиться с наркотической зависимостью.
Ознакомиться с деталями – выезд нарколога на дом цена в уфе
написание диплома на заказ заказать дипломная работа
Автоматизированные системы дозирования обеспечивают точное введение лекарственных средств, что минимизирует риск передозировки и побочных эффектов. Постоянный мониторинг жизненных показателей позволяет оперативно корректировать терапию в режиме реального времени, обеспечивая максимальную безопасность процедуры.
Подробнее тут – платный нарколог на дом в уфе
AntiNarcoForum — это онлайн-форум, созданный для тех, кто столкнулся с проблемой алкоголизма или наркомании. Анонимность, индивидуальный подход к каждому пользователю и квалифицированная поддержка делают форум эффективным инструментом в борьбе с зависимостью.
Подробнее тут – семья и зависимый
Экстренная установка капельницы необходима, если пациент находится в состоянии запоя более 2–3 дней или испытывает симптомы тяжелой интоксикации алкоголем:
Подробнее – https://kapelnica-ot-zapoya-sochi00.ru/kapelnicza-ot-zapoya-detoks-sochi
Форум AntiNarcoForum — место, где зависимые и их близкие могут анонимно получить помощь профессионалов и участников сообщества. Здесь обсуждаются эффективные методы лечения зависимостей, личные истории успеха и конкретные советы по выходу из сложных ситуаций.
Подробнее – реабилитация наркозависимости
Кроме того, клиника предлагает долгосрочные программы, включающие как стационарное, так и амбулаторное лечение. Мы понимаем, что восстановление — это не только медицинский процесс, но и важная психологическая поддержка, необходимая пациентам на каждом этапе их пути к выздоровлению.
Исследовать вопрос подробнее – https://тайный-вывод-из-запоя.рф/vyvod-iz-zapoya-cena-v-samare.xn--p1ai
mostbet bukmekerlik [url=http://mostbet4005.ru]mostbet bukmekerlik[/url]
Врач устанавливает внутривенную капельницу, через которую вводятся специально подобранные препараты для очищения организма от алкоголя, восстановления баланса жидкости и нормализации работы всех органов и систем. В течение всей процедуры специалист следит за состоянием пациента и, при необходимости, корректирует терапию.
Изучить вопрос глубже – https://kapelnica-ot-zapoya-sochi00.ru/kapelnicza-ot-zapoya-na-domu-sochi
mostbet uz tennis tikish http://www.mostbet4006.ru
где купить силовые трансформаторы где купить силовые трансформаторы .
AntiNarcoForum — это онлайн-форум, созданный для тех, кто столкнулся с проблемой алкоголизма или наркомании. Анонимность, индивидуальный подход к каждому пользователю и квалифицированная поддержка делают форум эффективным инструментом в борьбе с зависимостью.
Углубиться в тему – какой наркотик вызывает зависимость мгновенно
силовой трансформатор купить силовой трансформатор купить .
цена высоковольтный трансформатор [url=www.airlady.forum24.ru/?1-7-0-00003994-000-0-0-1750405477]цена высоковольтный трансформатор [/url] .
В нашей клинике работают врачи-наркологи, психологи и психиатры с многолетним опытом в лечении зависимостей. Все специалисты регулярно повышают свою квалификацию, участвуя в семинарах и конференциях, чтобы обеспечивать своим пациентам наиболее современное и качественное лечение.
Получить больше информации – https://быстро-вывод-из-запоя.рф/vyvod-iz-zapoya-v-stacionare-v-volgograde.xn--p1ai
AntiNarcoForum — форум помощи при зависимостях, обеспечивающий анонимность и поддержку каждому участнику. Здесь доступны проверенные методики лечения, реальные истории выздоровления и профессиональные рекомендации специалистов для эффективного преодоления зависимости.
Подробнее можно узнать тут – какие рехабы есть
1win. com 1win3008.com
888старз букмекерская контора скачать www. .