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 91,618 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 , , ,

91,618 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. buy cialis online: discreet ED pills delivery in the US – trusted online pharmacy for ED meds

    AndrewPal

    15 Oct 25 at 9:36 pm

  2. Good blog you have here.. It’s difficult to find excellent writing like yours nowadays.
    I really appreciate individuals like you! Take care!!

  3. These are really enormous ideas in regarding blogging.
    You have touched some pleasant points here. Any way keep up wrinting.

  4. потолки натяжные в нижнем новгороде [url=https://natyazhnye-potolki-nizhniy-novgorod.ru/]https://natyazhnye-potolki-nizhniy-novgorod.ru/[/url] .

  5. студия для самостоятельной записи [url=https://studiya-podkastov-spb.ru]https://studiya-podkastov-spb.ru[/url] .

  6. Greetings I am so glad I found your web site, I really found you by accident, while I
    was searching on Askjeeve for something else, Regardless I am here now and would just
    like to say thank you for a incredible post and a all round entertaining
    blog (I also love the theme/design), I don’t have time to read it all at the minute but I have saved it and also added your RSS feeds, so when I have time I will be back to read much more, Please do keep up the superb jo.

  7. все микрозаймы [url=https://zaimy-28.ru/]все микрозаймы[/url] .

    zaimi_mlKa

    15 Oct 25 at 9:42 pm

  8. Thanks for the good writeup. It actually was once a enjoyment account it.
    Look complex to far introduced agreeable from you!
    By the way, how could we keep in touch?

    Many thanks

    15 Oct 25 at 9:42 pm

  9. студия для съемки подкастов [url=studiya-podkastov-spb.ru]studiya-podkastov-spb.ru[/url] .

  10. bs2web at Интересуешься, что происходит в тёмных уголках сети? Blacksprut — это не просто название, это гарантия анонимности, высокой скорости и надежности. Переходи на bs2best.at — там ты найдёшь то, о чём другие умалчивают. Тебе откроется доступ к информации, которую скрывают от большинства. Только для тех, кто понимает. Без компрометирующих следов. Без уступок. Только Blacksprut. Не упусти шанс узнать первым — bs2best.at уже готов открыть свои двери. Дерзнешь ли ты взглянуть правде в глаза?

    HermanRhype

    15 Oct 25 at 9:46 pm

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

  12. потолочки [url=https://natyazhnye-potolki-nizhniy-novgorod.ru/]https://natyazhnye-potolki-nizhniy-novgorod.ru/[/url] .

  13. Wow! In the end I got a web site from where I know how to
    actually obtain helpful information regarding my study and
    knowledge.

  14. https://tadalifepharmacy.com/# TadaLife Pharmacy

    MervinWoorE

    15 Oct 25 at 9:51 pm

  15. организация прямой трансляции [url=https://zakazat-onlayn-translyaciyu1.ru/]организация прямой трансляции[/url] .

  16. кухни на заказ производство спб [url=https://kuhni-spb-1.ru/]kuhni-spb-1.ru[/url] .

    kyhni spb_bemi

    15 Oct 25 at 9:53 pm

  17. 1win az bonus 500 [url=https://1win5005.com]1win az bonus 500[/url]

    1win_hdml

    15 Oct 25 at 9:53 pm

  18. взять +в аренду экскаватор [url=https://arenda-mini-ekskavatora-v-moskve.ru]https://arenda-mini-ekskavatora-v-moskve.ru[/url] .

  19. потолочкин натяжные потолки отзывы клиентов нижний новгород [url=www.natyazhnye-potolki-nizhniy-novgorod.ru]www.natyazhnye-potolki-nizhniy-novgorod.ru[/url] .

  20. sportwetten tipps für heute

    My web page – wettanbieter ohne einzahlung (Maxie)

    Maxie

    15 Oct 25 at 9:55 pm

  21. wetten pferderennen tipps

    Also visit my blog: wett vorhersage – Florence

    Florence

    15 Oct 25 at 9:57 pm

  22. вывод из запоя омск
    vivod-iz-zapoya-omsk012.ru
    лечение запоя омск

    vivodomskNeT

    15 Oct 25 at 9:57 pm

  23. стоимость онлайн трансляции на мероприятии [url=www.zakazat-onlayn-translyaciyu.ru/]www.zakazat-onlayn-translyaciyu.ru/[/url] .

  24. MichaelSig

    15 Oct 25 at 10:00 pm

  25. потолочкин потолки натяжные отзывы [url=www.stretch-ceilings-nizhniy-novgorod.ru]www.stretch-ceilings-nizhniy-novgorod.ru[/url] .

  26. потолок натяжной [url=http://www.natyazhnye-potolki-nizhniy-novgorod-1.ru]потолок натяжной[/url] .

  27. A motivating discussion is definitely worth comment.
    I do think that you should publish more on this subject, it may not be a taboo matter but generally people do
    not talk about these issues. To the next! All the best!!

    해운대호빠

    15 Oct 25 at 10:02 pm

  28. онлайн трансляция заказать [url=http://zakazat-onlayn-translyaciyu1.ru/]онлайн трансляция заказать[/url] .

  29. заказать кухню спб [url=kuhni-spb-1.ru]kuhni-spb-1.ru[/url] .

    kyhni spb_shmi

    15 Oct 25 at 10:04 pm

  30. натяжные потолки сайт [url=http://www.stretch-ceilings-nizhniy-novgorod-1.ru]натяжные потолки сайт[/url] .

  31. потолка [url=www.natyazhnye-potolki-nizhniy-novgorod.ru]www.natyazhnye-potolki-nizhniy-novgorod.ru[/url] .

  32. The $MTAUR token utility in unlocking special zones is what sets it apart from generic play-to-earn. Presale stage 1 savings are massive, up to 5x value. Team’s experience from top crypto projects adds credibility.
    minotaurus ico

    WilliamPargy

    15 Oct 25 at 10:07 pm

  33. EverettGuemn

    15 Oct 25 at 10:07 pm

  34. With havin so much content and articles do you
    ever run into any problems of plagorism or copyright infringement?
    My blog has a lot of unique content I’ve either created myself or outsourced but it looks like a lot of it is popping it up all over the internet without my
    authorization. Do you know any solutions to help stop content from being
    stolen? I’d certainly appreciate it.

    facer.io

    15 Oct 25 at 10:08 pm

  35. все микрозаймы онлайн [url=http://www.zaimy-28.ru]все микрозаймы онлайн[/url] .

    zaimi_fyKa

    15 Oct 25 at 10:08 pm

  36. EverettGuemn

    15 Oct 25 at 10:08 pm

  37. Обязательно позвонить должны, как позвонят легче забрать самому чем ждать пока курьер доставит
    https://telegra.ph/Kvadrokopter-dji-mavic-3t-kupit-10-13-3
    то-же самое могу сказать!

    MichaelViess

    15 Oct 25 at 10:09 pm

  38. В этой статье мы рассмотрим ключевые признаки эффективной наркологической помощи в Ярославле — от состава команды до подходов в работе с мотивацией пациента.
    Детальнее – https://lechenie-narkomanii-yaroslavl0.ru/

    RichardEsser

    15 Oct 25 at 10:10 pm

  39. Ich liebe die unbandige Kraft von Lowen Play Casino, es verstromt eine Spielstimmung, die wie eine Savanne tobt. Die Spielauswahl im Casino ist wie eine wilde Horde, mit Casino-Spielen, die fur Kryptowahrungen optimiert sind. Der Casino-Service ist zuverlassig und machtig, ist per Chat oder E-Mail erreichbar. Auszahlungen im Casino sind schnell wie ein Raubkatzen-Sprint, aber wurde ich mir mehr Casino-Promos wunschen, die wie ein Feuer lodern. Am Ende ist Lowen Play Casino ein Casino, das man nicht verpassen darf fur Fans moderner Casino-Slots! Zusatzlich die Casino-Navigation ist kinderleicht wie eine Fahrte, einen Hauch von Abenteuer ins Casino bringt.
    lГ¶wen play uetersen|

    zappysquirrel3zef

    15 Oct 25 at 10:10 pm

  40. http://tadalifepharmacy.com/# tadalafil tablets without prescription

    MervinWoorE

    15 Oct 25 at 10:11 pm

  41. Adoro o clima explosivo de JabiBet Casino, oferece uma aventura de cassino que arrasta tudo. O catalogo de jogos do cassino e uma tempestade, incluindo jogos de mesa de cassino cheios de vibe. O suporte do cassino ta sempre na area 24/7, garantindo suporte de cassino direto e sem tempestade. As transacoes do cassino sao simples como uma brisa, as vezes mais bonus regulares no cassino seria top. No geral, JabiBet Casino e o point perfeito pros fas de cassino para os viciados em emocoes de cassino! Vale falar tambem o site do cassino e uma obra-prima de estilo, da um toque de classe aquatica ao cassino.
    jabibet casino|

    zippyoctopus4zef

    15 Oct 25 at 10:11 pm

  42. EverettGuemn

    15 Oct 25 at 10:13 pm

  43. EverettGuemn

    15 Oct 25 at 10:14 pm

  44. студия для самостоятельной записи [url=http://www.studiya-podkastov-spb.ru]http://www.studiya-podkastov-spb.ru[/url] .

  45. Estou pirando com PagolBet Casino, tem uma vibe de jogo que e pura eletricidade. A gama do cassino e simplesmente uma faisca, com slots de cassino unicos e contagiantes. O servico do cassino e confiavel e brabo, dando solucoes na hora e com precisao. Os ganhos do cassino chegam voando como um meteoro, mesmo assim mais bonus regulares no cassino seria top. No fim das contas, PagolBet Casino e o point perfeito pros fas de cassino para os amantes de cassinos online! Alem disso a interface do cassino e fluida e cheia de energia eletrica, torna o cassino uma curticao total.
    pagolbet cassino|

    zanyflamingo2zef

    15 Oct 25 at 10:14 pm

  46. натяжные потолки сайт [url=natyazhnye-potolki-nizhniy-novgorod.ru]natyazhnye-potolki-nizhniy-novgorod.ru[/url] .

  47. Ich bin fasziniert von SpinBetter Casino, es bietet einen einzigartigen Kick. Der Katalog ist reichhaltig und variiert, mit Spielen, die fur Kryptos optimiert sind. Der Service ist von hoher Qualitat, verfugbar rund um die Uhr. Die Gewinne kommen prompt, ab und an mehr Rewards waren ein Plus. Alles in allem, SpinBetter Casino ist ein Muss fur alle Gamer fur Krypto-Enthusiasten ! Hinzu kommt die Navigation ist kinderleicht, erleichtert die gesamte Erfahrung. Hervorzuheben ist die schnellen Einzahlungen, die Vertrauen schaffen.
    spinbettercasino.de|

    ChillgerN4zef

    15 Oct 25 at 10:16 pm

  48. Сначала врач проводит экспресс-диагностику. Измеряются давление, пульс, сатурация, температура, оценивается неврологический статус и уровень обезвоживания. Уточняются аллергии, хронические заболевания, длительность и объём употребления, принимаемые препараты. При необходимости выполняется ЭКГ, чтобы исключить острые риски со стороны сердечно-сосудистой системы.
    Получить дополнительные сведения – https://narkolog-na-dom-krasnogorsk6.ru/

    JosephVem

    15 Oct 25 at 10:20 pm

  49. 1win app qeydiyyat [url=1win5004.com]1win5004.com[/url]

    1win_ocoi

    15 Oct 25 at 10:21 pm

  50. Thanks a bunch for sharing this with all of us you actually
    realize what you’re speaking about! Bookmarked. Please also talk over with my web site =).
    We can have a link exchange contract between us

Leave a Reply