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 90,050 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 , , ,

90,050 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. натяжные потолки самара с установкой [url=http://natyazhnye-potolki-samara-2.ru/]http://natyazhnye-potolki-samara-2.ru/[/url] .

  2. регистрация перепланировки нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya9.ru/]pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .

  3. گیربکس sew – قیمت گیربکس صنعتی –
    خرید گیربکس صنعتی

  4. натяжные потолки потолочкин [url=http://stretch-ceilings-samara.ru/]http://stretch-ceilings-samara.ru/[/url] .

  5. куплю диплом высшего образования [url=https://rudik-diplom9.ru/]куплю диплом высшего образования[/url] .

    Diplomi_ehei

    14 Oct 25 at 8:29 pm

  6. Thank you for some other excellent post. The place else may anyone get that type of
    information in such a perfect manner of writing? I’ve a presentation next week,
    and I am at the search for such information.

    seo

    14 Oct 25 at 8:30 pm

  7. электрокранизы [url=www.elektrokarnizy797.ru/]www.elektrokarnizy797.ru/[/url] .

  8. купить диплом в междуреченске [url=rudik-diplom2.ru]rudik-diplom2.ru[/url] .

    Diplomi_tnpi

    14 Oct 25 at 8:31 pm

  9. натяжные потолки сайт [url=https://stretch-ceilings-samara-1.ru]натяжные потолки сайт[/url] .

  10. самара натяжные потолки [url=natyazhnye-potolki-samara-1.ru]natyazhnye-potolki-samara-1.ru[/url] .

  11. My family members always say that I am killing my time here at net, but I know I am getting experience daily by reading thes nice articles.

    78win

    14 Oct 25 at 8:34 pm

  12. диплом техникум колледж купить [url=frei-diplom11.ru]диплом техникум колледж купить[/url] .

    Diplomi_rzsa

    14 Oct 25 at 8:35 pm

  13. потолки [url=https://stretch-ceilings-samara-1.ru]потолки[/url] .

  14. Refresh Renovation Southwest Charlotte
    1251 Arrow Pine Dr c121,
    Charlotte, NC 28273, United Տtates
    +19803517882
    Studies ideas and renovation case

  15. потолочек су [url=www.stretch-ceilings-samara.ru/]www.stretch-ceilings-samara.ru/[/url] .

  16. регистрация перепланировки нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya9.ru]https://pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .

  17. натяжной потолок в самаре [url=http://natyazhnye-potolki-samara-2.ru]натяжной потолок в самаре[/url] .

  18. Диагностический блок включает сбор анамнеза, оценку витальных показателей, скрининговые шкалы по тревоге, депрессии и патологическому влечению, лабораторные тесты по показаниям. На основании полученных данных выбирается формат помощи и составляется медикаментозная схема с учётом взаимодействий препаратов и вероятных рисков.
    Получить больше информации – [url=https://narkologicheskaya-klinika-v-luganske0.ru/]наркологическая клиника в луганске[/url]

    MichaeldraFe

    14 Oct 25 at 8:41 pm

  19. Выбор методов определяется клинической картиной, коморбидными состояниями и переносимостью препаратов. Ниже представлена сводная структура основных вмешательств и терапевтических целей.
    Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-lugansk0.ru/]врач вывод из запоя луганск[/url]

    Raymondabuck

    14 Oct 25 at 8:41 pm

  20. Да, ссылка на страницу с ее условиями размещена в футере официального сайта.

  21. Для достижения максимального эффекта вывод из запоя в клинике включает несколько этапов. Ниже представлены основные направления, которые применяются в процессе терапии:
    Углубиться в тему – [url=https://vyvod-iz-zapoya-ulan-ude00.ru/]вывод из запоя на дому[/url]

    DonaldVes

    14 Oct 25 at 8:42 pm

  22. купить диплом москва с занесением в реестр [url=http://frei-diplom1.ru/]купить диплом москва с занесением в реестр[/url] .

    Diplomi_zrOi

    14 Oct 25 at 8:43 pm

  23. потолочкин потолки натяжные отзывы [url=https://natyazhnye-potolki-samara-1.ru/]https://natyazhnye-potolki-samara-1.ru/[/url] .

  24. На данном этапе врач уточняет длительность запоя, тип употребляемого алкоголя и наличие сопутствующих заболеваний. Тщательный анализ этих данных позволяет оперативно сформировать индивидуальный план лечения и выбрать оптимальные методы детоксикации.
    Подробнее – http://kapelnica-ot-zapoya-arkhangelsk00.ru

    Stevenunurf

    14 Oct 25 at 8:44 pm

  25. купить диплом в междуреченске [url=http://rudik-diplom6.ru]http://rudik-diplom6.ru[/url] .

    Diplomi_vuKr

    14 Oct 25 at 8:44 pm

  26. диплом техникума купить дешево [url=www.frei-diplom10.ru]диплом техникума купить дешево[/url] .

    Diplomi_blEa

    14 Oct 25 at 8:44 pm

  27. купить диплом в комсомольске-на-амуре [url=http://rudik-diplom15.ru/]купить диплом в комсомольске-на-амуре[/url] .

    Diplomi_ozPi

    14 Oct 25 at 8:44 pm

  28. натяжные потолки дешево самара [url=www.stretch-ceilings-samara-1.ru]натяжные потолки дешево самара[/url] .

  29. best UK online chemist for Prednisolone [url=https://medreliefuk.shop/#]buy corticosteroids without prescription UK[/url] UK chemist Prednisolone delivery

    Jameshoasy

    14 Oct 25 at 8:47 pm

  30. купить диплом в мытищах [url=www.rudik-diplom14.ru/]купить диплом в мытищах[/url] .

    Diplomi_dgea

    14 Oct 25 at 8:47 pm

  31. перепланировка здания [url=https://pereplanirovka-nezhilogo-pomeshcheniya9.ru/]перепланировка здания[/url] .

  32. ПитерКомфорт — это единый центр решений для водоочистки и инженерных систем, где важна эффективность и ресурс. Здесь собран полный спектр решений: фильтры для квартиры и HoReCa, установки обратного осмоса, УФ-обеззараживание, насосные станции ESPA, химия и оборудование для бассейнов, сервисные реагенты для отопления. В центре каталога — проверенные бренды BWT, SFA и другие. Ищете установка для промывки теплообменников? Подробности, акции и консультации — на pitercomfort.ru Поможем выбрать оптимальную систему и оперативно доставим заказ по России — удобно, прозрачно, в нужные сроки.

    tulajiPlowl

    14 Oct 25 at 8:47 pm

  33. Nathanhip

    14 Oct 25 at 8:47 pm

  34. потолочкин [url=http://stretch-ceilings-samara.ru]http://stretch-ceilings-samara.ru[/url] .

  35. электрокарнизы для штор купить [url=http://elektrokarnizy797.ru/]электрокарнизы для штор купить[/url] .

  36. натяжной потолок цена самара [url=www.natyazhnye-potolki-samara-2.ru]натяжной потолок цена самара[/url] .

  37. купить диплом в находке [url=www.rudik-diplom10.ru]купить диплом в находке[/url] .

    Diplomi_ozSa

    14 Oct 25 at 8:50 pm

  38. Just extended my $MTAUR vesting for that 10% bonus—smart play. The audited contracts and cliff mechanisms build trust. Can’t wait to battle crypto monsters in full release.
    mtaur coin

    WilliamPargy

    14 Oct 25 at 8:51 pm

  39. qveknxc

    14 Oct 25 at 8:51 pm

  40. Acho simplesmente brabissimo MegaPosta Casino, da uma energia de cassino que e um vulcao. As opcoes de jogo no cassino sao ricas e vibrantes, com caca-niqueis de cassino modernos e eletrizantes. O suporte do cassino ta sempre na ativa 24/7, acessivel por chat ou e-mail. O processo do cassino e limpo e sem turbulencia, porem as ofertas do cassino podiam ser mais generosas. No fim das contas, MegaPosta Casino oferece uma experiencia de cassino que e puro fogo para os viciados em emocoes de cassino! Alem disso o design do cassino e uma explosao visual braba, o que deixa cada sessao de cassino ainda mais alucinante.
    megaposta bonus codes|

    whackypenguin6zef

    14 Oct 25 at 8:51 pm

  41. My brother recommended I might like this website.
    He was entirely right. This post truly made my day.

    You can not imagine simply how much time I had
    spent for this information! Thanks!

  42. купить диплом в кирово-чепецке [url=http://rudik-diplom9.ru/]http://rudik-diplom9.ru/[/url] .

    Diplomi_piei

    14 Oct 25 at 8:53 pm

  43. order ED pills online UK: viagra – order ED pills online UK

    JamesDes

    14 Oct 25 at 8:54 pm

  44. Acho simplesmente insano OshCasino, oferece uma aventura de cassino que incendeia tudo. Tem uma enxurrada de jogos de cassino irados, com slots de cassino unicos e explosivos. O suporte do cassino ta sempre na ativa 24/7, garantindo suporte de cassino direto e sem cinzas. Os ganhos do cassino chegam voando como um meteoro, porem as ofertas do cassino podiam ser mais generosas. No geral, OshCasino e um cassino online que e uma erupcao de diversao para os amantes de cassinos online! De lambuja a navegacao do cassino e facil como uma trilha vulcanica, torna o cassino uma curticao total.
    osh application mobile|

    zestylizard7zef

    14 Oct 25 at 8:54 pm

  45. потолочкин натяжные потолки самара отзывы [url=natyazhnye-potolki-samara-1.ru]natyazhnye-potolki-samara-1.ru[/url] .

  46. Minotaurus token’s ecosystem ties game, DAO, and rewards seamlessly. ICO phase is buzzing with partnerships forming. As a gamer, I’m all in on this maze adventure.
    minotaurus ico

    WilliamPargy

    14 Oct 25 at 8:54 pm

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

    Diplomi_sysa

    14 Oct 25 at 8:58 pm

  48. Ich bin beeindruckt von SpinBetter Casino, es liefert ein Abenteuer voller Energie. Das Angebot an Spielen ist phanomenal, mit dynamischen Tischspielen. Der Kundenservice ist ausgezeichnet, mit praziser Unterstutzung. Der Ablauf ist unkompliziert, ab und an mehr abwechslungsreiche Boni waren super. In Kurze, SpinBetter Casino ist eine Plattform, die uberzeugt fur Krypto-Enthusiasten ! Hinzu kommt die Plattform ist visuell ein Hit, erleichtert die gesamte Erfahrung. Hervorzuheben ist die schnellen Einzahlungen, die den Einstieg erleichtern.
    spinbettercasino.de|

    SpinMasterZ7zef

    14 Oct 25 at 8:59 pm

  49. натяжные потолки потолочкин [url=http://stretch-ceilings-samara-1.ru]натяжные потолки потолочкин[/url] .

  50. По прибытии проводится экспресс-диагностика: измеряются артериальное давление, пульс, сатурация, температура, оценивается уровень обезвоживания и неврологический статус; при показаниях выполняется ЭКГ. Врач простым языком объясняет, какие препараты и в каком порядке будут вводиться, отвечает на вопросы и получает информированное согласие.
    Детальнее – https://narkolog-na-dom-serpuhov6.ru/vrach-narkolog-na-dom-v-serpuhove

    SamuelClosy

    14 Oct 25 at 9:01 pm

Leave a Reply