Wanneer casino weer open South Holland

  1. Roulette Wiel: Wed liefde om u een mooie gemakkelijke manier om een overwinning te garanderen wanneer u klikt om te draaien.
  2. Gratis Casino I Mobilen - Rekening houdend met alles, heeft dit Grosvenor beoordeling denk dat deze operator heeft het recht om zichzelf te labelen als de meest populaire casino in het Verenigd Koninkrijk.
  3. Wat Heb Je Nodig Om Bingo Te Spelen: Jagen prooi groter dan zichzelf, terwijl heimelijk negeren van hun vijand early warning systeem is slechts een van de vele coole combinaties in het spel.

Winkans bij loterijen

Wild Spells Online Gokkast Spelen Gratis En Met Geld
We hebben deze download online casino's door middel van een strenge beoordeling proces om ervoor te zorgen dat u het meeste uit uw inzetten wanneer u wint.
Nieuwe Gokkasten Gratis
Dit betekent dat het hangt af van wat inkomstenbelasting bracket je in, en of de winst zal duwen u in een andere bracket.
The delight is de geanimeerde banner met de welkomstpromotie bij de eerste duik je in.

Pokersites voor Enschedeers

Nieuw Casino
De reel set is 7x7, met een totaal van 49 symbolen in het spel.
Casigo Casino 100 Free Spins
Holland Casino Eindhoven is een vestiging waar veel georganiseerd op het gebied van entertainment..
Casino Spel Gratis Slots

Sjoerd Maessen blog

PHP and webdevelopment

PHP hook, building hooks in your application

with 120,247 comments

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!

Written by Sjoerd Maessen

May 23rd, 2011 at 8:02 pm

Posted in API

Tagged with , , ,

120,247 Responses to 'PHP hook, building hooks in your application'

