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!
Особое внимание в клинике уделяется предотвращению рецидивов. Мы обучаем пациентов навыкам управления стрессом и эмоциональной стабильности, помогая формировать здоровые привычки. Это способствует долгосрочному восстановлению и снижает вероятность возвращения к зависимости.
Выяснить больше – https://медицинский-вывод-из-запоя.рф/vyvod-iz-zapoya-anonimno-v-rostove-na-donu.xn--p1ai/
В современном обществе проблема зависимостей от психоактивных веществ становится всё более острой. Алкоголизм, наркомания и игромания представляют серьёзные угрозы для общественного здоровья и безопасности. На фоне растущей нагрузки на систему здравоохранения Наркологическая клиника “Новый Взгляд” предлагает комплексные решения для людей, страдающих от различных форм зависимости. Мы ориентируемся на индивидуальный подход к каждому пациенту, что позволяет достигать высоких результатов в лечении и реабилитации.
Изучить вопрос глубже – http://тайный-вывод-из-запоя.рф/
Наш подход охватывает все аспекты реабилитации, помогая пациентам справиться с зависимостями и вернуться к полноценной жизни.
Получить дополнительные сведения – http://медицина-вывод-из-запоя.рф
кает кайт Кайт школа СПБ предлагает обучение кайтингу и кайтсёрфингу в живописных местах. Здесь работают опытные инструкторы, которые помогут вам быстро освоить необходимые навыки и уверенно чувствовать себя на воде.
сколько стоит игровой компьютер https://kupit-igrovoj-kompyuter3.ru/ .
мостбет скачать приложение http://www.mostbet4004.ru
клубная музыка 2023 http://www.klubnaya-muzyka30.ru .
Hi there would you mind stating which blog platform you’re using?
I’m going to start my own blog soon but I’m having a
hard time selecting between BlogEngine/Wordpress/B2evolution and Drupal.
The reason I ask is because your design seems different then most blogs and I’m looking for something completely unique.
P.S Sorry for getting off-topic but I had to ask!
my web site :: ดูบอลไลสกอ
купить игровой пк в рассрочку [url=www.kupit-igrovoj-kompyuter3.ru]www.kupit-igrovoj-kompyuter3.ru[/url] .
Мы понимаем уникальность каждого пациента и проводим тщательную диагностику, анализируя его медицинскую историю, психологическое состояние и социальные факторы. На основе полученных данных создаем персональные планы лечения, включающие медикаментозные средства, психотерапию и социальные программы.
Получить больше информации – http://медицинский-вывод-из-запоя.рф/vyvod-iz-zapoya-cena-v-rostove-na-donu.xn--p1ai/
Наркологическая клиника “Возрождение” находится по адресу: ул. Агрономическая, д. 122А, г. Нижний Новгород, Россия. Мы открыты для вас круглосуточно и также предлагаем онлайн-консультации, чтобы сделать наши услуги более доступными.
Исследовать вопрос подробнее – https://медицина-вывод-из-запоя.рф/vyvod-iz-zapoya-cena-v-nizhnem-novgoroge.xn--p1ai/
перепланировка квартиры дизайн проект https://www.proekt-pereplanirovki-kvartiry13.ru .
клубные сеты миксы klubnaya-muzyka30.ru .
Мы активно используем методы, такие как когнитивно-поведенческая терапия, гештальт-терапия и арт-терапия, помогая пациентам преодолеть психологические травмы и внутренние конфликты, лежащие в основе аддиктивного поведения. Также наши консультанты по химической зависимости предоставляют информационную поддержку пациентам и их семьям, помогая разобраться в вопросах лечения, реабилитации и социальной адаптации.
Детальнее – https://надежный-вывод-из-запоя.рф/vyvod-iz-zapoya-cena-v-voronezhe.xn--p1ai/
you’re in point of fact a good webmaster. The web site loading
speed is amazing. It seems that you’re doing any distinctive trick.
In addition, The contents are masterwork. you have performed a fantastic job in this topic!
проект перепланировки заказать proekt-pereplanirovki-kvartiry13.ru .
автомобиль под залог
e-avtolombard-pts65.ru/kazan.html
автоломбард под птс в казани
Крайне рекомендую https://mercadoarte.com.ar/2021/08/17/imactions-sorprende-con-sus-disenos-web-a-medida-desarrollados-en-wordpress/
Зависимость — это коварное хроническое заболевание, затрагивающее как физическое, так и психическое здоровье человека. Она воздействует на волю и разум, искажает восприятие реальности и разрушает жизни, семьи и судьбы. Алкоголизм, наркомания и игровая зависимость — все это проявления одной и той же проблемы, требующей комплексного и профессионального подхода.
Подробнее можно узнать тут – http://
клубные ремиксы 2023 скачать [url=https://klubnaya-muzyka30.ru/]https://klubnaya-muzyka30.ru/[/url] .
заказать перепланировку квартиры в москве [url=proekt-pereplanirovki-kvartiry13.ru]proekt-pereplanirovki-kvartiry13.ru[/url] .
1win download [url=http://1win3003.com]http://1win3003.com[/url]
It’s awesome in favor of me to have a web site, which is useful designed for my knowledge.
thanks admin
В этом обзоре представлены различные методы избавления от зависимости, включая терапевтические и психологические подходы. Мы сравниваем их эффективность и предоставляем рекомендации для тех, кто хочет вернуться к трезвой жизни. Читатели смогут найти информацию о реабилитационных центрах и поддерживающих группах.
Выяснить больше – https://kazguki.ru/chto-delaet-narkologicheskuyu-kliniku-v-sankt-peterburge-takim-nadezhnym-vyborom.html
Мы также уделяем большое внимание социальной адаптации. Пациенты учатся восстанавливать навыки общения и обретать уверенность в себе, что помогает в будущем избежать рецидивов и успешно вернуться к полноценной жизни, будь то работа или учеба.
Детальнее – https://быстро-вывод-из-запоя.рф/vyvod-iz-zapoya-anonimno-v-volgograde.xn--p1ai/
Yo forum friends, I’m Ivan from Croatia. I wanna tell you about my insane experience with this unreal online casino I stumbled on not long ago.
To be honest, I was struggling badly, and now I can’t believe it myself — I cashed out £590,000 playing mostly slots!
Now I’m thinking of getting a new car here in Split, and investing a serious chunk of my winnings into Toncoin.
Later I’ll probably move to a better neighborhood and retire early.
Now I’m going by Andrei from Romania because I honestly feel
like a new person. My life is flipping upside down in the best way.
I gotta ask, what would you guys do if you had this kinda luck?
Are you thinking “damn!” right now?
For real, I never thought I’d be able to help my family.
It’s all happening so fast!
Let’s talk crypto too!
автоломбард под залог птс
e-avtolombard-pts65.ru/kazan.html
наличные под залог автомобиля
Этот информационный материал привлекает внимание множеством интересных деталей и необычных ракурсов. Мы предлагаем уникальные взгляды на привычные вещи и рассматриваем вопросы, которые волнуют общество. Будьте в курсе актуальных тем и расширяйте свои знания!
Разобраться лучше – https://brandonnapaintingandcleaning.com/2020/08/25/construction-industry-as-their-over-draft-4
I for all time emailed this blog post page to all my associates, since
if like to read it next my contacts will too.
Its not my first time to pay a quick visit this web
site, i am browsing this web site dailly and obtain nice facts
from here all the time.
Can I simply just say what a relief to discover someone that genuinely understands what they are discussing on the net.
You certainly know how to bring a problem to light and make
it important. More and more people should check this out and understand this side of your story.
I was surprised you’re not more popular since you most certainly
have the gift.
Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех!
Разобраться лучше – https://angalitza.com/kak-vzjat%D1%8C-obeshhannyj-platezh-rostelekom-na
Remarkable! Its really amazing post, I have got much clear idea regarding from this article.
If some one desires to be updated with most recent technologies therefore he must be visit
this site and be up to date everyday.
Эта информационная публикация освещает широкий спектр тем из мира медицины. Мы предлагаем читателям ясные и понятные объяснения современных заболеваний, методов профилактики и лечения. Информация будет полезна как пациентам, так и медицинским работникам, желающим поддержать уровень своих знаний.
Подробнее тут – https://ketokotleta.ru/the_articles/lecheniya-alkogolnoy-zavisimosti.html
Этот краткий обзор предлагает сжатую информацию из области медицины, включая ключевые факты и последние новости. Мы стремимся сделать информацию доступной и понятной для широкой аудитории, что позволит читателям оставаться в курсе актуальных событий в здравоохранении.
Получить дополнительную информацию – https://varikostop.ru/chto-takoe-chastnaya-skoraya-pomoshh-i-kakovy-ee-preimushhestva.html
В данной обзорной статье представлены интригующие факты, которые не оставят вас равнодушными. Мы критикуем и анализируем события, которые изменили наше восприятие мира. Узнайте, что стоит за новыми открытиями и как они могут изменить ваше восприятие реальности.
Углубиться в тему – http://www.ahoracasa.es/fondopie
В этой публикации мы сосредоточимся на интересных аспектах одной из самых актуальных тем современности. Совмещая факты и мнения экспертов, мы создадим полное представление о предмете, которое будет полезно как новичкам, так и тем, кто глубоко изучает вопрос.
Изучить вопрос глубже – https://meta.earth/hello-world
Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех!
Узнать больше – http://marketingsimreneeonline.cf/post/34
Мы предлагаем документы любых учебных заведений, которые находятся на территории всей РФ. Приобрести диплом любого университета:
bgclubgirls.copiny.com/question/details/id/1113545
Мы изготавливаем дипломы психологов, юристов, экономистов и любых других профессий по доступным тарифам. Мы можем предложить документы ВУЗов, расположенных в любом регионе Российской Федерации. Документы печатаются на “правильной” бумаге высшего качества. Это позволяет делать настоящие дипломы, не отличимые от оригиналов. orikdok-v-gorode-moskva-77.online
мостбет бк вход https://mostbet4016.ru
Купить документ о получении высшего образования вы можете в нашей компании в столице. Купить диплом университета по невысокой цене можно, обращаясь к надежной специализированной фирме. backshowtime.ru/kupit-diplom-s-ofitsialnyim-blankom-goznak-bez-posrednikov
Эта разъяснительная статья содержит простые и доступные разъяснения по актуальным вопросам. Мы стремимся сделать информацию понятной для широкой аудитории, чтобы каждый смог разобраться в предмете и извлечь из него максимум пользы.
Узнать больше – https://kaedehair.com/2020/11/19/%E3%81%8A%E6%B0%97%E3%81%AB%E5%85%A5%E3%82%8A
I’m amazed, I must say. Seldom do I encounter
a blog that’s equally educative and amusing, and without a doubt, you have
hit the nail on the head. The problem is something that too
few men and women are speaking intelligently about. I am very happy that I stumbled across this in my hunt for something concerning this.
Приобрести документ университета можно у нас в столице. Заказать диплом института по доступной стоимости возможно, обращаясь к проверенной специализированной фирме. l-avt.ru/support/dialog/PAGE_NAME=profile_view&UID=113869
Мы готовы предложить дипломы любой профессии по доступным ценам. Мы готовы предложить документы ВУЗов, расположенных в любом регионе России. Дипломы и аттестаты выпускаются на бумаге высшего качества. Это дает возможности делать государственные дипломы, которые невозможно отличить от оригиналов. orikdok-2v-gorode-tolyatti-63.ru
Мы можем предложить документы институтов, расположенных на территории всей Российской Федерации. Приобрести диплом любого ВУЗа:
eczadepocularidernegi.org/kachestvennye-diplomy-dlja-vashego-uspeha-96
В обзорной статье вы найдете собрание важных фактов и аналитики по самым разнообразным темам. Мы рассматриваем как современные исследования, так и исторические контексты, чтобы вы могли получить полное представление о предмете. Погрузитесь в мир знаний и сделайте шаг к пониманию!
Подробнее тут – https://www.progettodiciotto.it/index.php/component/k2/item/3-et-accusamus-et-iusto-odio?limit=10&start=72100
займ под залог автомобиля
e-avtolombard-pts65.ru/kemerovo.html
автоломбард