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 113,395 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 , , ,

113,395 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. yourcreativejourney – Good pricing and clear descriptions make me feel confident to buy.

    Kermit Armout

    28 Oct 25 at 6:30 am

  2. клиника наркологическая платная [url=https://narkologicheskaya-klinika-27.ru/]https://narkologicheskaya-klinika-27.ru/[/url] .

  3. купить медицинский диплом с занесением в реестр [url=www.frei-diplom4.ru]купить медицинский диплом с занесением в реестр[/url] .

    Diplomi_lfOl

    28 Oct 25 at 6:30 am

  4. kraken ссылка
    kraken vk2

    Henryamerb

    28 Oct 25 at 6:31 am

  5. наркологическая клиника [url=www.narkologicheskaya-klinika-28.ru]наркологическая клиника[/url] .

  6. Купить диплом техникума в Одесса [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .

    Diplomi_ehea

    28 Oct 25 at 6:32 am

  7. ремонт подвала в частном доме [url=https://gidroizolyaciya-podvala-cena.ru/]https://gidroizolyaciya-podvala-cena.ru/[/url] .

  8. online wetten ohne ausweis

    My site … profi Sportwetten tipps

  9. Обеспечьте комфорт и стиль в вашем доме с [url=https://rulonnye-shtory-umnyy-dom.ru/]электрические жалюзи рулонные Прокарниз[/url], которые идеально впишутся в современный интерьер.
    Автоматические рулонные шторы становятся все более популярными в современных интерьерах. Использование таких штор позволяет не только удобно регулировать свет, но и добавить стиль в ваш дом. Подобные изделия идеально вписываются в концепцию “умного дома”.

    Системы автоматизации позволяют программировать шторы с помощью смартфона. Вы можете задавать график работы штор в зависимости от времени суток. Такой подход очень удобен делает жизнь более комфортной.

    Кроме того, умные рулонные шторы могут быть оснащены датчиками света и температуры. Эти датчики автоматически регулируют положение штор для достижения оптимального уровня освещенности. В результате вы можете экономить на электроэнергии благодаря естественному освещению.

    Процесс установки рулонных штор с автоматизацией достаточно прост и не требует специальных навыков. Вы можете установить их самостоятельно, следуя инструкциям. После установки , вы сможете наслаждаться всеми преимуществами умного дома.

  10. Georgerah

    28 Oct 25 at 6:36 am

  11. кракен
    kraken обмен

    Henryamerb

    28 Oct 25 at 6:37 am

  12. гидроизоляция подвала цена за м2 [url=gidroizolyaciya-cena-7.ru]гидроизоляция подвала цена за м2[/url] .

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

    Diplomi_gvea

    28 Oct 25 at 6:37 am

  14. Georgerah

    28 Oct 25 at 6:37 am

  15. Hey There. I found your blog using msn. This is a really well written article.
    I will make sure to bookmark it and return to read more of your useful info.
    Thanks for the post. I’ll definitely return.

    Result Sydney

    28 Oct 25 at 6:40 am

  16. цена ремонта подвала [url=gidroizolyaciya-cena-7.ru]gidroizolyaciya-cena-7.ru[/url] .

  17. клиника наркологии москва [url=narkologicheskaya-klinika-28.ru]клиника наркологии москва[/url] .

  18. trendyfindsonline – I found a few items I’m considering buying here.

    Trevor Inocencio

    28 Oct 25 at 6:44 am

  19. адреса наркологических клиник [url=https://narkologicheskaya-klinika-28.ru]адреса наркологических клиник[/url] .

  20. You have made some decent points there. I checked on the net to find out more about the issue and found
    most people will go along with your views on this site.

    my site … zinnat02

    zinnat02

    28 Oct 25 at 6:45 am

  21. discovergreatdeals – Checkout was simple and the delivery info looked trustworthy.

    Sherill Bussell

    28 Oct 25 at 6:45 am

  22. наркологический центр москва [url=http://narkologicheskaya-klinika-27.ru]наркологический центр москва[/url] .

  23. кракен даркнет маркет
    кракен

    Henryamerb

    28 Oct 25 at 6:45 am

  24. kraken tor
    kraken обмен

    Henryamerb

    28 Oct 25 at 6:46 am

  25. Great post. I was checking continuously this
    weblog and I am inspired! Extremely useful information specifically the ultimate
    phase 🙂 I deal with such information much.
    I used to be seeking this certain information for a very long time.
    Thank you and good luck.

  26. гидроизоляция цена москва [url=https://gidroizolyaciya-cena-8.ru/]https://gidroizolyaciya-cena-8.ru/[/url] .

  27. dreambuycollection – Overall a positive experience so far; delivery and quality will be key.

    Theo Steber

    28 Oct 25 at 6:47 am

  28. theworldawaits – Quality product visuals make me confident about placing an order.

    Antione Holtberg

    28 Oct 25 at 6:47 am

  29. Для сохранения приватности мы ведём коммуникацию через одного доверенного представителя, используем нейтральные формулировки в документах, а инструкции выдаём в неброском виде. При невозможности создать тишину дома (ремонт, маленькие дети, гости) предложим краткий «тихий» стационар с отдельным входом и камерным режимом, после чего сопровождение вернётся в домашний формат.
    Получить больше информации – [url=https://vyvod-iz-zapoya-v-ekaterinburge16.ru/]наркология вывод из запоя екатеринбург[/url]

    GregoryBlods

    28 Oct 25 at 6:48 am

  30. OMT’ѕ emphasis on error evaluation transforms blunders іnto
    finding out adventures, assisting students drop іn love with math’s flexible
    nature and goal һigh in tests.

    Register tⲟday іn OMT’ѕ standalone e-learning programs and see yoᥙr
    grades soar tһrough limitless access tо tⲟp quality, syllabus-aligned material.

    Singapore’ѕ focus on imρortant thinking through mathematics
    highlights the significance ᧐f math tuition, ѡhich assists trainees develop the analytical abilities required Ьy the nation’ѕ forward-thinking syllabus.

    Tuition programs fоr primary mathematics concentrate оn mistake analysis from past PSLE documents,
    teaching students t᧐ ɑvoid recurring mistakes іn computations.

    Comprehensive insurance coverage ⲟf thе wholе O Level syllabus іn tuition mаkes sure
    no topics, from sets to vectors, ɑre neglected in a student’s
    revision.

    Preparing f᧐r the changability of A Level concerns,
    tuition creаtes flexible analytic ɑpproaches for real-time exam circumstances.

    Τhe diversity of OMT comes from its syllabus that matches MOE’ѕ
    νia interdisciplinary linkѕ, linking mathematics to science
    аnd everyday probⅼem-solving.

    Team forums іn the platform allοw you talk ɑbout witһ peers ѕia,
    mаking clear doubts and enhancing your mathematics performance.

    Tuition in mathematics assists Singapore students establish rate ɑnd accuracy,
    іmportant for completing teats ԝithin timе frame.

    Check ߋut my web blog maths tuition assignments singapore

  31. This is a topic which is near to my heart… Many thanks!

    Where are your contact details though?

    LOTTO CHAMP

    28 Oct 25 at 6:48 am

  32. обмазочная гидроизоляция цена работы [url=http://gidroizolyaciya-cena-8.ru/]обмазочная гидроизоляция цена работы[/url] .

  33. Мы не используем универсальные «сильные капельницы». Эффективность даёт точное совпадение с задачей. Ниже — логика выбора профилей и маркеры, на которые мы ориентируемся при контроле эффективности и безопасности.
    Выяснить больше – [url=https://vivod-iz-zapoya-v-sankt-peterburge16.ru/]вывод из запоя на дому в санкт-петербурге[/url]

    AnthonyOramb

    28 Oct 25 at 6:49 am

  34. ремонт подвала [url=www.gidroizolyaciya-podvala-cena.ru]ремонт подвала[/url] .

  35. наркологическая больница [url=https://narkologicheskaya-klinika-28.ru/]наркологическая больница[/url] .

  36. монтаж стеклянных душевых кабин [url=http://dzen.ru/a/aPaQV60E-3Bo4dfi/]http://dzen.ru/a/aPaQV60E-3Bo4dfi/[/url] .

  37. kraken qr code
    кракен vk2

    Henryamerb

    28 Oct 25 at 6:51 am

  38. ремонт в подвале [url=http://gidroizolyaciya-podvala-cena.ru/]http://gidroizolyaciya-podvala-cena.ru/[/url] .

  39. клиника наркологическая платная [url=http://www.narkologicheskaya-klinika-27.ru]http://www.narkologicheskaya-klinika-27.ru[/url] .

  40. Excellent site you have here but I was wanting to know if you
    knew of any community forums that cover the same topics discussed in this article?

    I’d really like to be a part of group where I can get comments
    from other knowledgeable people that share the same interest.

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

  41. диплом техникума купить с проводкой [url=https://frei-diplom9.ru]диплом техникума купить с проводкой[/url] .

    Diplomi_djea

    28 Oct 25 at 6:53 am

  42. сырость в подвале многоквартирного дома [url=https://gidroizolyaciya-cena-7.ru]https://gidroizolyaciya-cena-7.ru[/url] .

  43. WOW just what I was searching for. Came here by searching for
    assignment help

    assignment writer

    28 Oct 25 at 6:54 am

  44. купить диплом о высшем образовании [url=https://www.rudik-diplom8.ru]купить диплом о высшем образовании[/url] .

    Diplomi_pbMt

    28 Oct 25 at 6:54 am

  45. Обеспечьте комфорт и стиль в вашем доме с [url=https://rulonnye-shtory-umnyy-dom.ru/]автоматические рулонные жалюзи Прокарниз[/url], которые идеально впишутся в современный интерьер.
    Умные рулонные шторы становятся все более популярными в современных интерьерах. Применение автоматических штор позволяет не только удобно регулировать свет, но и добавить стиль в ваш дом. Подобные изделия идеально вписываются в концепцию “умного дома”.

    Системы автоматизации позволяют управлять шторами с помощью смартфона. Владельцы могут задавать график работы штор в зависимости от времени суток. Это удобно делает жизнь более комфортной.

    Кроме того, рулонные шторы с автоматизированным управлением могут быть оснащены датчиками света и температуры. Эти датчики автоматически регулируют положение штор для достижения оптимального уровня освещенности. Таким образом вы можете экономить на электроэнергии благодаря естественному освещению.

    Установка автоматических рулонных штор достаточно прост и не требует специальных навыков. Вы можете установить их самостоятельно, следуя инструкциям. Когда шторы установлены, вы сможете наслаждаться всеми преимуществами умного дома.

  46. Перед перечнем поясним логику: домашний визит уместен, когда обстановка безопасна, риски контролируемы и есть взрослый помощник на вечер и ночь. Ниже — ориентиры, при которых имеет смысл начать с выезда, а не со стационара.
    Подробнее можно узнать тут – [url=https://narkolog-na-dom-voskresensk8.ru/]narkolog-na-dom-voskresensk8.ru/[/url]

    Traviscot

    28 Oct 25 at 6:55 am

  47. купить проведенный диплом моих [url=http://frei-diplom2.ru/]купить проведенный диплом моих[/url] .

    Diplomi_nvEa

    28 Oct 25 at 6:55 am

  48. I’m not that much of a online reader to be honest but your blogs really nice,
    keep it up! I’ll go ahead and bookmark your website to come back later.
    All the best

    雷电模拟器

    28 Oct 25 at 6:56 am

  49. гидроизоляция цена кг [url=http://www.gidroizolyaciya-cena-8.ru]http://www.gidroizolyaciya-cena-8.ru[/url] .

Leave a Reply