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 88,168 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 , , ,

88,168 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=www.pereplanirovka-nezhilogo-pomeshcheniya10.ru]www.pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .

  2. It’s perfect time to make some plans for the future and it’s time
    to be happy. I’ve read this post and if I could I
    wish to suggest you few interesting things or tips.

    Perhaps you can write next articles referring to this article.

    I desire to read even more things about it!

    homepage

    13 Oct 25 at 11:35 pm

  3. Suchen Sie Immobilien? Montenegro immobilien von privat kaufen wohnungen, Villen und Grundstucke mit Meerblick. Aktuelle Preise, Fotos, Auswahlhilfe und umfassende Transaktionsunterstutzung.

    Carminenus

    13 Oct 25 at 11:36 pm

  4. перепланировка в нежилом помещении [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru]перепланировка в нежилом помещении[/url] .

  5. rumalaya online

    13 Oct 25 at 11:42 pm

  6. аренда гусеничного мини экскаватора [url=http://www.arenda-mini-ekskavatora-v-moskve-2.ru]аренда гусеничного мини экскаватора[/url] .

  7. разрешение на перепланировку нежилого помещения не требуется [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru]http://pereplanirovka-nezhilogo-pomeshcheniya11.ru[/url] .

  8. brightideaweb – Content feels fresh, helpful, and not overloaded.

    Damien Heist

    13 Oct 25 at 11:48 pm

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

  10. согласование перепланировок нежилых помещений [url=https://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]https://pereplanirovka-nezhilogo-pomeshcheniya11.ru/[/url] .

  11. Website backlinks SEO

    Our services are accessible by the following keywords: website backlinks, search engine optimization links, Google-focused backlinks, link building service, link developer, obtain backlinks, backlinking service, web backlinks, purchase backlinks, Kwork-based backlinks, website backlinks, SEO-focused backlinks.

  12. Получить диплом любого университета мы поможем. Купить аттестат в Тюмени – [url=http://diplomybox.com/kupit-attestat-v-tyumeni/]diplomybox.com/kupit-attestat-v-tyumeni[/url]

    Cazrbeg

    13 Oct 25 at 11:53 pm

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

  14. generic Amoxicillin pharmacy UK: amoxicillin uk – buy penicillin alternative online

    JamesDes

    13 Oct 25 at 11:57 pm

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

  16. Для максимальной эффективности мы предлагаем несколько сценариев — от разового экстренного вмешательства до длительного сопровождения ремиссии. Выбор формата определяется состоянием, анамнезом и целями пациента. Возможен гибридный маршрут: старт на дому, затем — дневной стационар или госпитализация, а после стабилизации — амбулаторное сопровождение.
    Детальнее – [url=https://narkologicheskaya-pomoshch-ramenskoe7.ru/]chastnaya-skoraya-narkologicheskaya-pomoshch[/url]

    AntonioMit

    13 Oct 25 at 11:59 pm

  17. DAGA 88 대한민국에 오신 것을 환영합니다 –
    당신의 승리, 전액 지급. 지금 바로 매력적인 보너스를 받고,
    최고의 게임을 즐기며, 믿을 수 있고 편리한 온라인 베팅 경험을 시작하세요!

  18. Sou viciado no fluxo de Brazino Casino, explode com uma vibe aquatica eletrizante. A selecao de titulos e uma correnteza de emocoes. com caca-niqueis que reluzem como perolas. O time do cassino e digno de um capitao de navio. garantindo suporte direto e sem correntezas. Os pagamentos sao seguros e fluidos. em alguns momentos as ofertas podiam ser mais generosas. Em resumo, Brazino Casino e um recife de emocoes para os mergulhadores do cassino! E mais o site e uma obra-prima de estilo subaquatico. dando vontade de voltar como uma onda.
    brazino777 apuestas|

    whimsybubblecrab6zef

    14 Oct 25 at 12:02 am

  19. узаконивание перепланировки нежилого помещения [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]узаконивание перепланировки нежилого помещения[/url] .

  20. Greɑt post. Ι was checking constantly this blog and I am impressed!

    Extremely usefuⅼ informаtion рarticularly the lasst part 🙂 Ι care for such informatiοn a lⲟt.

    I wаs loօking for this paгticular information foг
    a very long time. Thank you аnd good luck.

    My blog :: jc math tuition serangoon

  21. согласование перепланировки в нежилом здании [url=www.pereplanirovka-nezhilogo-pomeshcheniya9.ru]www.pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .

  22. потолки в самаре [url=https://www.stretch-ceilings-samara-1.ru]потолки в самаре[/url] .

  23. If some one needs expert view regarding running a blog then i propose him/her to
    pay a visit this blog, Keep up the nice work.

    Hobicode

    14 Oct 25 at 12:06 am

  24. I’m gone to convey my little brother, that he should also visit
    this web site on regular basis to take updated from hottest
    gossip.

    K88

    14 Oct 25 at 12:07 am

  25. Wow, mega Plattform! Sehr professionell, Glückwunsch ans Team!

    linneasky onlyfans leak

  26. перепланировка нежилого помещения в москве [url=http://www.pereplanirovka-nezhilogo-pomeshcheniya11.ru]перепланировка нежилого помещения в москве[/url] .

  27. Brentsek

    14 Oct 25 at 12:11 am

  28. Backlinks for your site
    Effective in every area of the resource.

    I build backlinks to your site.

    These backlinks draw in indexing bots to the resource, something that significantly impacts for ranking, thus it is essential to promote a resource that does not have errors that obstruct ranking.

    Posting is secure for your domain!

    I avoid filling in contact forms, (contact forms are harmful the domain because of reports from the owners).

    Placement is performed in allowed areas.

    Links are posted to their latest continuously refreshed list. Several portals in the list.

  29. Greetings, There’s no doubt that your website could possibly be having web
    browser compatibility problems. Whenever I take a look at your site in Safari, it looks fine however, when opening in Internet
    Explorer, it has some overlapping issues. I just wanted
    to give you a quick heads up! Apart from that, excellent
    site!

    Puro Tradelux

    14 Oct 25 at 12:12 am

  30. компания потолочник [url=http://natyazhnye-potolki-samara-1.ru]http://natyazhnye-potolki-samara-1.ru[/url] .

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

  32. жалюзи для пластиковых окон с электроприводом [url=http://www.zhalyuzi-s-elektroprivodom77.ru]http://www.zhalyuzi-s-elektroprivodom77.ru[/url] .

  33. готовые рулонные шторы купить в москве [url=rulonnaya-shtora-s-elektroprivodom.ru]готовые рулонные шторы купить в москве[/url] .

  34. Sou viciado no codigo de PlayPix Casino, tem uma energia de jogo tao vibrante quanto um codigo binario em furia. A selecao de titulos e um buffer de prazeres. incluindo mesas com charme de algoritmo. Os agentes sao rapidos como um download. assegurando apoio sem erros. Os pagamentos sao lisos como um buffer. porem mais giros gratis seriam vibrantes. Em sintese, PlayPix Casino vale explorar esse cassino ja para os viciados em emocoes de cassino! De lambuja o design e um espetaculo visual de matriz. amplificando o jogo com vibracao digital.
    saque diГЎrio playpix|

    zapwhirlwindostrich3zef

    14 Oct 25 at 12:15 am

  35. If you want to learn everything about online platforms in the United States, then this is definitely worth checking out. Discover the full details via the link at the bottom of the page:

    best online casino

    FrancisCrymn

    14 Oct 25 at 12:18 am

  36. перепланировка нежилого помещения в нежилом здании законодательство [url=https://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]перепланировка нежилого помещения в нежилом здании законодательство[/url] .

  37. Estou completamente incendiado por Fogo777 Casino, oferece uma aventura que reluz como brasas vivas. O leque do cassino e um fogo de delicias. com caca-niqueis modernos que hipnotizam como fogos. Os agentes sao rapidos como uma faisca. com solucoes precisas e instantaneas. Os pagamentos sao lisos como uma pira. de vez em quando mais giros gratis seriam uma loucura de fogo. Ao final, Fogo777 Casino e o point perfeito pros fas de cassino para quem curte apostar com estilo flamejante! Adicionalmente o visual e uma explosao de chamas. transformando cada aposta em uma aventura flamejante.
    plataforma fogo777 Г© confiГЎvel|

    flamewhirlwindemu2zef

    14 Oct 25 at 12:18 am

  38. Suchen Sie Immobilien? http://www.montenegro-immobilien-kaufen.com wohnungen, Villen und Grundstucke mit Meerblick. Aktuelle Preise, Fotos, Auswahlhilfe und umfassende Transaktionsunterstutzung.

    Carminenus

    14 Oct 25 at 12:19 am

  39. купить диплом в симферополе [url=http://rudik-diplom13.ru/]http://rudik-diplom13.ru/[/url] .

    Diplomi_laon

    14 Oct 25 at 12:19 am

  40. Программы терапии строятся так, чтобы одновременно воздействовать на биологические, психологические и социальные факторы зависимости. Это повышает результативность и уменьшает риск повторного употребления.
    Подробнее – [url=https://narkologicheskaya-klinika-lugansk0.ru/]www.domen.ru[/url]

    Lowellseery

    14 Oct 25 at 12:20 am

  41. можно купить диплом медсестры [url=http://frei-diplom15.ru/]можно купить диплом медсестры[/url] .

    Diplomi_gxoi

    14 Oct 25 at 12:21 am

  42. перепланировка нежилого помещения в москве [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]перепланировка нежилого помещения в москве[/url] .

  43. Suchen Sie Immobilien? Montenegro immobilie kaufen erfahrungen wohnungen, Villen und Grundstucke mit Meerblick. Aktuelle Preise, Fotos, Auswahlhilfe und umfassende Transaktionsunterstutzung.

    Carminenus

    14 Oct 25 at 12:22 am

  44. Hi, i think that i noticed you visited my web site thus i came to return the favor?.I’m trying to
    to find things to enhance my web site!I guess its adequate to
    use some of your concepts!!

    kra42 cc

    14 Oct 25 at 12:23 am

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

  46. Hi! Do you know if they make any plugins to protect against hackers?

    I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

    Lumineux Invexus

    14 Oct 25 at 12:26 am

  47. It is perfect time to make some plans for the long run and it’s time to be happy.

    I’ve learn this publish and if I could I want to counsel you few interesting things or advice.
    Perhaps you can write subsequent articles regarding this article.
    I want to read even more things about it!

    Westrise Corebit

    14 Oct 25 at 12:27 am

  48. Выделяется ряд преимуществ, которые делают терапию в клинике оптимальным решением для борьбы с зависимостью.
    Выяснить больше – [url=https://lechenie-alkogolizma-perm0.ru/]здоровье лечение алкоголизма в перми[/url]

    Francisaxogy

    14 Oct 25 at 12:27 am

  49. Saved as a favorite, I like your site!

    Thanks

    14 Oct 25 at 12:28 am

Leave a Reply