Subscribe to comments with RSS or TrackBack to 'PHP hook, building hooks in your application'.

  1. 648704.com – Loved the layout today; clean, simple, and genuinely user-friendly overall.

    Chau Dunshee

    1 Nov 25 at 12:11 am

  2. купить диплом бухгалтера [url=https://rudik-diplom15.ru/]купить диплом бухгалтера[/url] .

    Diplomi_rvPi

    1 Nov 25 at 12:11 am

  3. MichaelPione

    1 Nov 25 at 12:12 am

  4. диплом колледжа купить диплом юриста [url=www.frei-diplom11.ru]www.frei-diplom11.ru[/url] .

    Diplomi_fqsa

    1 Nov 25 at 12:13 am

  5. организация трансляции [url=https://zakazat-onlayn-translyaciyu4.ru/]организация трансляции[/url] .

  6. Мы обеспечиваем полную поддержку на всех этапах лечения в Ростове-на-Дону, включая реабилитацию и профилактику рецидивов.
    Получить больше информации – [url=https://vyvod-iz-zapoya-rostov115.ru/]врач вывод из запоя ростов-на-дону[/url]

    GeorgeHiB

    1 Nov 25 at 12:14 am

  7. non-prescription medicines UK: Uk Meds Guide – legitimate pharmacy sites UK

    HaroldSHems

    1 Nov 25 at 12:14 am

  8. Hi! Do you know if they make any plugins to safeguard against hackers?
    I’m kinda paranoid about losing everything I’ve worked hard on. Any tips?

    Cenný Finthra

    1 Nov 25 at 12:15 am

  9. best Irish pharmacy websites

    Edmundexpon

    1 Nov 25 at 12:15 am

  10. Списался с данным магазом пару месяцев назад, беру клады по москве, ребята работают отлично, сервис на высоте! Последний раз даже клад сделали минут за 15 всего, первый раз такое, в других магазах приходилось часов по 5 ждать свое клада! Рега тоже отличная, беру JV-90 очень мощная штука! Спасибо ребятам за качественный товар и сервис продолжайте в том же духе!!! купить Кокаин, Мефедрон, Экстази Или вводит всех в заблуждение?!

    StephenZew

    1 Nov 25 at 12:16 am

  11. организация трансляций [url=http://zakazat-onlayn-translyaciyu5.ru/]организация трансляций[/url] .

  12. Kazino təcrübəsi hər yerdə səni gözləyir. blackjack oynamaq
    üçün https://apk.tw/space-uid-7308096.html?do=profile platformasına qoşul.
    Canlı oyunlar real dilerlərlə keçirilir.
    Bonuslar hər depozitə əlavə olunur. İndi başla və əylən.

  13. Having read this I believed it was rather enlightening.
    I appreciate you taking the time and energy to put this informative article together.
    I once again find myself spending a lot of time
    both reading and leaving comments. But so what, it was still
    worth it!

  14. товары для страсти и любви Секс-шоп Erross интим-магазин товаров для взрослых с анонимной доставкой по Москве и РФ.

    GregoryBum

    1 Nov 25 at 12:19 am

  15. This design is spectacular! You definitely know
    how to keep a reader entertained. Between your wwit and your videos, I was almoist movged to start my own log (well, almost…HaHa!) Grest job.
    I really enjoyed what you had to say, and more than that,
    how you presented it. Tooo cool!

    boyarka

    1 Nov 25 at 12:21 am

  16. электрический карниз для штор купить [url=https://elektrokarniz777.ru/]elektrokarniz777.ru[/url] .

  17. голосовое управление жалюзи [url=elektricheskie-zhalyuzi97.ru]elektricheskie-zhalyuzi97.ru[/url] .

  18. 90’lardan gunumuze uzanan guzellik anlay?s?na ?s?k tutan bu rehberle, zaman?n otesine gecen bir tarz elde edin.

    Кстати, если вас интересует Ev Dekorasyonunda Modern ve Estetik Cozumler, загляните сюда.

    Вот, делюсь ссылкой:

    [url=https://evimturk.com]https://evimturk.com[/url]

    90’lar?n buyusunu modern dunyaya tas?mak hic bu kadar kolay olmam?st?. Unutulmayan bu donemin guzellik s?rlar?n? unutmay?n!

    Josephassof

    1 Nov 25 at 12:24 am

  19. Клиника «ЧСП№1» в Ростове-на-Дону предлагает услуги по выводу из запоя. Вы можете выбрать удобный для вас вариант: выезд нарколога на дом или лечение в стационаре. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
    Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-rostov17.ru/]нарколог вывод из запоя в ростове-на-дону[/url]

    FloydDiach

    1 Nov 25 at 12:25 am

  20. стоимость онлайн трансляции на мероприятии [url=https://zakazat-onlayn-translyaciyu4.ru/]https://zakazat-onlayn-translyaciyu4.ru/[/url] .

  21. trusted online pharmacy Ireland

    Edmundexpon

    1 Nov 25 at 12:25 am

  22. заказать онлайн трансляцию [url=https://zakazat-onlayn-translyaciyu5.ru/]заказать онлайн трансляцию[/url] .

  23. купить диплом логиста [url=https://rudik-diplom15.ru]купить диплом логиста[/url] .

    Diplomi_pnPi

    1 Nov 25 at 12:26 am

  24. купить диплом техникума готовый пять плюс [url=frei-diplom11.ru]купить диплом техникума готовый пять плюс[/url] .

    Diplomi_hxsa

    1 Nov 25 at 12:26 am

  25. заказать трансляцию [url=https://zakazat-onlayn-translyaciyu5.ru/]заказать трансляцию[/url] .

  26. I’ll immediately grab your rss as I can’t to find your e-mail subscription hyperlink or newsletter service.
    Do you have any? Kindly let me recognize so that I could subscribe.
    Thanks.

    Kepeltrix

    1 Nov 25 at 12:28 am

  27. 648704.com – Navigation felt smooth, found everything quickly without any confusing steps.

    Ricarda Daste

    1 Nov 25 at 12:29 am

  28. Very energetic article, I enjoyed that bit. Will there be a part 2?

  29. Great site, I recommend it to everyone.[url=https://rolete.md/]rolete md[/url]

    RoleteMd2Nic

    1 Nov 25 at 12:30 am

  30. гардина с электроприводом [url=www.elektrokarniz777.ru]www.elektrokarniz777.ru[/url] .

  31. Safe Meds Guide: best pharmacy sites with discounts – promo codes for online drugstores

    Johnnyfuede

    1 Nov 25 at 12:31 am

  32. best Australian pharmacies: best Australian pharmacies – Aussie Meds Hub Australia

    Johnnyfuede

    1 Nov 25 at 12:32 am

  33. Yes! Finally someone writes about 시알리스 구매.

  34. Excellent site you have here but I was wanting to know if you knew of
    any discussion boards that cover the same topics talked about in this article?
    I’d really love to be a part of community where I can get
    feed-back from other knowledgeable people that share the same interest.

    If you have any suggestions, please let me know.
    Cheers!

    Bextra Dynamic

    1 Nov 25 at 12:33 am

  35. заказать трансляцию конференции [url=www.zakazat-onlayn-translyaciyu5.ru]www.zakazat-onlayn-translyaciyu5.ru[/url] .

  36. организация трансляции мероприятия [url=www.zakazat-onlayn-translyaciyu4.ru/]организация трансляции мероприятия[/url] .

  37. где купить диплом техникума всеми [url=http://www.frei-diplom11.ru]где купить диплом техникума всеми[/url] .

    Diplomi_rqsa

    1 Nov 25 at 12:33 am

  38. В Ростове-на-Дону клиника «ЧСП№1» предоставляет услуги по выводу из запоя. Вы можете заказать выезд нарколога на дом или пройти лечение в стационаре. Все процедуры проводятся анонимно и с соблюдением конфиденциальности.
    Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-rostov28.ru/]вывод из запоя капельница[/url]

    RichardLop

    1 Nov 25 at 12:35 am

  39. I’m not sure where you’re getting your information, but great topic.
    I needs to spend some time learning more or understanding more.
    Thanks for great information I was looking for this information for my mission.

  40. http://aussiemedshubau.com/# best Australian pharmacies

    Haroldovaph

    1 Nov 25 at 12:38 am

  41. карнизы с электроприводом [url=http://elektrokarniz777.ru/]карнизы с электроприводом[/url] .

  42. pharmacy online: verified pharmacy coupon sites Australia – verified pharmacy coupon sites Australia

    Johnnyfuede

    1 Nov 25 at 12:42 am

  43. организация онлайн трансляций москва [url=https://zakazat-onlayn-translyaciyu4.ru/]zakazat-onlayn-translyaciyu4.ru[/url] .

  44. электрожалюзи на заказ [url=http://elektricheskie-zhalyuzi97.ru/]http://elektricheskie-zhalyuzi97.ru/[/url] .

  45. Excellent, what a webpage it is! This weblog presents valuable information to us, keep it up.

    price action

    1 Nov 25 at 12:45 am

  46. заказать трансляцию конференции [url=https://zakazat-onlayn-translyaciyu5.ru/]https://zakazat-onlayn-translyaciyu5.ru/[/url] .

  47. организация онлайн трансляций мероприятий [url=http://www.zakazat-onlayn-translyaciyu5.ru]организация онлайн трансляций мероприятий[/url] .

  48. best online pharmacy [url=https://safemedsguide.com/#]cheapest pharmacies in the USA[/url] cheapest pharmacies in the USA

    Hermanengam

    1 Nov 25 at 12:48 am

  49. купить диплом в невинномысске [url=https://www.rudik-diplom9.ru]купить диплом в невинномысске[/url] .

    Diplomi_gpei

    1 Nov 25 at 12:49 am

  50. Из особенностей — специальная
    защита от ботов, только реальные люди и алгоритм поднимающий страницу выше при более быстрых и активных ответах в переписке.

Leave a Reply