Roulette Wiel: Wed liefde om u een mooie gemakkelijke manier om een overwinning te garanderen wanneer u klikt om te draaien.
  • 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.
  • 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 72,781 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 , , ,

    72,781 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://novosti-sporta-16.ru/]https://novosti-sporta-16.ru/[/url] .

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

    3. 1win android yuklab olish [url=http://1win5508.ru/]http://1win5508.ru/[/url]

      1win_ldSt

      2 Oct 25 at 9:18 pm

    4. купить диплом железнодорожника [url=http://www.rudik-diplom6.ru]купить диплом железнодорожника[/url] .

      Diplomi_uuKr

      2 Oct 25 at 9:19 pm

    5. It’s not my first time to pay a visit this web site, i
      am browsing this site dailly and take pleasant information from here daily.

      material

      2 Oct 25 at 9:20 pm

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

    7. стоимость услуг экскаватора погрузчика [url=www.arenda-ekskavatora-pogruzchika-cena.ru]стоимость услуг экскаватора погрузчика[/url] .

    8. купить диплом в димитровграде [url=www.rudik-diplom14.ru]купить диплом в димитровграде[/url] .

      Diplomi_mcea

      2 Oct 25 at 9:25 pm

    9. прогноз ставок на спорт [url=http://www.stavka-11.ru]http://www.stavka-11.ru[/url] .

      stavka_zcst

      2 Oct 25 at 9:26 pm

    10. Stacymug

      2 Oct 25 at 9:28 pm

    11. купить диплом в рубцовске [url=http://rudik-diplom6.ru]http://rudik-diplom6.ru[/url] .

      Diplomi_dlKr

      2 Oct 25 at 9:28 pm

    12. сайт прогнозов на спорт [url=stavka-11.ru]stavka-11.ru[/url] .

      stavka_hdst

      2 Oct 25 at 9:30 pm

    13. 소액결제 현금화는 본인 명의 휴대폰으로 소액결제 한도 만큼 정보이용료, 상품권 등을 결제하고 업체에 판매하여 자금을 마련하는 대표적인
      현금화 방법입니다

    14. услуги экскаватора в москве [url=http://www.arenda-ekskavatora-pogruzchika-cena.ru]http://www.arenda-ekskavatora-pogruzchika-cena.ru[/url] .

    15. New releases in one click: https://sviluppoleadership.com/

      MichaelZEM

      2 Oct 25 at 9:36 pm

    16. где купить телефон айфон [url=https://iphone-kupit-1.ru/]где купить телефон айфон[/url] .

    17. What’s important and relevant: https://www.lagodigarda.com

      Jameslarge

      2 Oct 25 at 9:38 pm

    18. После первичной диагностики начинается активная фаза детоксикации, во время которой современные препараты вводятся капельничным методом. Этот этап помогает быстро снизить концентрацию токсинов в крови, восстановить нормальные обменные процессы и нормализовать работу внутренних органов, таких как печень, почки и сердце.
      Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-tula0.ru/]наркология вывод из запоя[/url]

      JeffreyBeaps

      2 Oct 25 at 9:38 pm

    19. https://magic.ly

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

    20. The most worthwhile are here: https://eguidemagazine.com

      DennisBex

      2 Oct 25 at 9:40 pm

    21. ставки в прогнозе [url=http://stavka-11.ru/]http://stavka-11.ru/[/url] .

      stavka_zest

      2 Oct 25 at 9:40 pm

    22. сервис аренды спецтехники [url=www.arenda-ekskavatora-pogruzchika-cena.ru]www.arenda-ekskavatora-pogruzchika-cena.ru[/url] .

    23. эпл спб [url=http://www.iphone-kupit-1.ru]http://www.iphone-kupit-1.ru[/url] .

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

    25. Truly when someone doesn’t know after that its up to other people that they will help, so here it takes place.

      toto togel

      2 Oct 25 at 9:46 pm

    26. Je suis invincible face a Super Casino, c’est un bastion ou chaque mise libere une vague de puissance. Le stock est un manuel de divertissements surpuissants, avec des slots aux pouvoirs thematiques qui amplifient les combos. L’assistance deploie des tactiques affutees, accessible par alerte ou appel d’urgence. Les trophees atterrissent via Bitcoin ou Ethereum, bien que les protocoles d’offres pourraient s’amplifier en puissance. A la fin de cette mission, Super Casino invite a une patrouille sans repli pour les gardiens de casinos virtuels ! De surcroit la circulation est instinctive comme un jetpack, simplifie la traversee des zones ludiques.
      super casino le bourg d’oisans|

      ZephyrQuestG9zef

      2 Oct 25 at 9:47 pm

    27. прогноз букмекеров на сегодня [url=https://stavka-11.ru]https://stavka-11.ru[/url] .

      stavka_ehst

      2 Oct 25 at 9:48 pm

    28. экспресс прогнозы на спорт бесплатно на сегодня [url=www.prognozy-na-sport-12.ru]www.prognozy-na-sport-12.ru[/url] .

    29. It’s an amazing post for all the online users; they will get benefit
      from it I am sure.

    30. What’s up, I want to subscribe for this webpage to take most up-to-date updates, so where can i do it please help out.

    31. прогноз ставки на спорт [url=www.stavka-11.ru/]www.stavka-11.ru/[/url] .

      stavka_jyst

      2 Oct 25 at 9:52 pm

    32. Stacymug

      2 Oct 25 at 9:54 pm

    33. Bullish on Minotaurus ICO’s viral referrals. $MTAUR utility strong. Sector expansion aids.
      mtaur token

      WilliamPargy

      2 Oct 25 at 9:55 pm

    34. 1win app promo bilan [url=https://1win5508.ru]1win app promo bilan[/url]

      1win_zeSt

      2 Oct 25 at 9:56 pm

    35. прогноз ставки на спорт [url=https://www.stavka-11.ru]https://www.stavka-11.ru[/url] .

      stavka_aust

      2 Oct 25 at 9:56 pm

    36. apple телефон купить спб [url=http://www.iphone-kupit-1.ru]http://www.iphone-kupit-1.ru[/url] .

    37. Сотрудничество со СтройСинтез оказалось комфортным и надёжным. Заказывали проект кирпичного дома в классическом стиле. Всё было сделано в срок, планировка продуманная, качество строительства на высоком уровне. Жить в таком доме приятно и удобно: https://stroysyntez.com/

      Brianvop

      2 Oct 25 at 10:02 pm

    38. DragonMoney – лицензированное казино с щедрыми бонусами, топовыми играми, быстрыми выплатами и круглосуточной поддержкой
      dragon casino

      EdgarPak

      2 Oct 25 at 10:04 pm

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

    40. На первом приёме нарколог собирает полную клиническую картину: продолжительность зависимости, количество и частоту приёмов спиртного, наличие соматических и психических осложнений. Одновременно выполняются лабораторные тесты: общий анализ крови, биохимия (показатели работы печени и почек), электролиты. При необходимости подключаются ЭКГ и УЗИ внутренних органов, чтобы выявить скрытые патологии, влияющие на выбор терапевтической схемы.
      Получить дополнительные сведения – https://lechenie-alkogolizma-arkhangelsk0.ru/

      JustinTab

      2 Oct 25 at 10:05 pm

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

    42. who was afarrier.エロ 人形At dinner,

    43. Bullish on Minotaurus ICO’s raffle prizes. $MTAUR utility in zones deepens play. Growth trajectory strong.
      minotaurus ico

      WilliamPargy

      2 Oct 25 at 10:11 pm

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

    45. Nice weblog here! Additionally your site
      a lot up very fast! What host are you the usage of?
      Can I get your associate link for yourr host? I want my web site loaded up as
      fast as yours lol

      Best Vapor

      2 Oct 25 at 10:14 pm

    46. I really like what you guys are up too. This type of clever work and coverage!

      Keep up the very good works guys I’ve added you guys to my blogroll.

    47. оригинальные телефоны айфон [url=https://iphone-kupit-1.ru]https://iphone-kupit-1.ru[/url] .

    48. Thank you for the good writeup. It in truth was once a entertainment account it.
      Glance advanced to more added agreeable from you!
      By the way, how could we keep in touch?

      seo

      2 Oct 25 at 10:16 pm

    49. Buy Tadalafil 20mg: Generic tadalafil 20mg price – Generic tadalafil 20mg price

      MartinJaive

      2 Oct 25 at 10:17 pm

    50. кайт сафари Кайт школа: Кайт школа – это место, где мечта о покорении волн на кайте становится реальностью. Это не просто учебное заведение, это комьюнити единомышленников, объединенных любовью к ветру и воде. Профессиональные инструкторы, аттестованные международными организациями, помогут вам освоить азы кайтсерфинга, научат безопасному управлению кайтом, объяснят принципы аэродинамики и метеорологии. В кайт школах используются современные методики обучения, позволяющие даже новичкам быстро и безопасно освоить основные навыки. Обучение включает в себя как теоретические занятия, так и практические занятия на берегу и на воде. Кайт школа предоставляет все необходимое оборудование, включая кайты, доски, гидрокостюмы и средства безопасности. После прохождения обучения вы получите сертификат, подтверждающий ваш уровень подготовки, и сможете самостоятельно кататься на кайте, соблюдая правила безопасности. Кайт школа – это ваш надежный проводник в мир кайтсерфинга, где вас ждут новые друзья, незабываемые приключения и безграничная свобода.

      Kevinnek

      2 Oct 25 at 10:18 pm

    Leave a Reply