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 74,499 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 , , ,

    74,499 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://prognozy-na-futbol-10.ru/]http://prognozy-na-futbol-10.ru/[/url] .

    2. купить диплом косметолога [url=www.rudik-diplom3.ru]купить диплом косметолога[/url] .

      Diplomi_coei

      3 Oct 25 at 6:38 pm

    3. Купить диплом техникума в Херсон [url=https://educ-ua7.ru/]https://educ-ua7.ru/[/url] .

      Diplomi_zbea

      3 Oct 25 at 6:38 pm

    4. онлайн-казино с лицензией Curacao. Предлагает щедрые бонусы, топовые игры от ведущих провайдеров, быстрые выплаты и круглосуточную поддержку
      драгон мани официальный сайт

      BrittGor

      3 Oct 25 at 6:39 pm

    5. купить диплом в нижнем тагиле [url=https://www.rudik-diplom7.ru]купить диплом в нижнем тагиле[/url] .

      Diplomi_njPl

      3 Oct 25 at 6:39 pm

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

      Diplomi_gcOi

      3 Oct 25 at 6:41 pm

    7. купить диплом в шахтах [url=rudik-diplom2.ru]rudik-diplom2.ru[/url] .

      Diplomi_kmpi

      3 Oct 25 at 6:41 pm

    8. wtgmkjx

      3 Oct 25 at 6:42 pm

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

      Diplomi_paOr

      3 Oct 25 at 6:44 pm

    10. What i don’t realize is in reality how you’re not actually a lot more neatly-favored than you
      may be now. You’re very intelligent. You realize thus considerably in terms of this subject, produced me for my part
      imagine it from a lot of numerous angles. Its like men and
      women don’t seem to be involved until it’s something to do with Woman gaga!

      Your individual stuffs great. All the time handle it up!

      AeveniroxAi

      3 Oct 25 at 6:44 pm

    11. купить диплом в нижневартовске [url=http://www.rudik-diplom3.ru]http://www.rudik-diplom3.ru[/url] .

      Diplomi_pkei

      3 Oct 25 at 6:44 pm

    12. медсестра которая купила диплом врача [url=www.frei-diplom14.ru]www.frei-diplom14.ru[/url] .

      Diplomi_ahoi

      3 Oct 25 at 6:45 pm

    13. диплом колледжа купить в липецке [url=https://frei-diplom8.ru/]https://frei-diplom8.ru/[/url] .

      Diplomi_exsr

      3 Oct 25 at 6:45 pm

    14. купить диплом о высшем образовании легально [url=https://frei-diplom4.ru/]купить диплом о высшем образовании легально[/url] .

      Diplomi_huOl

      3 Oct 25 at 6:45 pm

    15. прогнозы на сегодня футбол [url=prognozy-na-futbol-10.ru]прогнозы на сегодня футбол[/url] .

    16. диплом техникум колледж купить [url=https://educ-ua7.ru]https://educ-ua7.ru[/url] .

      Diplomi_uoea

      3 Oct 25 at 6:46 pm

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

      Diplomi_noPa

      3 Oct 25 at 6:46 pm

    18. PatrickGop

      3 Oct 25 at 6:47 pm

    19. OMT’s helpful comments loops motivate development ᴡay of
      thinking, assisting students love mathematics ɑnd feel inspired for examinations.

      Dive intо sеlf-paced mathematics proficiency with OMT’s 12-month e-learning courses, complete ԝith practice
      worksheets аnd taped sessions foг thorough modification.

      Singapore’s focus οn crucial thinking tһrough mathematics highlights thе significance of math tuition, ѡhich assists
      trainees establish thee analytical abilities required ƅy the country’s forward-thinking syllabus.

      Improving primary education ᴡith math tuition prepares trainees for PSLE by cultivating a development
      ѕtate of mind tоwards difficult topics ⅼike proportion and improvements.

      All natural development tһrough math tuition not only improves O
      Level scores һowever ⅼikewise grows abstract hought
      abilities іmportant fօr lifelong discovering.

      Tuition in junior college math gears սp trainees witһ statistical methods аnd probability versions crucial fοr analyzing data-driven concerns іn A Level papers.

      Ᏼy integrating proprietary methods ᴡith the MOE curriculum, OMT ᥙses an unique strategy
      tһat highlights clearness and deepness in mathematical thinking.

      Detailed remedies offered оn thе internet leh, teaching уou exactⅼy how to address problems properly
      for far Ƅetter qualities.

      Math tuition supplies targeted method ѡith prwvious examination documents, familiarizing trainees ᴡith concern patterns
      seen іn Singapore’s national analyses.

      Here іs my web site – primary math tuition

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

      Diplomi_pbMt

      3 Oct 25 at 6:47 pm

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

      Diplomi_szOl

      3 Oct 25 at 6:47 pm

    22. купить аттестат за 11 класс [url=https://rudik-diplom14.ru]купить аттестат за 11 класс[/url] .

      Diplomi_fiea

      3 Oct 25 at 6:48 pm

    23. This is a topic which is close to my heart… Many thanks!
      Where are your contact details though?

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

      Diplomi_ecer

      3 Oct 25 at 6:49 pm

    25. ставки на футбол [url=prognozy-na-futbol-10.ru]ставки на футбол[/url] .

    26. купить легальный диплом колледжа [url=https://frei-diplom3.ru]купить легальный диплом колледжа[/url] .

      Diplomi_teKt

      3 Oct 25 at 6:49 pm

    27. It’s awesome to pay a visit this web site and reading the views of all colleagues
      on the topic of this article, while I am also keen of getting know-how.

    28. Every weekend i used to pay a visit this web page, as i want enjoyment, since this this
      web page conations in fact good funny stuff too.

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

      Diplomi_lcoi

      3 Oct 25 at 6:51 pm

    30. прогноз ставок на футбол [url=https://prognozy-na-futbol-10.ru]https://prognozy-na-futbol-10.ru[/url] .

    31. Добро пожаловать в Vodka
      Casino, где каждый найдет что-то для себя!
      Здесь вас ждут великолепные предложения, интересные игры и огромные шансы
      на победу. Водка казино.

      Почему стоит выбрать Vodka Casino?

      Удобный интерфейс для всех игроков.

      Возможности для крупных побед с каждой ставкой.

      Регулярные акции для новичков
      и постоянных игроков.
      Множество способов оплаты.

      Начните играть в Vodka Casino и выиграйте
      прямо сейчас!

    32. купить диплом в спб [url=www.rudik-diplom5.ru]купить диплом в спб[/url] .

      Diplomi_cfma

      3 Oct 25 at 6:52 pm

    33. Lucky Mate is an online casino for Australian players, offering pokies, table games, and live dealer options. It provides a welcome bonus up to AUD 1,000, accepts Visa, PayID, and crypto with AUD 20 minimum deposit, and has withdrawal limits of AUD 5,000 weekly. Licensed, it promotes safe play: Lucky Mate

      Edwardfrevy

      3 Oct 25 at 6:54 pm

    34. Project-based learning ɑt OMT transforms mathematics гight іnto hands-on enjoyable, triggering enthusiasm іn Singapore pupils for superior exam гesults.

      Ⲥhange math obstacles іnto triumphs ѡith OMT Math Tuition’ѕ blend of online and on-site alternatives,
      baϲked by а track record of student excellence.

      Singapore’ѕ emphasis οn crucial analyzing mathematics highlights
      tһe importance օf math tuition, ᴡhich assists students establish tһe
      analytical abilities required Ьy the nation’s forward-thinking curriculum.

      Math tuition addresses specific discovering rates, enabling primary trainees
      tߋ deepen understanding of PSLE subjects ⅼike aгea, perimeter, and volume.

      Comprehensive protection ߋf the whoⅼe O Level syllabus іn tuition maks certain no subjects, fгom sets tօ vectors, аre ignorеd іn a pupil’s alteration.

      Tuition ѕhows mistake analysis strategies, aiding junior university student prevent usual risks іn A
      Level computations and proofs.

      Distinctly, OMT enhances tһe MOE educational program ԝith
      a proprietary program tһаt consists of real-tіme progression monitoring
      for tailored enhancement strategies.

      Endless access tο worksheets mеans yoս practice ᥙntil
      shiok, increasing yߋur math confidence and grades in a snap.

      Ꮃith mathematics scores impacting higһ school placements,
      tuition іѕ essential fօr Singapore primary trainees goіng
      for elite organizations tһrough PSLE.

      Ѕtoρ by mү site; math tuition singapore (Manual)

      Manual

      3 Oct 25 at 6:56 pm

    35. купить диплом кандидата наук [url=www.rudik-diplom1.ru/]купить диплом кандидата наук[/url] .

      Diplomi_woer

      3 Oct 25 at 6:56 pm

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

      Diplomi_yoKt

      3 Oct 25 at 6:57 pm

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

      Diplomi_skkt

      3 Oct 25 at 6:57 pm

    38. купить диплом в череповце [url=https://www.rudik-diplom7.ru]https://www.rudik-diplom7.ru[/url] .

      Diplomi_jqPl

      3 Oct 25 at 6:57 pm

    39. Having read this I thought it was really informative.
      I appreciate you finding the time and energy to put this information together.
      I once again find myself spending a significant amount of time both reading and posting comments.

      But so what, it was still worthwhile!

      AYUTOGEL

      3 Oct 25 at 6:58 pm

    40. Hurrah! Finally I got a web site from where I be able to really take helpful facts regarding my study and
      knowledge.

      Eternal Lunesta

      3 Oct 25 at 6:58 pm

    41. Hi my loved one! I want to say that this article is amazing, great written and include approximately all vital
      infos. I’d like to see extra posts like this
      .

      RR99

      3 Oct 25 at 6:58 pm

    42. футбол ставки [url=http://prognozy-na-futbol-10.ru]http://prognozy-na-futbol-10.ru[/url] .

    43. купить диплом с проводкой моих [url=www.frei-diplom2.ru]купить диплом с проводкой моих[/url] .

      Diplomi_xvEa

      3 Oct 25 at 6:59 pm

    44. Школа SensoTango в Мытищах — место, где танго становится языком общения и вдохновения. Педагог с 25-летним танцевальным стажем и сертификациями ORTO CID UNESCO и МФАТ даёт быстрый старт новичкам, развивает музыкальность и технику импровизации, есть группы и индивидуальные занятия, милонги и мастер-классы. Ученики отмечают тёплую атмосферу и ощутимый прогресс. Узнайте расписание и запишитесь на https://sensotango.ru/ — первый шаг к новому хобби проще, чем кажется.

      fetermMus

      3 Oct 25 at 7:00 pm

    45. купить диплом в кемерово [url=rudik-diplom2.ru]купить диплом в кемерово[/url] .

      Diplomi_tnpi

      3 Oct 25 at 7:01 pm

    46. купить свидетельство о браке [url=http://www.rudik-diplom14.ru]купить свидетельство о браке[/url] .

      Diplomi_dzea

      3 Oct 25 at 7:01 pm

    47. купить диплом медбрата [url=www.rudik-diplom1.ru]купить диплом медбрата[/url] .

      Diplomi_ryer

      3 Oct 25 at 7:02 pm

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

      Diplomi_elKt

      3 Oct 25 at 7:02 pm

    49. Wow, this paragraph is nice, my sister is analyzing these kinds
      of things, so I am going to convey her.

    50. купить диплом в спб [url=www.rudik-diplom4.ru]купить диплом в спб[/url] .

      Diplomi_sqOr

      3 Oct 25 at 7:03 pm

    Leave a Reply