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!
займ под залог авто кемерово
zaimpod-pts89.ru/kemerovo.html
займ под залог авто кемерово
When some one searches for his essential thing, thus he/she wishes to be available that in detail, therefore
that thing is maintained over here.
Профессиональный ремонт вашей бытовой техники.
Yo forum friends, I’m Ivan from Croatia. I wanna tell you about my insane experience with this next-level online casino I stumbled on recently.
To be honest, I was totally broke, and now I can’t believe it myself — I hit €1,200,000 playing mostly sports bets!
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 Toncoin.
Later I’ll probably move to a better neighborhood and travel the world.
Now I’m going by Nikola from Serbia because I honestly feel like a new person. My life
is flipping upside down in the best way.
Let’s be honest, what would you guys do if you had this
kinda luck? Are you a bit envious right now?
For real, I never thought I’d have a shot at investing. It’s all happening so fast!
Drop your thoughts below!
аренда авто без залога Краснодар аренда автомобиля: Лучшие предложения по аренде автомобилей в Краснодаре.
This is my first time pay a visit at here and i
am genuinely impressed to read everthing at alone place.
Heya i’m for the first time here. I came across
this board and I find It really useful & it helped me out
a lot. I hope to give something back and aid others like you aided me.
Rent-Auto.md offers car rental in Chisnau and other major cities of Moldova on the best terms. Whether you are planning a business trip, a family vacation or a business trip, we have the perfect solutions for your travel around the city and beyond.
Definitely believe that which you said. Your favorite reason seemed to be on the internet the easiest thing to be aware
of. I say to you, I certainly get irked while people think about worries that they plainly don’t know about.
You managed to hit the nail upon the top as well as defined out the whole
thing without having side effect , people could take a signal.
Will probably be back to get more. Thanks
Visit my page … Packaging Machinery
Наша миссия заключается в предоставлении качественной помощи людям, страдающим от зависимостей. Мы стремимся создать безопасную и поддерживающую атмосферу, где каждый сможет получить необходимую помощь. Основная цель — восстановление здоровья, психоэмоционального состояния и социальной адаптации.
Получить дополнительные сведения – вывод из запоя анонимно в омске
купить диплом о среднем образовании ссср купить диплом о среднем образовании ссср .
медицинский диплом купить в москве медицинский диплом купить в москве .
warface купить Приобретение нового оружия в Warface – это отличный способ улучшить свою статистику, разнообразить игровой процесс и стать более эффективным в бою. Варфейс купить пин код
Заказать диплом любого университета. Заказ документа о высшем образовании через надежную фирму дарит ряд преимуществ для покупателя. Такое решение позволяет сэкономить время и значительные средства. orikdok-v-gorode-omsk-55.online
Hey there! I know this is kinda off topic however I’d figured
I’d ask. Would you be interested in trading links or maybe guest authoring a blog article
or vice-versa? My blog discusses a lot of the same subjects
as yours and I think we could greatly benefit from each other.
If you might be interested feel free to send me an email.
I look forward to hearing from you! Great blog by the way!
Мы активно используем методы, такие как когнитивно-поведенческая терапия, гештальт-терапия и арт-терапия, помогая пациентам преодолеть психологические травмы и внутренние конфликты, лежащие в основе аддиктивного поведения. Также наши консультанты по химической зависимости предоставляют информационную поддержку пациентам и их семьям, помогая разобраться в вопросах лечения, реабилитации и социальной адаптации.
Получить больше информации – http://
Hello just wanted to give you a quick heads up. The text in your content seem to be
running off the screen in Chrome. I’m not sure if this is a formatting issue
or something to do with browser compatibility but I figured
I’d post to let you know. The design look great
though! Hope you get the issue fixed soon. Cheers
Купить диплом можно через официальный сайт компании. orikdok-4v-gorode-yaroslavl-76.ru
купить аттестат в екатеринбурге купить аттестат в екатеринбурге .
Заказать диплом о высшем образовании. Приобретение документа о высшем образовании через надежную компанию дарит много плюсов. Это решение дает возможность сэкономить как личное время, так и существенные средства. orikdok-5v-gorode-kaliningrad-39.online
Клиника «Центр реабилитации «Свет Надежды» – специализированное учреждение, предоставляющее профессиональную помощь пациентам, страдающим от алкогольной и наркотической зависимости. Наша главная цель – помощь людям в преодолении зависимости и возвращении к здоровому образу жизни с применением современных методик реабилитации и индивидуального подхода.
Ознакомиться с деталями – https://быстро-вывод-из-запоя.рф/vyvod-iz-zapoya-v-kruglosutochno-v-volgograde.xn--p1ai
Заказать натяжной потолок Карниз для натяжного потолка позволяет скрыть стык между стеной и потолком, а также установить шторы. Натяжной потолок в ванной
Заказать диплом на заказ возможно через сайт компании. orikdok-5v-gorode-rostov-na-donu-61.online
Климатическая техника https://brand-climat.ru для дома и офиса: кондиционеры, рекуператоры, увлажнители и обогреватели, помощь в выборе, установка и гарантийное обслуживание, комфорт и экономия.
Заказать диплом института по выгодной цене возможно, обратившись к надежной специализированной компании. Мы можем предложить документы учебных заведений, которые расположены на территории всей РФ. kupite-diplom0024.ru/kupit-diplom-s-registratsiej-v-reestre-bez-problem/
mostbet. http://mostbet11002.ru/
Мы изготавливаем дипломы любой профессии по невысоким тарифам. Дипломы производятся на настоящих бланках государственного образца Заказать диплом любого института [url=http://diplomd-magazinp.ru/]diplomd-magazinp.ru[/url]
Заказать диплом института по доступной стоимости возможно, обратившись к проверенной специализированной фирме. Мы оказываем услуги по производству и продаже документов об окончании любых университетов России. Заказать диплом о высшем образовании– [url=http://drugisaitove.listbb.ru/ucp.php?mode=login&sid=1bb43bb3c03ac29f41234a40e6a75bb3/]drugisaitove.listbb.ru/ucp.php?mode=login&sid=1bb43bb3c03ac29f41234a40e6a75bb3[/url]
Где приобрести диплом специалиста?
Приобрести диплом института по выгодной стоимости возможно, обратившись к проверенной специализированной фирме.: [url=http://10000diplomov.ru/]10000diplomov.ru[/url]
специализированная онлайн-платформа https://traktorbook.com для покупки, продажи и аренды сельскохозяйственной техники, тракторов, запчастей и оборудования. Сайт объединяет фермеров, аграрные компании и частных продавцов, предлагая удобный интерфейс, фильтры для точного поиска и актуальные объявления со всей страны.
Заказать диплом об образовании. Заказ диплома через надежную компанию дарит ряд достоинств. Такое решение позволяет сберечь как личное время, так и серьезные финансовые средства. [url=http://orikdok-1v-gorode-moskva-77.ru/]orikdok-1v-gorode-moskva-77.ru[/url]
Ремонт бампера автомобиля — это актуальная услуга, которая позволяет восстановить заводской вид транспортного средства после мелких повреждений. Передовые технологии позволяют убрать потертости, трещины и вмятины без полной замены детали. При выборе между ремонтом или заменой бампера https://telegra.ph/Remont-ili-zamena-bampera-05-22 важно рассматривать уровень повреждений и экономическую рентабельность. Профессиональное восстановление включает подготовку, грунтовку и покраску.
Смена бампера требуется при значительных повреждениях, когда ремонт бамперов неэффективен или невозможен. Цена восстановления зависит от материала изделия, характера повреждений и типа автомобиля. Пластиковые элементы поддаются ремонту лучше металлических, а современные композитные материалы требуют специального оборудования. Качественный ремонт продлевает срок службы детали и поддерживает заводскую геометрию кузова.
Без колебаний связаться со мной для поддержки по вопросам Замена бампера мазда 3 2007 – обращайтесь в Telegram ldt16
деньги под залог автомобиля авто остается
proavtolombard-pts65.ru
займ кредит под птс
аттестат купить в красноярске [url=http://arus-diplom5.ru/]http://arus-diplom5.ru/[/url] .
Families and friends of addicts can share their experiences and find help here.
Get more info – personal stories of drug recovery
Купить диплом университета!
Покупка документа о высшем образовании через надежную компанию дарит ряд плюсов. Заказать диплом об образовании у надежной компании: [url=http://doks-v-gorode-cheboksary-21.online/]doks-v-gorode-cheboksary-21.online[/url]
Приобрести диплом под заказ возможно используя официальный сайт компании. [url=http://orikdok-3v-gorode-ekaterinburg-66.ru/]orikdok-3v-gorode-ekaterinburg-66.ru[/url]
скачать приложение 888starz скачать приложение 888starz .
888starz зеркало 888starz зеркало .
Мы можем предложить дипломы любых профессий по приятным тарифам. Для нас важно, чтобы дипломы были доступными для большинства граждан. Приобрести диплом о высшем образовании [url=http://zoshen.com/jobgrant/companies/premialnie-diplom-24/]zoshen.com/jobgrant/companies/premialnie-diplom-24[/url]
аренда машины краснодар Аренда авто без залога: Простое решение для тех, кто ценит мобильность без лишних хлопот. Забудьте о сложных процедурах и крупных депозитах, наслаждайтесь поездкой без лишних финансовых обременений.
После завершения процедур врач дает пациенту и его родственникам подробные рекомендации по дальнейшему восстановлению и профилактике рецидивов.
Изучить вопрос глубже – нарколог на дом клиника
Мы предлагаем дипломы любой профессии по приятным тарифам. Цена может зависеть от выбранной специальности, года получения и образовательного учреждения: [url=http://tavasporan.flybb.ru/viewtopic.php?f=13&t=3632/]tavasporan.flybb.ru/viewtopic.php?f=13&t=3632[/url]
AntiNarcoForum — форум помощи при зависимостях, обеспечивающий анонимность и поддержку каждому участнику. Здесь доступны проверенные методики лечения, реальные истории выздоровления и профессиональные рекомендации специалистов для эффективного преодоления зависимости.
Детальнее – рехабы отзывы пациентов
mostbet app login mostbet app login
888stars http://888starz.com.ru .
бк 888 starz бк 888 starz .
mostbet skachat 2024 http://mostbet4019.ru
Hey folks, I’m Ivan from Croatia. I wanna tell you about my insane experience with this trending 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 cashed out €384,000 playing mostly live roulette!
Now I’m thinking of buying a house here in Belgrade, and investing a serious chunk of my winnings into Cardano.
Later I’ll probably move to a better neighborhood and
retire early.
Now I’m going by Tomasz from Poland because I honestly feel
like a new person. My life is flipping upside down in the best way.
Let’s be honest, what would you guys do if you had this kinda luck?
Are you jealous right now?
For real, I never thought I’d be living this dream. It’s all happening so fast!
Reply if you wanna chat!
мостбет. регистрация. http://mostbet11002.ru