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!
Hi! This is kind of off topic but I need some advice from an established blog.
Is it difficult to set up your own blog? I’m not very techincal
but I can figure things out pretty fast. I’m thinking about creating my own but I’m not sure
where to start. Do you have any ideas or suggestions?
Thanks
Наркологическая клиника “Чистый Путь” — это специализированное медицинское учреждение, предоставляющее помощь людям, страдающим от алкогольной и наркотической зависимости. Наша цель — помочь пациентам справиться с зависимостью, вернуться к здоровой и полноценной жизни, используя эффективные методы лечения и всестороннюю поддержку.
Получить больше информации – https://срочно-вывод-из-запоя.рф/
goobet
Комплексная терапия при выводе из запоя на дому включает в себя два основных направления: медикаментозную детоксикацию и психологическую поддержку. Такой подход позволяет добиться быстрого и устойчивого эффекта, минимизируя риск осложнений и обеспечивая долгосрочную ремиссию.
Углубиться в тему – вызов нарколога на дом в уфе
goobet
goobet
Thanks for sharing your info. I truly appreciate your efforts and I am waiting for your further write ups thanks once again.
Dismemberment
Обращение за помощью на дому имеет ряд неоспоримых преимуществ, особенно для тех, кто ценит конфиденциальность и стремится избежать дополнительных стрессовых факторов, связанных с посещением клиники:
Углубиться в тему – https://narcolog-na-dom-ufa00.ru/narkolog-na-dom-kruglosutochno-ufa/
AntiNarcoForum — анонимное сообщество помощи людям, страдающим от алкогольной, наркотической и игровой зависимости. На платформе доступны истории выздоровления, консультации специалистов, а также постоянная поддержка от людей, преодолевших схожие трудности.
Выяснить больше – освобождение от созависимости
займы онлайн без процентов https://zajmy-onlajn.ru
займ под птс без посещения офиса
infoavtolombard-pts65.ru/nsk.html
кредит под птс автомобиля в новосибирске
Услуга “Нарколог на дом” в Уфе охватывает широкий спектр лечебных мероприятий, направленных как на устранение токсической нагрузки, так и на работу с психоэмоциональным состоянием пациента. Комплексная терапия включает в себя медикаментозную детоксикацию, корректировку обменных процессов, а также психотерапевтическую поддержку, что позволяет не только вывести пациента из состояния запоя, но и помочь ему справиться с наркотической зависимостью.
Ознакомиться с деталями – частный нарколог на дом уфа
goobet
My programmer is trying to persuade me to move to .net from PHP.
I have always disliked the idea because of the expenses.
But he’s tryiong none the less. I’ve been using Movable-type on numerous websites forr about a year and am
worried about switching to another platform. I have heard excellent things about blogengine.net.
Is there a way I can transfer all my wordpress posts into it?
Any help would be greatly appreciated!
Процесс вывода из запоя капельничным методом организован по строгой схеме, позволяющей обеспечить максимальную эффективность терапии. Каждая стадия направлена на комплексное восстановление организма и минимизацию риска осложнений.
Изучить вопрос глубже – http://kapelnica-ot-zapoya-tyumen0.ru
goobet
Наркологическая клиника “Чистый Путь” — это специализированное медицинское учреждение, предоставляющее помощь людям, страдающим от алкогольной и наркотической зависимости. Наша цель — помочь пациентам справиться с зависимостью, вернуться к здоровой и полноценной жизни, используя эффективные методы лечения и всестороннюю поддержку.
Ознакомиться с деталями – https://срочно-вывод-из-запоя.рф/vyvod-iz-zapoya-v-stacionare-v-chelyabinske.xn--p1ai
goobet
Пациенты, которые обращаются в нашу клинику за наркологической помощью, получают не просто стандартное лечение, а комплексный подход к проблеме зависимости. Наши врачи имеют большой практический опыт и высокую квалификацию, благодаря чему могут эффективно справляться даже с самыми сложными случаями. Мы используем только проверенные методики и сертифицированные препараты, гарантирующие безопасность и эффективность лечения.
Разобраться лучше – вызов нарколога на дом сочи
Клиника «Центр реабилитации «Свет Надежды» – специализированное учреждение, предоставляющее профессиональную помощь пациентам, страдающим от алкогольной и наркотической зависимости. Наша главная цель – помощь людям в преодолении зависимости и возвращении к здоровому образу жизни с применением современных методик реабилитации и индивидуального подхода.
Узнать больше – https://быстро-вывод-из-запоя.рф/vyvod-iz-zapoya-v-kruglosutochno-v-volgograde.xn--p1ai
mostbet lisenziyasi uz https://www.mostbet4009.ru
Hey folks, I’m Marko from Serbia. I wanna tell you about my insane experience with this crazy popular online
casino I stumbled on this spring.
To be honest, I was barely affording rent, and now I can’t believe it myself — I
crushed it and made $712,000 playing mostly slots!
Now I’m thinking of buying a boat here in Warsaw, and investing a serious chunk of my winnings into Bitcoin.
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.
I gotta ask, what would you guys do if you had this kinda luck?
Are you feeling curious right now?
For real, I never thought I’d be able to help my family.
It’s all happening so fast!
Feel free to DM me!
Thank you for the good writeup. It in fact was a amusement account it.
Look advanced to far added agreeable from you! However,
how can we communicate?
Форум AntiNarcoForum — место, где зависимые и их близкие могут анонимно получить помощь профессионалов и участников сообщества. Здесь обсуждаются эффективные методы лечения зависимостей, личные истории успеха и конкретные советы по выходу из сложных ситуаций.
Изучить вопрос глубже – Форум о зависимостях, лечении и реабилитации «AntiNarcoForum»
псков диплом купить http://arus-diplom6.ru .
Magnificent beat ! I would like to apprentice while you amend your
web site, how could i subscribe for a blog website? The account aided me a acceptable
deal. I had been tiny bit acquainted of this your broadcast provided bright clear idea
If some one wishes to be updated with most recent technologies after that
he must be visit this web site and be up to date all the time.
мфо без отказа мфо без отказа .
где можно взять кредит без отказа где можно взять кредит без отказа .
I’ve been dealing with knee pain for years, and it’s encouraging
to hear so many positive reviews about Ageless Knees.
Improved mobility and less pain would be life-changing—definitely considering giving this
program a try!
mostbet скачать mostbet скачать
Вы покупаете документ через надежную и проверенную временем компанию. Купить диплом о высшем образовании– [url=http://seo-elita.ru/kupit-diplom-v-moskve-s-zaneseniem-v-reestr-bistro/]seo-elita.ru/kupit-diplom-v-moskve-s-zaneseniem-v-reestr-bistro/[/url]
goobet
Основное направление работы клиники – это комплексный подход, который включает медицинское лечение, психотерапию и социальную реабилитацию. Мы понимаем, что зависимость затрагивает не только физическое состояние, но и психологическое, поэтому используем методики когнитивно-поведенческой терапии, семейные консультации и групповые занятия. Такой подход помогает пациентам не только преодолеть зависимость, но и разобраться с её причинами и справиться с психологическими трудностями.
Углубиться в тему – http://быстро-вывод-из-запоя.рф/vyvod-iz-zapoya-cena-v-volgograde.xn--p1ai/
купить аттестат в красноярске купить аттестат в красноярске .
I think everything published was very reasonable. But, what about this? suppose you were to write a awesome headline? I mean, I don’t want to tell you how to run your website, but what if you added a headline that makes people want more? I mean %BLOG_TITLE% is a little plain. You ought to look at Yahoo’s home page and note how they write post headlines to grab viewers to open the links. You might try adding a video or a pic or two to get people interested about what you’ve got to say. Just my opinion, it would bring your blog a little livelier.
Weapon
Мы активно используем методы, такие как когнитивно-поведенческая терапия, гештальт-терапия и арт-терапия, помогая пациентам преодолеть психологические травмы и внутренние конфликты, лежащие в основе аддиктивного поведения. Также наши консультанты по химической зависимости предоставляют информационную поддержку пациентам и их семьям, помогая разобраться в вопросах лечения, реабилитации и социальной адаптации.
Исследовать вопрос подробнее – https://надежный-вывод-из-запоя.рф/vyvod-iz-zapoya-na-domu-v-voronezhe.xn--p1ai
goobet
goobet
goobet
Hi, constantly i used to check website posts here in the early hours in the morning, since i enjoy to learn more and more.
Terrorism
Портал Киева https://u-misti.kyiv.ua новости и события в Киеве сегодня.
Команда клиники “Аура Здоровья” состоит из опытных и квалифицированных врачей-наркологов, обладающих глубокими знаниями фармакологии и психотерапии. Они регулярно повышают свою квалификацию, участвуя в профессиональных конференциях и семинарах, чтобы применять самые эффективные методы лечения.
Выяснить больше – http://
Как отмечают наркологи нашей клиники, чем раньше пациент получает необходимую помощь, тем меньше риск тяжелых последствий и тем быстрее восстанавливаются функции организма.
Изучить вопрос глубже – капельница от запоя на дому сочи.
Выезд врача-нарколога из клиники «ТрезвоПрофи» на дом происходит в любое время суток, включая выходные и праздники. Перед началом детоксикации врач проводит осмотр, измеряет давление, частоту пульса, уровень кислорода в крови и подбирает индивидуальную схему лечения. Сама процедура обычно занимает от 1 до 2 часов и проводится под строгим контролем врача.
Подробнее – vyzvat-kapelniczu-ot-zapoya sochi
At this time I am going away to do my breakfast, after having my breakfast coming
again to read additional news.
Мы создаем благоприятные условия для полного выздоровления и восстановления личности каждого пациента. Наша команда разрабатывает индивидуальные программы терапии, учитывая особенности здоровья и психического состояния человека. Лечение строится на научно обоснованных методах, что позволяет нам добиваться высоких результатов.
Получить больше информации – http://быстро-вывод-из-запоя.рф
mostbrt https://www.mostbet4009.ru
Подруга посоветовала кашпо для цветов дизайнерские именно здесь покупать. Говорит, что выбор огромный!
mosbet uz mosbet uz