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,771 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,771 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=https://pereplanirovka-nezhilogo-pomeshcheniya8.ru]https://pereplanirovka-nezhilogo-pomeshcheniya8.ru[/url] .

  2. карниз с приводом [url=http://karniz-shtor-elektroprivodom.ru]http://karniz-shtor-elektroprivodom.ru[/url] .

  3. аренда погрузчиков в москве и московской области [url=http://arenda-ekskavatora-pogruzchika-cena-2.ru]http://arenda-ekskavatora-pogruzchika-cena-2.ru[/url] .

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

    Diplomi_fwoi

    13 Oct 25 at 5:57 pm

  5. узаконить перепланировку нежилого помещения [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru]https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .

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

    Diplomi_smoi

    13 Oct 25 at 5:57 pm

  7. перепланировка в нежилом помещении [url=https://pereplanirovka-nezhilogo-pomeshcheniya8.ru/]https://pereplanirovka-nezhilogo-pomeshcheniya8.ru/[/url] .

  8. переустройство нежилого помещения [url=www.pereplanirovka-nezhilogo-pomeshcheniya8.ru]www.pereplanirovka-nezhilogo-pomeshcheniya8.ru[/url] .

  9. http://amoxicareonline.com/# generic Amoxicillin pharmacy UK

    HerbertScacy

    13 Oct 25 at 6:02 pm

  10. Частный заем денег ооо домашние деньги альтернатива банковскому кредиту. Быстро, безопасно и без бюрократии. Получите нужную сумму наличными или на карту за считанные минуты.

    Grantgricy

    13 Oct 25 at 6:03 pm

  11. buy viagra: Viagra online UK – British online pharmacy Viagra

    Brettesofe

    13 Oct 25 at 6:04 pm

  12. перепланировка нежилых помещений [url=http://pereplanirovka-nezhilogo-pomeshcheniya8.ru/]http://pereplanirovka-nezhilogo-pomeshcheniya8.ru/[/url] .

  13. Je suis totalement seduit par Locowin Casino, c’est une plateforme qui bouillonne d’energie. La selection de jeux est phenomenale, comprenant des jeux compatibles avec les cryptos. Pour un demarrage en force. Les agents repondent avec rapidite, offrant des reponses claires. Les gains arrivent sans delai, mais des recompenses supplementaires seraient un atout. Dans l’ensemble, Locowin Casino garantit du fun a chaque instant pour les joueurs en quete d’excitation ! En prime le site est rapide et attrayant, amplifie le plaisir de jouer. A noter egalement les evenements communautaires engageants, qui booste l’engagement.
    DГ©marrer maintenant|

    QuantumLeapB8zef

    13 Oct 25 at 6:04 pm

  14. wettseiten

    my web page – Einzahlungsbonus Sportwetten

  15. трактор погрузчик аренда [url=http://arenda-ekskavatora-pogruzchika-cena-2.ru/]http://arenda-ekskavatora-pogruzchika-cena-2.ru/[/url] .

  16. Visitez Roulettino Casino https://roulettino-fr.com et obtenez un bonus de 500 € + 100 tours gratuits dès maintenant ! Explorez notre sélection de jeux et découvrez Roulettino Casino France, qui offre une expérience de jeu légale, réglementée et structurée, adaptée aux joueurs français. Pour en savoir plus, consultez le site web.

    gosunFaula

    13 Oct 25 at 6:10 pm

  17. Heya i am for the first time here. I came across this board and I find It really helpful
    & it helped me out much. I hope to provide one thing back and aid others
    such as you aided me.

    tits

    13 Oct 25 at 6:10 pm

  18. RobertHag

    13 Oct 25 at 6:11 pm

  19. order medication online legally in the UK: online pharmacy – pharmacy online UK

    JamesDes

    13 Oct 25 at 6:12 pm

  20. Rogerunsub

    13 Oct 25 at 6:12 pm

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

    Davidboots

    13 Oct 25 at 6:12 pm

  22. В «ВладЗдоровье» применяется комплексный подход, сочетающий медикаментозное лечение, психотерапию и реабилитацию. Врач-нарколог подбирает препараты индивидуально, с учётом анамнеза, переносимости компонентов и текущего состояния организма. Психотерапевтический блок включает когнитивно-поведенческую терапию, мотивационные интервью, семейную терапию и работу с посттравматическими реакциями.
    Детальнее – [url=https://narkologicheskaya-pomoshh-vladimir0.ru/]оказание наркологической помощи в владимире[/url]

    Russellsmugh

    13 Oct 25 at 6:13 pm

  23. карнизы с электроприводом купить [url=https://karniz-shtor-elektroprivodom.ru/]карнизы с электроприводом купить[/url] .

  24. Brentsek

    13 Oct 25 at 6:15 pm

  25. Wow that was strange. I just wrote an extremely long comment but after I
    clicked submit my comment didn’t appear. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say
    fantastic blog!

  26. Каждый из методов подбирается индивидуально, что позволяет учитывать медицинские показания и личные особенности пациента.
    Детальнее – [url=https://lechenie-alkogolizma-perm0.ru/]лечение алкоголизма и наркомании центр пермь[/url]

    Francisaxogy

    13 Oct 25 at 6:17 pm

  27. https://www.tumblr.com/candetoxblend/794393330425446400/preguntas-frecuentes-sobre-detox-para-examen-de

    Limpieza para examen de orina se ha transformado en una opcion cada vez mas reconocida entre personas que requieren eliminar toxinas del cuerpo y superar pruebas de analisis de drogas. Estos productos estan disenados para ayudar a los consumidores a limpiar su cuerpo de residuos no deseadas, especialmente las relacionadas con el ingesta de cannabis u otras sustancias ilicitas.

    Uno buen detox para examen de orina debe ofrecer resultados rapidos y confiables, en particular cuando el tiempo para prepararse es limitado. En el mercado actual, hay muchas alternativas, pero no todas prometen un proceso seguro o fiable.

    Que funciona un producto detox? En terminos claros, estos suplementos funcionan acelerando la eliminacion de metabolitos y componentes a traves de la orina, reduciendo su presencia hasta quedar por debajo del nivel de deteccion de los tests. Algunos funcionan en cuestion de horas y su efecto puede durar entre 4 a seis horas.

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

    Los mejores productos de limpieza para orina incluyen ingredientes como extractos de naturales, vitaminas del complejo B y minerales que apoyan el funcionamiento de los organos y la funcion hepatica. Entre las marcas mas vendidas, se encuentran aquellas que presentan certificaciones sanitarias y estudios de resultado.

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

    Un error comun es suponer que todos los detox actuan identico. Existen diferencias en dosis, 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 preparacion previa al dia del examen. Estos programas suelen recomendar abstinencia, buena alimentacion y descanso recomendado.

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

    JuniorShido

    13 Oct 25 at 6:18 pm

  28. рулонные шторы автоматические купить [url=http://rulonnaya-shtora-s-elektroprivodom.ru/]http://rulonnaya-shtora-s-elektroprivodom.ru/[/url] .

  29. Brentsek

    13 Oct 25 at 6:20 pm

  30. аренда экскаватора смена [url=www.arenda-ekskavatora-pogruzchika-cena-2.ru/]www.arenda-ekskavatora-pogruzchika-cena-2.ru/[/url] .

  31. «Как отмечает врач-нарколог Андрей Николаевич Селиванов, «своевременный визит специалиста на дом позволяет избежать тяжёлых осложнений и ускоряет стабилизацию состояния»».
    Детальнее – [url=https://narkolog-na-dom-sankt-peterburg14.ru/]нарколог на дом анонимно в санкт-петербурге[/url]

    Jerrysmism

    13 Oct 25 at 6:21 pm

  32. It’s the best time to make a few plans for the future and it’s time to
    be happy. I’ve learn this put up annd if I may just I desire to suggest
    yyou few attention-grabbing things or advice.
    Maybe you could write next artjcles referring to this article.
    I want to read more issues about it!

    boyarka

    13 Oct 25 at 6:25 pm

  33. stellenangebote wettbüro

    Also visit my site – Neue buchmacher

    Neue buchmacher

    13 Oct 25 at 6:29 pm

  34. перепланировка офиса согласование [url=http://pereplanirovka-nezhilogo-pomeshcheniya8.ru]http://pereplanirovka-nezhilogo-pomeshcheniya8.ru[/url] .

  35. аренда экскаватора погрузчика цена москва [url=https://arenda-ekskavatora-pogruzchika-cena-2.ru]https://arenda-ekskavatora-pogruzchika-cena-2.ru[/url] .

  36. Today, while I was at work, my cousin stole my iPad and tested
    to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad is now destroyed and she has 83 views.
    I know this is entirely off topic but I had to share
    it with someone!

  37. согласование перепланировки нежилого помещения в жилом доме [url=https://pereplanirovka-nezhilogo-pomeshcheniya9.ru/]https://pereplanirovka-nezhilogo-pomeshcheniya9.ru/[/url] .

  38. Enjoy fast VPS server with 4 gigabytes RAM, Ryzen 4-core CPU, and
    4 terabytes transfer. Perfect for learners to learn applications.

    free Backlinks

    13 Oct 25 at 6:38 pm

  39. دوست، در صورتی که نسبت به وب‌سایت‌های بازی‌های
    شرطی فکر می‌کنید، ایست نمائید.
    خودم تجربه مستقیم کرده‌ام که نشان می‌گردد چنین سایت‌ها وسیله جهت کلاهبرداری به
    علاوه نابودی دارایی هستند.
    پول سریع هدر می‌شود و سوءمصرف دائمی
    می‌گردد. بهتر است پرهیز شوید و
    به کمک روانشناسان توجه آورید!

  40. согласование проекта перепланировки нежилого помещения [url=http://www.pereplanirovka-nezhilogo-pomeshcheniya11.ru]http://www.pereplanirovka-nezhilogo-pomeshcheniya11.ru[/url] .

  41. Stevennic

    13 Oct 25 at 6:45 pm

  42. электрокарнизы купить в москве [url=karniz-shtor-elektroprivodom.ru]электрокарнизы купить в москве[/url] .

  43. Everything typed made a bunch of sense. However, what about this?
    what if you added a little content? I am not saying your content is
    not good, however suppose you added a headline that grabbed folk’s attention? I mean PHP hook, building hooks in your application – Sjoerd
    Maessen blog at Sjoerd Maessen blog is kinda boring. You might peek at Yahoo’s home
    page and watch how they create news titles to grab viewers
    to click. You might add a related video or a related pic
    or two to grab readers interested about everything’ve written. In my opinion, it could bring your blog a little livelier.

    Fundrex Impulso

    13 Oct 25 at 6:47 pm

  44. Все спортивные новости http://sportsat.ru в реальном времени. Итоги матчей, трансферы, рейтинги и обзоры. Следите за событиями мирового спорта и оставайтесь в курсе побед и рекордов!

    sportsat-379

    13 Oct 25 at 6:50 pm

  45. Jamesduets

    13 Oct 25 at 6:50 pm

  46. $MTAUR ICO is gaining traction over SHIB/XRP rallies. Token’s in-game convertibility ensures demand. Presale’s 1.4M USDT milestone proves it.
    minotaurus presale

    WilliamPargy

    13 Oct 25 at 6:50 pm

  47. Частный заем денег домашние деньги займ на карту альтернатива банковскому кредиту. Быстро, безопасно и без бюрократии. Получите нужную сумму наличными или на карту за считанные минуты.

    Grantgricy

    13 Oct 25 at 6:50 pm

  48. Перед выбором метода врач проводит диагностику, оценивает физическое и психоэмоциональное состояние пациента, рассказывает о возможных рисках и особенностях процедуры. Только после согласования всех деталей назначается дата и форма кодирования.
    Получить дополнительную информацию – [url=https://kodirovanie-ot-alkogolizma-ehlektrostal6.ru/]kodirovanie-ot-alkogolizma-ceny[/url]

    ScottCet

    13 Oct 25 at 6:51 pm

Leave a Reply