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 98,875 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 , , ,

98,875 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://www.proekt-pereplanirovki-kvartiry11.ru]сколько стоит перепланировка квартиры[/url] .

  2. JamesDaync

    20 Oct 25 at 12:28 pm

  3. Do you mind if I quote a few of your posts as long as I provide credit and sources back to your weblog?
    My blog is in the exact same niche as yours and my users would genuinely benefit from a
    lot of the information you provide here. Please let me know if this alright with you.
    Appreciate it!

    j88slot

    20 Oct 25 at 12:28 pm

  4. диплом техникума купить екатеринбург [url=https://frei-diplom11.ru/]диплом техникума купить екатеринбург[/url] .

    Diplomi_qwsa

    20 Oct 25 at 12:30 pm

  5. cialis generika [url=https://potenzvital.com/#]Cialis generika günstig kaufen[/url] Tadalafil 20mg Bestellung online

    GeorgeHot

    20 Oct 25 at 12:30 pm

  6. купить аттестаты за 9 [url=www.rudik-diplom15.ru]купить аттестаты за 9[/url] .

    Diplomi_owPi

    20 Oct 25 at 12:32 pm

  7. Публикация предлагает читателю не просто информацию, а инструменты для анализа и саморазвития. Мы стимулируем критическое мышление, предлагая различные точки зрения и призывая к самостоятельному поиску решений.
    Интересует подробная информация – http://capmeroccitanie.fr/facade-maritime-occitanie-patrimoine-a

    Robertarelo

    20 Oct 25 at 12:33 pm

  8. wettbüro krefeld

    Here is my webpage :: wettanbieter paypal (Bud)

    Bud

    20 Oct 25 at 12:34 pm

  9. There is certainly a great deal to learn about this subject.
    I love all of the points you have made.

    website

    20 Oct 25 at 12:34 pm

  10. EdwardAdete

    20 Oct 25 at 12:37 pm

  11. KevinKinny

    20 Oct 25 at 12:37 pm

  12. EdwardAdete

    20 Oct 25 at 12:38 pm

  13. cd player with clock [url=www.alarm-radio-clocks.com]www.alarm-radio-clocks.com[/url] .

  14. Hey There. I found your blog using msn. This is a very well
    written article. I’ll be sure to bookmark it
    and come back to read more of your useful information. Thanks for the post.
    I will certainly return.

  15. [url=https://rebatemyforex.com/]The RebateMyForex platform [/url]helps forex traders recover part of their trading costs through cash rebates. You can link your existing forex accounts to the platform with just a few clicks and immediately begin earning money back from your trades. Every executed order can bring you additional income. The concept is simple: the more you trade, the more you earn. Whether you’re a beginner or an expert trader, the system adapts to your needs. Users appreciate the fast payments, detailed statistics, and full transparency of their earnings. All transactions are clear, and you always see how much you’ve earned. You can choose from dozens of reputable forex brokers directly inside your account. RebateMyForex also provides useful educational content and trading analytics. Withdrawal methods are flexible and fast, supporting multiple currencies. Many traders call it an essential part of their trading toolkit. Support is always available to help users with registration or broker connection. If you’re serious about forex trading, you shouldn’t miss this opportunity. Its mission is to make forex trading more rewarding and accessible. Create your account and activate your cashback within minutes.
    https://rebatemyforex.com/

    Ralphchect

    20 Oct 25 at 12:39 pm

  16. Everything is very open with a very clear description of
    the issues. It was truly informative. Your website is very useful.

    Many thanks for sharing!

  17. potenzmittel cialis [url=https://potenzvital.com/#]Tadalafil 20mg Bestellung online[/url] cialis kaufen

    GeorgeHot

    20 Oct 25 at 12:43 pm

  18. купить диплом в новом уренгое [url=http://rudik-diplom14.ru/]http://rudik-diplom14.ru/[/url] .

    Diplomi_pxea

    20 Oct 25 at 12:44 pm

  19. купить диплом в оренбурге [url=rudik-diplom2.ru]купить диплом в оренбурге[/url] .

    Diplomi_gupi

    20 Oct 25 at 12:44 pm

  20. NormanmuP

    20 Oct 25 at 12:45 pm

  21. kraken 2025
    kraken вход

    JamesDaync

    20 Oct 25 at 12:46 pm

  22. купить диплом спб колледж [url=frei-diplom8.ru]frei-diplom8.ru[/url] .

    Diplomi_xksr

    20 Oct 25 at 12:47 pm

  23. https://telegra.ph/Consejos-de-Hidrataci%C3%B3n-para-un-Examen-de-Orina-Exitoso-en-Chile-09-11

    Detox para examen de miccion se ha transformado en una solucion cada vez mas conocida entre personas que requieren eliminar toxinas del sistema y superar pruebas de test de drogas. Estos formulas estan disenados para ayudar a los consumidores a purgar su cuerpo de componentes no deseadas, especialmente aquellas relacionadas con el consumo de cannabis u otras drogas.

    Uno buen detox para examen de pipi debe ofrecer resultados rapidos y visibles, en especial cuando el tiempo para limpiarse es limitado. En el mercado actual, hay muchas opciones, pero no todas garantizan un proceso seguro o rapido.

    ?Como funciona un producto detox? En terminos simples, estos suplementos operan acelerando la expulsion de metabolitos y residuos a traves de la orina, reduciendo su nivel hasta quedar por debajo del limite de deteccion de los tests. Algunos trabajan en cuestion de horas y su efecto puede durar entre 4 a seis horas.

    Resulta fundamental combinar estos productos con adecuada hidratacion. Beber al menos par litros de agua al dia antes y despues del ingesta del detox puede mejorar los resultados. Ademas, se sugiere evitar alimentos dificiles y bebidas acidas durante el proceso de preparacion.

    Los mejores productos de limpieza para orina incluyen ingredientes como extractos de naturales, vitaminas del tipo B y minerales que respaldan el funcionamiento de los sistemas y la funcion hepatica. Entre las marcas mas vendidas, se encuentran aquellas que tienen certificaciones sanitarias y estudios de prueba.

    Para usuarios frecuentes de marihuana, se recomienda usar detoxes con tiempos de accion largas o iniciar una preparacion previa. Mientras mas prolongada sea la abstinencia, mayor sera la potencia del producto. Por eso, combinar la organizacion con el uso correcto del detox es clave.

    Un error comun es pensar que todos los detox actuan lo mismo. Existen diferencias en dosis, sabor, metodo de toma y duracion del resultado. Algunos vienen en presentacion liquido, otros en capsulas, y varios combinan ambos.

    Ademas, hay productos que agregan fases de preparacion o limpieza previa al dia del examen. Estos programas suelen sugerir abstinencia, buena alimentacion y descanso adecuado.

    Por ultimo, es importante recalcar que todo detox garantiza 100% de exito. Siempre hay variables personales como metabolismo, frecuencia de consumo, y tipo de examen. Por ello, es vital seguir todas instrucciones del fabricante y no relajarse.

    JuniorShido

    20 Oct 25 at 12:51 pm

  24. I’ve been exploring for a little for any high-quality articles or
    weblog posts on this kind of house . Exploring in Yahoo I at last stumbled upon this
    site. Studying this info So i am glad to exhibit that I have a very good uncanny feeling I came upon exactly what I needed.
    I most certainly will make sure to do not fail to
    remember this website and provides it a look on a continuing basis.

  25. купить диплом в люберцах [url=http://rudik-diplom2.ru/]купить диплом в люберцах[/url] .

    Diplomi_hzpi

    20 Oct 25 at 12:54 pm

  26. Keithmug

    20 Oct 25 at 12:55 pm

  27. проект перепланировки квартиры москва [url=http://www.proekt-pereplanirovki-kvartiry11.ru]проект перепланировки квартиры москва[/url] .

  28. EdwardAdete

    20 Oct 25 at 12:58 pm

  29. cd player alarm clock radio [url=http://www.alarm-radio-clocks.com]http://www.alarm-radio-clocks.com[/url] .

  30. перепланировка квартиры в москве [url=https://proekt-pereplanirovki-kvartiry11.ru/]перепланировка квартиры в москве[/url] .

  31. EdwardAdete

    20 Oct 25 at 12:59 pm

  32. https://www.medtronik.ru/ узнайте, как получить приветственные бонусы и участвовать в акциях

    Aaronawads

    20 Oct 25 at 12:59 pm

  33. диплом колледжа узбекистана купить [url=www.frei-diplom8.ru/]www.frei-diplom8.ru/[/url] .

    Diplomi_jmsr

    20 Oct 25 at 12:59 pm

  34. Coreycip

    20 Oct 25 at 12:59 pm

  35. купить диплом в сосновом бору [url=https://rudik-diplom2.ru]https://rudik-diplom2.ru[/url] .

    Diplomi_bcpi

    20 Oct 25 at 1:00 pm

  36. kraken официальный
    kraken официальный

    JamesDaync

    20 Oct 25 at 1:04 pm

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

    Diplomi_ipsa

    20 Oct 25 at 1:06 pm

  38. Беттеру достаточно ввести размер транзакции
    и подождать от нескольких минут до 48
    часов.

  39. Бесплатные промокоды 1xBet при регистрации 2026. Сегодня пользователям 1xBet-казино предлагаются халявные промокоды на первый депозит, которые активируются при первой регистрации. С их помощью можно увеличить сумму базового бонуса до 32500 рублей. получить промокод от 1xbet. Для получения реального выигрыша с возможностью вывода на карту, необходимо поставить всю бонусную сумму на экспресс-ставку с коэффициентом от 1,4. Если прогноз окажется правильным, система переведет деньги на основной счет. Не секрет, что у букмекерской конторы 1xBet помимо спортивных ставок есть и другие направления, включая онлайн-игры, гоночные события или политические состязания.

    Stanleyvonna

    20 Oct 25 at 1:08 pm

  40. NormanmuP

    20 Oct 25 at 1:09 pm

  41. купить свидетельство о рождении [url=www.rudik-diplom1.ru/]купить свидетельство о рождении[/url] .

    Diplomi_kner

    20 Oct 25 at 1:10 pm

  42. clock radio with cd player [url=www.alarm-radio-clocks.com]www.alarm-radio-clocks.com[/url] .

  43. [url=https://lectnicametall.ru/]готовая лестница купить[/url]

    Elmersoupt

    20 Oct 25 at 1:12 pm

  44. [url=https://rebatemyforex.com/]Forex rebate service RebateMyForex [/url]provides a transparent forex rebate system for traders worldwide. This service connects directly with top forex brokers so you can start receiving rebates without changing your trading strategy. Even losing trades return cashback to your account. It’s a straightforward way to make your trading more profitable. RebateMyForex works with both individual traders and professional investors. Users appreciate the fast payments, detailed statistics, and full transparency of their earnings. There are no extra commissions or complicated terms. The service supports popular brokers like IC Markets, Exness, and XM. RebateMyForex also provides useful educational content and trading analytics. Withdrawal methods are flexible and fast, supporting multiple currencies. By using RebateMyForex, traders increase their profitability without additional risk. The platform values reliability and client satisfaction above all. Start earning rebates today and make every trade work for you. RebateMyForex continues to expand its network and reward active clients. Create your account and activate your cashback within minutes.
    https://rebatemyforex.com/

    Ralphchect

    20 Oct 25 at 1:12 pm

  45. купить диплом в усолье-сибирском [url=www.rudik-diplom15.ru]купить диплом в усолье-сибирском[/url] .

    Diplomi_xhPi

    20 Oct 25 at 1:12 pm

  46. проект для перепланировки квартиры стоимость [url=https://proekt-pereplanirovki-kvartiry11.ru/]https://proekt-pereplanirovki-kvartiry11.ru/[/url] .

  47. Grabbed $MTAUR in stage 1 frenzy. Presale perks stack. Game beta hype high.
    mtaur coin

    WilliamPargy

    20 Oct 25 at 1:14 pm

  48. Добро пожаловать в удивительный мир природы России!

    Хочу выделить материал про Изучение ООПТ России: парки, заповедники, водоемы.

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

    [url=https://alloopt.ru]https://alloopt.ru[/url]

    Вот такое у нас получилось погружение в мир природы.

    fixRow

    20 Oct 25 at 1:14 pm

  49. Anthonycam

    20 Oct 25 at 1:14 pm

Leave a Reply