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 102,375 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 , , ,

102,375 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-diplom8.ru]купить диплом в вологде[/url] .

    Diplomi_viMt

    22 Oct 25 at 9:38 am

  2. findsolutionsfast – Great for quick wins rather than deep dives — exactly what I needed.

    Teddy Kobashigawa

    22 Oct 25 at 9:38 am

  3. купить диплом техникума иркутск [url=https://frei-diplom7.ru]купить диплом техникума иркутск[/url] .

    Diplomi_xgei

    22 Oct 25 at 9:39 am

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

    Diplomi_zhea

    22 Oct 25 at 9:40 am

  5. Эта статья сочетает в себе как полезные, так и интересные сведения, которые обогатят ваше понимание насущных тем. Мы предлагаем практические советы и рекомендации, которые легко внедрить в повседневную жизнь. Узнайте, как улучшить свои навыки и обогатить свой опыт с помощью простых, но эффективных решений.
    Нажми и узнай всё – https://jsretaildisplays.com/metal-magazine-display-stand

    DavidPycle

    22 Oct 25 at 9:40 am

  6. Где купить План в Полысаевое?Обратите внимание на https://repairmycar.ru
    – нормальные отзывы и адекватные цены. Доставка работает оперативно. Кто-нибудь проверял их лично?

    Stevenref

    22 Oct 25 at 9:41 am

  7. купить диплом в минеральных водах [url=https://www.rudik-diplom2.ru]https://www.rudik-diplom2.ru[/url] .

    Diplomi_bppi

    22 Oct 25 at 9:41 am

  8. [url=https://ltdvin.ru/category/siemens/teplovoe-napravlenie/] защита двигателей[/url]

    CesarBat

    22 Oct 25 at 9:42 am

  9. перевод медицинских терминов [url=http://www.teletype.in/@alexd78/HN462R01hzy]http://www.teletype.in/@alexd78/HN462R01hzy[/url] .

  10. JamesDaync

    22 Oct 25 at 9:42 am

  11. технический перевод в машиностроении [url=https://dzen.ru/a/aPFFa3ZMdGVq1wVQ/]dzen.ru/a/aPFFa3ZMdGVq1wVQ[/url] .

  12. диплом об окончании техникума купить в [url=https://educ-ua7.ru/]https://educ-ua7.ru/[/url] .

    Diplomi_roea

    22 Oct 25 at 9:45 am

  13. строительный техникум купить диплом [url=https://frei-diplom9.ru/]строительный техникум купить диплом[/url] .

    Diplomi_moea

    22 Oct 25 at 9:45 am

  14. купить диплом в новотроицке [url=www.rudik-diplom5.ru]купить диплом в новотроицке[/url] .

    Diplomi_fbma

    22 Oct 25 at 9:45 am

  15. keepgrowingforward.shop – Great tips and advice, really practical for personal growth today.

    Renita Mcginister

    22 Oct 25 at 9:46 am

  16. seo optimization ranking [url=www.top-10-seo-prodvizhenie.ru/]www.top-10-seo-prodvizhenie.ru/[/url] .

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

    Diplomi_xqKt

    22 Oct 25 at 9:47 am

  18. Very good post! We are linking to this particularly great content on our
    website. Keep up the good writing.

    cannabis

    22 Oct 25 at 9:48 am

  19. seo marketing agency [url=seo-prodvizhenie-reiting-kompanij.ru]seo marketing agency[/url] .

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

    Diplomi_ngEa

    22 Oct 25 at 9:48 am

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

    Diplomi_jwpi

    22 Oct 25 at 9:48 am

  22. rodarodaku.xyz – The content feels original and nicely organized across sections today.

    Isiah Aderman

    22 Oct 25 at 9:49 am

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

    Diplomi_qgOi

    22 Oct 25 at 9:50 am

  24. купить диплом в ухте [url=https://www.rudik-diplom1.ru]купить диплом в ухте[/url] .

    Diplomi_pqer

    22 Oct 25 at 9:50 am

  25. You’re so awesome! I don’t believe I’ve truly read anything
    like that before. So wonderful to find another person with some original thoughts on this issue.
    Seriously.. thank you for starting this up. This web site is
    one thing that is needed on the internet, someone with a bit
    of originality!

    gid=0

    22 Oct 25 at 9:50 am

  26. Промокоды казино 1xBet при регистрации 2026. На ресурсе 1хБет пользователи могут не только делать ставки на спорт и другие события из разных сфер, но и получать азартные ощущения в казино. Играть можно как с машинами, так и с реальными дилерами в разделе лайв. Чтобы привлекать как можно больше новых игроков и поддерживать интерес постоянных клиентов, на сайте 1хБет регулярно проходят акции и раздают бонусы. Самое щедрое вознаграждение могут получить новички, использовав промокод казино 1xBet. Указав его при регистрации, пользователь получит дополнительные денежные средства на первые несколько депозитов, которые сможет использовать для ставок в играх. Это сделать просто, если иметь промокоды 1xbet куда вводить. Правда, дается он при условии выполнения некоторых правил. 1xBet бонус при регистрации. Не совсем промокод, но вы все равно ставите не свои деньги, если пополните депозит, – 100% бонуса от внесенной суммы. Максимум указан в верхней части главной страницы официального сайта.

    Stanleyvonna

    22 Oct 25 at 9:51 am

  27. купить диплом техникума недорого [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .

    Diplomi_tzea

    22 Oct 25 at 9:51 am

  28. Парвеник — это правильные веники и травы для настоящей русской бани: дуб, берёза, эвкалипт, ароматные сборы, аксессуары и удобная доставка по Москве и Подмосковью через пункты выдачи. Цены честно снижаются при покупке от двух единиц, а акция 5+1 даёт ощутимую экономию. Заказать просто: на https://www.parvenik.ru/ есть подробные карточки и указаны актуальные условия выдачи. Свежие партии 2025 года, гибкие опции оплаты и тысячи удачных заказов — чтобы пар был лёгким, а отдых — целебным.

    nanisCot

    22 Oct 25 at 9:52 am

  29. технический перевод это [url=http://www.dzen.ru/a/aPFFa3ZMdGVq1wVQ]http://www.dzen.ru/a/aPFFa3ZMdGVq1wVQ[/url] .

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

    Diplomi_szPa

    22 Oct 25 at 9:54 am

  31. кракен android
    kraken vk5

    JamesDaync

    22 Oct 25 at 9:54 am

  32. xxau.xyz – Pages load quickly, giving a smooth and pleasant browsing experience.

    Geraldo Cejka

    22 Oct 25 at 9:54 am

  33. mm9b.xyz – Bookmarked this site, looks reliable and worth revisiting often.

    Kelley Lail

    22 Oct 25 at 9:55 am

  34. When some one searches for his required thing, so he/she wants to be available that in detail, so that thing
    is maintained over here.

    Goldankauf Bochum

    22 Oct 25 at 9:56 am

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

    Diplomi_dpOi

    22 Oct 25 at 9:56 am

  36. технический перевод [url=teletype.in/@alexd78/HN462R01hzy]teletype.in/@alexd78/HN462R01hzy[/url] .

  37. Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
    Личный опыт — читайте сами – https://naklejto.com/product/long-sleeve-tee

    Donaldwax

    22 Oct 25 at 9:59 am

  38. Howdy! This is my first comment here so I just wanted to give a quick shout out and say I genuinely
    enjoy reading your blog posts. Can you suggest any other blogs/websites/forums that go over the same topics?
    Thanks!

  39. Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
    Только для своих – https://angelescares.com/2024/04/14/beyond-business-the-unique-benefits-of-family-owned-senior-care

    Charlesadamb

    22 Oct 25 at 10:01 am

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

    Diplomi_hcMi

    22 Oct 25 at 10:01 am

  41. kkgg1.xyz – The visuals and text blend naturally, keeping everything neat and clean.

    Marian Winer

    22 Oct 25 at 10:01 am

  42. kraken vk6
    kraken 2025

    JamesDaync

    22 Oct 25 at 10:02 am

  43. купить диплом в клинцах [url=https://www.rudik-diplom1.ru]купить диплом в клинцах[/url] .

    Diplomi_yler

    22 Oct 25 at 10:03 am

  44. перевод медицинских документов [url=https://telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16/]telegra.ph/Medicinskij-perevod-tochnost-kak-vopros-zhizni-i-zdorovya-10-16[/url] .

  45. https://linktr.ee/candetoxblend

    Superar un control sorpresa puede ser un momento critico. Por eso, se ha creado una alternativa confiable desarrollada en Canada.

    Su receta eficaz combina minerales, lo que sobrecarga tu organismo y disimula temporalmente los metabolitos de toxinas. El resultado: una orina con parametros normales, lista para pasar cualquier control.

    Lo mas interesante es su accion rapida en menos de 2 horas. A diferencia de detox irreales, no promete milagros, sino una estrategia de emergencia que te respalda en situaciones criticas.

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

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

    De qué funciona un producto detox? En términos básicos, estos suplementos funcionan acelerando la depuración de metabolitos y toxinas a través de la orina, reduciendo su concentración hasta quedar por debajo del nivel de detección de algunos tests. Algunos funcionan en cuestión de horas y su acción puede durar entre 4 a 6 horas.

    Resulta fundamental combinar estos productos con buena hidratación. Beber al menos dos litros de agua al día antes y después del consumo del detox puede mejorar los beneficios. Además, se sugiere evitar alimentos pesados y bebidas ácidas durante el proceso de desintoxicación.

    Los mejores productos de detox para orina incluyen ingredientes como extractos de naturales, vitaminas del grupo B y minerales que respaldan el funcionamiento de los riñones y la función hepática. Entre las marcas más destacadas, se encuentran aquellas que ofrecen certificaciones sanitarias y estudios de resultado.

    Para usuarios frecuentes de cannabis, se recomienda usar detoxes con ventanas de acción largas o iniciar una preparación temprana. Mientras más prolongada sea la abstinencia, mayor será la potencia del producto. Por eso, combinar la organización con el uso correcto del producto es clave.

    Un error común es suponer que todos los detox actúan idéntico. Existen diferencias en dosis, sabor, método de uso 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 limpieza previa al día del examen. Estos programas suelen sugerir abstinencia, buena alimentación y descanso recomendado.

    Por último, es importante recalcar que ninguno detox garantiza 100% de éxito. Siempre hay variables personales como metabolismo, historial de consumo, y tipo de examen. Por ello, es vital seguir ciertas instrucciones del fabricante y no confiarse.

    Miles de estudiantes ya han comprobado su seguridad. Testimonios reales mencionan paquetes 100% confidenciales.

    Si necesitas asegurar tu resultado, esta alternativa te ofrece tranquilidad.

    JuniorShido

    22 Oct 25 at 10:05 am

  46. A motivating discussion is worth comment. There’s no doubt that that you ought to
    write more about this issue, it may not be a taboo subject but usually people don’t speak about such issues.
    To the next! Kind regards!!

  47. click the up coming post

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

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

    Diplomi_liKt

    22 Oct 25 at 10:07 am

  49. раскрутка сайтов москва [url=http://www.seo-prodvizhenie-reiting-kompanij.ru]раскрутка сайтов москва[/url] .

  50. Can I simply say what a comfort to uncover someone that
    really knows what they are talking about on the internet.
    You definitely realize how to bring an issue to light and make it important.
    More and more people have to look at this and understand this side
    of your story. I can’t believe you aren’t more popular because you
    most certainly have the gift.

Leave a Reply