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!
мостбет вход, регистрация mostbet11010.ru
cargo shipping companies in uae China to Dubai: Building Trust and Transparency in Trade
После важного проекта решила побаловать себя — заслужила. Заказала бутылку розового на http://cse.google.az/url?sa=t&url=https://alcoclub25.ru/ , просто чтобы почувствовать вкус жизни. Привезли быстро, всё оригинальное, по цене — доступно. Налив бокал, поняла, как важно уметь радовать себя. Спасибо за сервис, который чувствует настроение.
Заказать диплом института по доступной цене возможно, обращаясь к проверенной специализированной фирме. Мы оказываем услуги по продаже документов об окончании любых ВУЗов России. Купить диплом ВУЗа– [url=http://ngkh.flybb.ru/viewtopic.php?f=2&t=328&sid=549447f0803e82aac0687cb2dfc5248d/]ngkh.flybb.ru/viewtopic.php?f=2&t=328&sid=549447f0803e82aac0687cb2dfc5248d[/url]
Мы предлагаем максимально быстро заказать диплом, который выполняется на оригинальном бланке и заверен мокрыми печатями, штампами, подписями. Диплом пройдет любые проверки, даже с использованием профессиональных приборов. [url=http://kazh.net/read-blog/2763_skolko-stoit-kupit-attestat-11-klassa.html/]kazh.net/read-blog/2763_skolko-stoit-kupit-attestat-11-klassa.html[/url]
This is very interesting, You are a very skilled blogger. I
have joined your feed and look forward to seeking more of your wonderful post.
Also, I have shared your web site in my social networks!
Перевод документов https://medicaltranslate.ru на немецкий язык для лечения за границей и с немецкого после лечения: высокая скорость, безупречность, 24/7
Закажите такси аэропорт Кишинёв, Молдова онлайн или по телефону. Подача точно в срок, чистые авто, русскоязычные водители. Надёжный трансфер по Молдове 24/7.
Very nice post. I definitely love this site. Keep writing!
автоломбард процент
zaimpod-pts90.ru/nsk.html
автоломбард новосибирск под залог птс в новосибирске
mostbet вход в личный кабинет mostbet вход в личный кабинет
пластиковый горшок для цветов напольный https://www.kashpo-napolnoe-spb.ru – пластиковый горшок для цветов напольный .
Онлайн-тренинги https://communication-school.ru и курсы для личного роста, карьеры и новых навыков. Учитесь в удобное время из любой точки мира.
Перевод документов https://medicaltranslate.ru на немецкий язык для лечения за границей и с немецкого после лечения: высокая скорость, безупречность, 24/7
1С без сложностей https://1s-legko.ru объясняем простыми словами. Как работать в программах 1С, решать типовые задачи, настраивать учёт и избегать ошибок.
займ под залог автомобиля
zaimpod-pts90.ru/ekb.html
займ под залог птс екатеринбург
It’s appropriate time to make some plans for the longer term and it’s time to
be happy. I have learn this publish and if I may
just I wish to counsel you some attention-grabbing things or tips.
Maybe you can write next articles referring to this article.
I wish to read even more issues approximately it!
https://dettka.com/piony-s-dostavkoj-po-moskve-krasota-i-udobstvo-v-vashem-dome/ Букет пионов с доставкой в Москве: Совершенный подарок для тех, кто ценит прекрасное. Букет пионов – это не просто цветы, это символ внимания, заботы и любви. Мы создаем уникальные композиции, сочетая различные сорта и оттенки пионов, чтобы каждый букет был настоящим произведением искусства. Доставка букета пионов в Москве – это идеальный способ выразить свои чувства и подарить незабываемые эмоции близкому человеку.
I have been exploring for a little bit for any high quality articles or
blog posts on this kind of space . Exploring in Yahoo I finally stumbled upon this site.
Studying this info So i am satisfied to show that I have an incredibly excellent uncanny feeling I discovered exactly what I needed.
I most for sure will make sure to don?t fail to remember
this site and provides it a look on a continuing basis.
What a stuff of un-ambiguity and preserveness of valuable familiarity
regarding unexpected emotions.
Онлайн-тренинги https://communication-school.ru и курсы для личного роста, карьеры и новых навыков. Учитесь в удобное время из любой точки мира.
теннесси бк скачать на андроид бесплатно теннесси бк скачать на андроид бесплатно
вход в мостбет https://www.mostbet11010.ru
1С без сложностей https://1s-legko.ru объясняем простыми словами. Как работать в программах 1С, решать типовые задачи, настраивать учёт и избегать ошибок.
I loved as much as you’ll receive carried out right here.
The sketch is attractive, your authored material stylish.
nonetheless, you command get bought an impatience over that you wish
be delivering the following. unwell unquestionably come more formerly again as exactly the same nearly
very often inside case you shield this increase.
china to uae Shipping China to UAE: The Future of Logistics and Global Trade
На прием Клинцы. Психотерапевт Киров. 258 оценок
Мы предлагаем дипломы любых профессий по доступным ценам. ЗАДАТЬ ВОПРОС — kyc-diplom.com/discussions.html
This page definitely has all the info I needed concerning this subject and didn’t know who to ask.
effetti collaterali tadalafil 5 mg
Definitely believe that that you said. Your favorite justification seemed to be
at the net the easiest thing to bear in mind of. I say to you, I definitely get irked whilst other folks consider worries that they just do
not recognize about. You controlled to hit the nail upon the top as neatly as outlined out the entire thing with no need side-effects ,
folks can take a signal. Will probably be again to get more.
Thanks
мостбет скачать https://mostbet11011.ru
Pretty nice post. I just stumbled upon your blog and wished to say that
I’ve really enjoyed surfing around your blog posts. In any case I will be subscribing to your rss feed and I hope
you write again very soon!
Feel free to surf to my web-site: OnebetAsia Judi Bola
Гороскоп http://85goelro.ru .
mostbey https://mostbet11010.ru/
Запреты дня http://www.85goelro.ru .
кредит залог птс наличные
zaimpod-pts91.ru/ekb.html
кредит под залог авто без подтверждения дохода
With havin so much content do you ever run into any problems of plagorism or copyright infringement?
My website has a lot of exclusive content I’ve either written myself or outsourced but it seems a lot of it is popping it up
all over the internet without my permission. Do you know any ways to help
reduce content from being ripped off? I’d genuinely appreciate it.
Лунные день сегодня http://actprom.ru .
доставка пионов в москве Пионы Москва: Симфония красок и ароматов в сердце столицы. Пионы – это не просто цветы, это настоящая магия, способная преобразить любой интерьер и подарить хорошее настроение. Москва, как мегаполис, требующий элегантности и изыска, нуждается в такой красоте. Наши пионы выращены с особой заботой, чтобы каждый бутон был наполнен жизненной силой и энергией. Мы предлагаем широкий выбор сортов и оттенков, чтобы удовлетворить самые взыскательные вкусы. Создайте неповторимую атмосферу уюта и роскоши в своем доме или офисе с помощью этих великолепных цветов. Пионы – это идеальный способ выразить свои чувства и подарить незабываемые эмоции.
shipping china to uae Best Cargo Company in UAE: Unveiling Top Providers & Service Excellence
I’m not sure exactly why but this blog is loading extremely slow for me.
Is anyone else having this problem or is it a issue on my end?
I’ll check back later and see if the problem still exists.
Народные приметы https://actprom.ru/ .
Календарь стрижек [url=https://85goelro.ru]https://85goelro.ru[/url] .
центр наркологии телефон наркологии
I’ve tried a few supplements for blood sugar, but none that actually
talk about clearing out the ‘gray mucus’ buildup—GlucoBerry sounds like it’s
addressing the root cause, not just the symptoms!
лучший пансионат для пожилых дом пансионат для пожилых
Пронедра [url=https://www.actprom.ru]https://www.actprom.ru[/url] .
строительное водопонижение строительное водопонижение .
скачать игры с облака mail Наслаждайтесь играми без ограничений, используя прямые ссылки и облачные хранилища.
система водопонижения система водопонижения .