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 87,022 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 , , ,

87,022 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://rudik-diplom2.ru]купить диплом охранника[/url] .

    Diplomi_xcpi

    13 Oct 25 at 2:12 am

  2. RandyEluse

    13 Oct 25 at 2:12 am

  3. я купил проведенный диплом [url=http://www.frei-diplom2.ru]я купил проведенный диплом[/url] .

    Diplomi_sfEa

    13 Oct 25 at 2:13 am

  4. купить диплом для техникума цена [url=frei-diplom9.ru]купить диплом для техникума цена[/url] .

    Diplomi_izea

    13 Oct 25 at 2:13 am

  5. Unquestionably believe that which you stated.

    Your favorite justification seemed to be on the net the easiest thing to be aware of.
    I say to you, I certainly get annoyed while people think about worries
    that they plainly don’t know about. You managed to hit
    the nail upon the top and defined out the whole thing
    without having side effect , people can take a signal.
    Will probably be back to get more. Thanks

    tits

    13 Oct 25 at 2:17 am

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

    Diplomi_huEa

    13 Oct 25 at 2:18 am

  7. купить диплом колледжа в нижнем тагиле [url=http://frei-diplom8.ru]http://frei-diplom8.ru[/url] .

    Diplomi_cksr

    13 Oct 25 at 2:19 am

  8. https://reality38261.blogzet.com/detox-examen-de-orina-cosas-que-debe-saber-antes-de-comprar-52593947

    Purificacion para examen de orina se ha transformado en una alternativa cada vez mas conocida entre personas que buscan eliminar toxinas del organismo y superar pruebas de deteccion de drogas. Estos formulas estan disenados para facilitar a los consumidores a limpiar su cuerpo de componentes no deseadas, especialmente las relacionadas con el uso de cannabis u otras sustancias ilicitas.

    Uno buen detox para examen de orina debe brindar resultados rapidos y visibles, en gran cuando el tiempo para limpiarse es limitado. En el mercado actual, hay muchas variedades, pero no todas aseguran un proceso seguro o fiable.

    De que funciona un producto detox? En terminos simples, estos suplementos actuan acelerando la depuracion de metabolitos y componentes a traves de la orina, reduciendo su concentracion hasta quedar por debajo del nivel de deteccion de los tests. Algunos actuan en cuestion de horas y su efecto puede durar entre 4 a seis horas.

    Resulta fundamental combinar estos productos con correcta hidratacion. Beber al menos par litros de agua diariamente antes y despues del consumo del detox puede mejorar los resultados. Ademas, se recomienda evitar alimentos dificiles y bebidas azucaradas durante el proceso de preparacion.

    Los mejores productos de purga 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 resultado.

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

    Un error comun es suponer que todos los detox actuan igual. Existen diferencias en formulacion, sabor, metodo de uso y duracion del impacto. Algunos vienen en presentacion liquido, otros en capsulas, y varios combinan ambos.

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

    Por ultimo, es importante recalcar que ningun detox garantiza 100% de exito. Siempre hay variables individuales como metabolismo, nivel de consumo, y tipo de examen. Por ello, es vital seguir todas instrucciones del fabricante y no descuidarse.

    JuniorShido

    13 Oct 25 at 2:19 am

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

    Diplomi_iopi

    13 Oct 25 at 2:21 am

  10. The Minotaurus presale vesting program is a game-changer for early birds. Extend for bonuses and avoid FOMO on post-TGE pumps. $MTAUR could be the dark horse in blockchain games.
    minotaurus presale

    WilliamPargy

    13 Oct 25 at 2:21 am

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

    Diplomi_cbOi

    13 Oct 25 at 2:22 am

  12. купить диплом в белово [url=www.rudik-diplom7.ru/]www.rudik-diplom7.ru/[/url] .

    Diplomi_bfPl

    13 Oct 25 at 2:22 am

  13. توجه به همه گرامی که به فکر شروع به وب‌سایت‌های قمار هستید.

    آنها پلتفرم‌ها مملو از کلاهبرداری هستند و فقط منفعت
    ادمین‌ها کار می‌کنند. یکی از دوستانم هزاران تومان
    نابود کردم و حالا درگیر دردسرهای اقتصادی و روانی هستم.
    اعتیاد به چنین بازی‌ها شبیه زهر عمل می‌کند و آرامش را نابود می‌کند.

    از این امور بمانید!

  14. prednisone online

    13 Oct 25 at 2:23 am

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

    Diplomi_kmKt

    13 Oct 25 at 2:24 am

  16. Hey there, You have done an incredible job. I will certainly digg it and
    personally recommend to my friends. I’m confident they will be benefited from this web site.

    toto

    13 Oct 25 at 2:25 am

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

    Diplomi_napi

    13 Oct 25 at 2:27 am

  18. купить диплом техникума и продажа дипломов [url=www.frei-diplom8.ru]купить диплом техникума и продажа дипломов[/url] .

    Diplomi_risr

    13 Oct 25 at 2:27 am

  19. Hi it’s me, I am also visiting this web page on a regular basis, this web site is really pleasant and the viewers are really sharing good thoughts.

  20. https://medreliefuk.shop/# order steroid medication safely online

    Raymondspemn

    13 Oct 25 at 2:28 am

  21. You ought to be a part of a contest for one
    of the most useful sites online. I will highly recommend this web site!

  22. Very nice post. I definitely love this site.
    Stick with it!

  23. Hello, Neat post. There is a problem along with your
    website in internet explorer, would check this?

    IE nonetheless is the market leader and a big part of other people will miss your excellent writing
    because of this problem.

    jelas 777

    13 Oct 25 at 2:30 am

  24. Picked up $MTAUR tokens early; the potential appreciation to 0.0002 USDT listing is mouthwatering. Maze navigation with hidden treasures feels rewarding. Team’s marketing savvy is on point.
    minotaurus coin

    WilliamPargy

    13 Oct 25 at 2:32 am

  25. купить диплом об окончании колледжа [url=https://www.frei-diplom8.ru]купить диплом об окончании колледжа[/url] .

    Diplomi_yjsr

    13 Oct 25 at 2:33 am

  26. куплю диплом медсестры в москве [url=http://frei-diplom15.ru]куплю диплом медсестры в москве[/url] .

    Diplomi_azoi

    13 Oct 25 at 2:33 am

  27. Have you ever thought about creating an e-book or
    guest authoring on other websites? I have a blog based
    upon on the same ideas you discuss and would love to have you share some
    stories/information. I know my readers would enjoy your work.

    If you are even remotely interested, feel free to send me an e mail.

    Continue Reading

    13 Oct 25 at 2:34 am

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

    Diplomi_otOi

    13 Oct 25 at 2:36 am

  29. купить диплом легально [url=www.frei-diplom2.ru]купить диплом легально[/url] .

    Diplomi_qpEa

    13 Oct 25 at 2:38 am

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

    Diplomi_omea

    13 Oct 25 at 2:39 am

  31. RandyEluse

    13 Oct 25 at 2:39 am

  32. hello there and thank you for your info – I have definitely picked up something new from right here.
    I did however expertise a few technical points using this site, as I experienced to reload the site many times previous to I could get it
    to load correctly. I had been wondering if your web host is OK?

    Not that I am complaining, but slow loading instances times
    will often affect your placement in google and can damage
    your high quality score if advertising and marketing with Adwords.
    Well I’m adding this RSS to my email and can look out for much more
    of your respective exciting content. Ensure that you update this again very soon.

  33. купить диплом в дзержинске [url=https://rudik-diplom7.ru/]купить диплом в дзержинске[/url] .

    Diplomi_soPl

    13 Oct 25 at 2:41 am

  34. купить диплом медсестры [url=www.frei-diplom13.ru/]купить диплом медсестры[/url] .

    Diplomi_nekt

    13 Oct 25 at 2:42 am

  35. 1win az müsbət rəylər [url=https://1win5005.com/]https://1win5005.com/[/url]

    1win_vwml

    13 Oct 25 at 2:43 am

  36. บทความนี้ อ่านแล้วเข้าใจง่าย ครับ
    ผม ไปเจอรายละเอียดของ เนื้อหาในแนวเดียวกัน

    สามารถอ่านได้ที่ Leopoldo
    ลองแวะไปดู
    มีข้อมูลที่อ่านแล้วเข้าใจได้ทันที

    ขอบคุณที่แชร์ บทความคุณภาพ นี้
    จะคอยดูว่ามีเนื้อหาใหม่ๆ มาเสริมอีกหรือไม่

    Leopoldo

    13 Oct 25 at 2:44 am

  37. prednisone online

    13 Oct 25 at 2:46 am

  38. купить диплом без внесения в реестр [url=www.frei-diplom1.ru/]купить диплом без внесения в реестр[/url] .

    Diplomi_liOi

    13 Oct 25 at 2:46 am

  39. купить диплом слесаря [url=www.rudik-diplom2.ru/]купить диплом слесаря[/url] .

    Diplomi_hnpi

    13 Oct 25 at 2:47 am

  40. купить техникум диплом [url=https://www.frei-diplom9.ru]купить техникум диплом[/url] .

    Diplomi_mbea

    13 Oct 25 at 2:48 am

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

    Diplomi_ojPl

    13 Oct 25 at 2:50 am

  42. купить диплом повара [url=www.rudik-diplom5.ru/]купить диплом повара[/url] .

    Diplomi_dzma

    13 Oct 25 at 2:51 am

  43. prednisone online

    13 Oct 25 at 2:51 am

  44. купить диплом строительного техникума [url=http://frei-diplom8.ru]купить диплом строительного техникума[/url] .

    Diplomi_zxsr

    13 Oct 25 at 2:55 am

  45. https://britpharmonline.shop/# buy sildenafil tablets UK

    Raymondspemn

    13 Oct 25 at 2:55 am

  46. купить диплом в шахтах [url=https://www.rudik-diplom7.ru]https://www.rudik-diplom7.ru[/url] .

    Diplomi_ntPl

    13 Oct 25 at 2:56 am

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

    Diplomi_bdOi

    13 Oct 25 at 2:57 am

  48. купить чистый диплом техникума [url=http://frei-diplom9.ru]купить чистый диплом техникума[/url] .

    Diplomi_vwea

    13 Oct 25 at 2:59 am

  49. hm88

    PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog

    hm88

    13 Oct 25 at 3:02 am

  50. Thanks. Building on this, my take: (https://jackcasinoonline.nl).

Leave a Reply