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 100,576 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 , , ,

100,576 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=pinup5008.ru]пин ап получить бонус[/url]

    pin_up_uz_ssSt

    21 Oct 25 at 12:29 pm

  2. компании сео [url=http://www.seo-prodvizhenie-reiting.ru]http://www.seo-prodvizhenie-reiting.ru[/url] .

  3. pin-up [url=https://www.pinup5008.ru]https://www.pinup5008.ru[/url]

    pin_up_uz_kmSt

    21 Oct 25 at 12:33 pm

  4. Good way of telling, and nice article to take facts regarding my presentation subject, which i
    am going to present in university.

    nsfw ai chat

    21 Oct 25 at 12:34 pm

  5. ссылки на кракен: https://obecretuvka.cz

  6. https://www.designspiration.com/candetoxblend/saves/

    Gestionar un control sorpresa puede ser complicado. Por eso, se ha creado una formula avanzada probada en laboratorios.

    Su receta precisa combina nutrientes esenciales, lo que ajusta tu organismo y enmascara temporalmente los trazas de alcaloides. El resultado: un analisis equilibrado, lista para pasar cualquier control.

    Lo mas valioso es su ventana de efectividad de 4 a 5 horas. A diferencia de metodos caseros, no promete resultados permanentes, sino una estrategia de emergencia que funciona cuando lo necesitas.

    Estos fórmulas están diseñados para colaborar a los consumidores a purgar su cuerpo de componentes no deseadas, especialmente aquellas relacionadas con el uso de cannabis u otras sustancias ilícitas.

    Uno buen detox para examen de fluido debe ofrecer resultados rápidos y confiables, en particular cuando el tiempo para limpiarse es limitado. En el mercado actual, hay muchas variedades, pero no todas prometen un proceso seguro o efectivo.

    ¿Cómo funciona un producto detox? En términos claros, estos suplementos operan acelerando la expulsión de metabolitos y componentes a través de la orina, reduciendo su presencia hasta quedar por debajo del umbral de detección de algunos tests. Algunos funcionan en cuestión de horas y su impacto puede durar entre 4 a cinco horas.

    Es fundamental combinar estos productos con adecuada hidratación. Beber al menos 2 litros de agua por jornada antes y después del ingesta del detox puede mejorar los efectos. Además, se aconseja evitar alimentos difíciles y bebidas ácidas durante el proceso de uso.

    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 riñones y la función hepática. Entre las marcas más vendidas, se encuentran aquellas que ofrecen certificaciones sanitarias y estudios de resultado.

    Para usuarios frecuentes de marihuana, se recomienda usar detoxes con márgenes de acción largas o iniciar una preparación previa. Mientras más prolongada sea la abstinencia, mayor será la eficacia del producto. Por eso, combinar la planificación con el uso correcto del suplemento es clave.

    Un error común es creer que todos los detox actúan lo mismo. Existen diferencias en contenido, sabor, método de toma y duración del resultado. Algunos vienen en presentación líquido, otros en cápsulas, y varios combinan ambos.

    Además, hay productos que incluyen fases de preparación o purga previa al día del examen. Estos programas suelen instruir abstinencia, buena alimentación y descanso previo.

    Por último, es importante recalcar que ningún detox garantiza 100% de éxito. Siempre hay variables individuales como metabolismo, frecuencia de consumo, y tipo de examen. Por ello, es vital seguir ciertas instrucciones del fabricante y no relajarse.

    Miles de trabajadores ya han validado su discrecion. Testimonios reales mencionan resultados exitosos en pruebas preocupacionales.

    Si no deseas dejar nada al azar, esta formula te ofrece tranquilidad.

    JuniorShido

    21 Oct 25 at 12:38 pm

  7. $MTAUR coin’s security audits by SolidProof and Coinsult make it trustworthy amid scam fears. Presale raffle for $100K is drawing crowds. Loving the whimsical creature battles in the demo.
    minotaurus ico

    WilliamPargy

    21 Oct 25 at 12:38 pm

  8. Стационар «Частного Медика 24» — условия, где пациент может спокойно пройти вывод из запоя без страха и дискомфорта.
    Узнать больше – [url=https://vyvod-iz-zapoya-v-stacionare-samara24.ru/]наркология вывод из запоя в стационаре[/url]

    JamessoypE

    21 Oct 25 at 12:40 pm

  9. wettbüro essen

    My blog pferderennen wetten (Caitlyn)

    Caitlyn

    21 Oct 25 at 12:40 pm

  10. топ seo [url=http://top-10-seo-prodvizhenie.ru/]топ seo[/url] .

  11. топ seo компаний [url=www.reiting-seo-agentstv.ru/]www.reiting-seo-agentstv.ru/[/url] .

  12. Danielignit

    21 Oct 25 at 12:43 pm

  13. агентство поискового продвижения [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]агентство поискового продвижения[/url] .

  14. куплю диплом младшей медсестры [url=https://frei-diplom13.ru]https://frei-diplom13.ru[/url] .

    Diplomi_txkt

    21 Oct 25 at 12:44 pm

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

    Diplomi_coPt

    21 Oct 25 at 12:45 pm

  16. pin up yuklash ios [url=http://pinup5008.ru/]http://pinup5008.ru/[/url]

    pin_up_uz_muSt

    21 Oct 25 at 12:45 pm

  17. Когда запой длится и состояние ухудшается, важно обратиться в стационар, где врачи «Частного Медика 24» в Воронеже проводят детоксикацию, насыщение организма витаминами, поддерживают сердце, печень и другие органы. Цена от 6500 ? включает всё необходимое — от диагностики до психологической поддержки.
    Подробнее тут – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh24.ru/]вывод из запоя в стационаре воронеж[/url]

    Donaldjange

    21 Oct 25 at 12:46 pm

  18. сео оптимизация заказать [url=https://reiting-runeta-seo.ru/]сео оптимизация заказать[/url] .

  19. DarylCeviZ

    21 Oct 25 at 12:47 pm

  20. DarylCeviZ

    21 Oct 25 at 12:48 pm

  21. В стационаре в Воронеже вам обеспечат безопасный выход из запоя: врачи контролируют состояние, корректируют лечение при сопутствующих заболеваниях, используют витамины, препараты для печени, кардиопротекторы, спазмолитики и другие средства, чтобы облегчить состояние.
    Углубиться в тему – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh22.ru/]быстрый вывод из запоя в стационаре в воронеже[/url]

    ClydeOmiGe

    21 Oct 25 at 12:48 pm

  22. Выездная наркологическая помощь в Нижнем Новгороде — капельница от запоя с выездом на дом. Мы обеспечиваем быстрое и качественное лечение без необходимости посещения клиники.
    Узнать больше – [url=https://vyvod-iz-zapoya-nizhnij-novgorod12.ru/]вывод из запоя цена в нижний новгороде[/url]

    AllanCauck

    21 Oct 25 at 12:49 pm

  23. top 100 seo [url=www.seo-prodvizhenie-reiting.ru]www.seo-prodvizhenie-reiting.ru[/url] .

  24. продвижение в топ [url=https://reiting-seo-agentstv.ru/]продвижение в топ[/url] .

  25. Oһ dear, famous establishments һave guidance assistance,
    directing youngsters аcross anxiety foг improved emotional ԝell-beіng and studies.

    Listen, parents, composed lah, leading schools feature creature handling programs, encouraging pet care careers.

    Parents, dread tһe disparity hor, mathematics foundation гemains essential at primary school t᧐ understanding data,
    crucial witһin modern digital economy.

    Aiyah, primary math instructs real-ԝorld applications ⅼike budgeting, ѕo ensure уоur
    kid getѕ that right frօm young age.

    Wah, mathematics acts ⅼike the groundwork block fօr primary schooling, aiding children іn dimensional analysis tⲟ design careers.

    Parents, fearful ߋf losing mode activated lah, strong primary math leads іn Ƅetter
    STEM comprehension ɑnd construction goals.

    Listen սp, steady pom pi pi, math іs one fгom the һighest topics
    in primary school, building base tо A-Level calculus.

    Nanyang Primary School ᧐ffers a prestigious education emphasizing scholastic rigor.

    Ƭһe school supports gifted students fօr future
    management.

    Fengshan Primary School ⲟffers livepy programs іn a helpful environment.

    Tһe school develops ѕelf-confidence thrⲟugh engaging activities.

    Parents vаlue its concentrate оn trainee weⅼl-bеing.

    My web blog; Admiralty Secondary School

  26. Danielignit

    21 Oct 25 at 12:52 pm

  27. список seo агентств [url=www.reiting-seo-kompanii.ru]www.reiting-seo-kompanii.ru[/url] .

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

    Diplomi_ydkt

    21 Oct 25 at 12:53 pm

  29. «Аврора Агро Партс» — онлайн каталог запчастей к сельхозтехнике с большим выбором оригиналов и качественных аналогов для John Deere, Claas, Assurpower, Greenly и других марок. Здесь удобно искать по артикулу и наименованию, доступны опт и розница, быстрая отгрузка со склада и помощь менеджеров в подборе. Подробности, цены и актуальные позиции — на https://aa-p.ru/catalog/john-deere Есть самовывоз, бесплатная доставка до ТК при соблюдении условий и регулярные обновления прайс листа для точного планирования закупок.

    fofogInatE

    21 Oct 25 at 12:54 pm

  30. купить диплом колледжа новосибирск [url=www.frei-diplom12.ru/]www.frei-diplom12.ru/[/url] .

    Diplomi_cuPt

    21 Oct 25 at 12:54 pm

  31. пин ап бонус за регистрацию [url=www.pinup5008.ru]www.pinup5008.ru[/url]

    pin_up_uz_daSt

    21 Oct 25 at 12:57 pm

  32. топ seo компаний [url=https://www.reiting-seo-kompanii.ru]топ seo компаний[/url] .

  33. This is a topic which is close to my heart… Cheers!
    Exactly where are your contact details though?

  34. Публикация предлагает читателю не просто информацию, а инструменты для анализа и саморазвития. Мы стимулируем критическое мышление, предлагая различные точки зрения и призывая к самостоятельному поиску решений.
    Читать далее > – https://alphadentalgroup.com.au/how-often-should-you-visit-your-dentist

    Larryvax

    21 Oct 25 at 1:01 pm

  35. I think everything published was actually very logical.
    But, consider this, what if you were to write a awesome headline?
    I mean, I don’t want to tell you how to run your blog, however suppose you added something to maybe get a person’s attention? I mean PHP hook, building hooks in your application – Sjoerd Maessen blog
    at Sjoerd Maessen blog is a little vanilla. You ought
    to peek at Yahoo’s home page and see how they create article titles to grab people to click.
    You might try adding a video or a related picture or two to grab readers excited about everything’ve got to say.
    In my opinion, it would make your posts a little bit more interesting.

  36. купить медицинский диплом медсестры [url=http://frei-diplom13.ru]купить медицинский диплом медсестры[/url] .

    Diplomi_adkt

    21 Oct 25 at 1:01 pm

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

    Diplomi_zoPt

    21 Oct 25 at 1:02 pm

  38. DarylCeviZ

    21 Oct 25 at 1:03 pm

  39. компании сео [url=https://seo-prodvizhenie-reiting.ru/]https://seo-prodvizhenie-reiting.ru/[/url] .

  40. Где купить Скорость в Киренске?Ребята, поделитесь опытом – присмотрел https://metalcandy.ru
    . Цены адекватные, работает доставка. Кто-то пробовал с ними? Насколько качественно?

    Stevenref

    21 Oct 25 at 1:04 pm

  41. Danielignit

    21 Oct 25 at 1:06 pm

  42. Minotaurus presale docs detail fair distribution. $MTAUR’s play-to-earn model sustainable. Endless mazes promise hours of play.
    minotaurus token

    WilliamPargy

    21 Oct 25 at 1:07 pm

  43. Danielignit

    21 Oct 25 at 1:07 pm

  44. http://potenzvital.com/# potenzmittel cialis

    LarryArrix

    21 Oct 25 at 1:09 pm

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

    Diplomi_bokt

    21 Oct 25 at 1:11 pm

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

    Diplomi_qsPt

    21 Oct 25 at 1:12 pm

  47. DarylCeviZ

    21 Oct 25 at 1:14 pm

  48. лидеры seo продвижения веб студия [url=http://www.reiting-seo-agentstv.ru]http://www.reiting-seo-agentstv.ru[/url] .

  49. компании занимающиеся продвижением сайтов [url=http://seo-prodvizhenie-reiting.ru/]компании занимающиеся продвижением сайтов[/url] .

  50. топ seo продвижение заказать [url=http://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]http://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .

Leave a Reply