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 81,093 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 , , ,

    81,093 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=www.narkolog-na-dom-1.ru/]www.narkolog-na-dom-1.ru/[/url] .

    2. It’s quick to use, taking around 10 to 15 seconds to download a 5-minute video.

    3. купить диплом техникума в спб [url=frei-diplom8.ru]купить диплом техникума в спб[/url] .

      Diplomi_tasr

      7 Oct 25 at 1:01 pm

    4. вывод из запоя москва клиника [url=https://narkologicheskaya-klinika-20.ru]https://narkologicheskaya-klinika-20.ru[/url] .

    5. Развлечение, обучение и маркетинг в одном флаконе. Квизы, или интерактивные опросы, стали неотъемлемой частью современной цифровой культуры. Они повсюду: в социальных сетях, на сайтах, в онлайн-играх.
      Но что же делает их такими популярными и почему они продолжают набирать обороты? Куда свходить на [url=https://webhamster.ru/punbb/viewtopic.php?pid=6021#p6021]квиз в Москве[/url]

      Edwardsog

      7 Oct 25 at 1:02 pm

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

      Diplomi_yiKr

      7 Oct 25 at 1:03 pm

    7. новости легкой атлетики [url=sport-novosti-1.ru]sport-novosti-1.ru[/url] .

    8. I am sure this article has touched all the internet
      viewers, its really really nice article on building up new
      blog.

      부산철거

      7 Oct 25 at 1:04 pm

    9. новости тенниса [url=http://sport-novosti-1.ru]http://sport-novosti-1.ru[/url] .

    10.  none of the participants who reported communicating about their desire discrepancies reported this strategy to be unhelpful.ラブドール エロTake AwayMost of the participants indicated that doing nothing was not a helpful strategy,

      ラブドール

      7 Oct 25 at 1:06 pm

    11. В данной обзорной статье представлены интригующие факты, которые не оставят вас равнодушными. Мы критикуем и анализируем события, которые изменили наше восприятие мира. Узнайте, что стоит за новыми открытиями и как они могут изменить ваше восприятие реальности.
      Хочу знать больше – https://devilleelectrique.com/electricien-st-jerome

      WillieememN

      7 Oct 25 at 1:06 pm

    12. купить диплом колледжа пермь [url=www.frei-diplom8.ru]www.frei-diplom8.ru[/url] .

      Diplomi_pksr

      7 Oct 25 at 1:07 pm

    13. Refresh Renovation Southwest Charlotte
      1251 Arrow Pine Ꭰr c121,
      Charlotte, NC 28273, United Ѕtates
      +19803517882
      remodeling consultants in the us

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

      Diplomi_leea

      7 Oct 25 at 1:09 pm

    15. новости хоккея [url=http://sportivnye-novosti-1.ru/]новости хоккея[/url] .

    16. It has worried meterriblyon Sunday afternoons,that is,エロオナホ

      ラブドール

      7 Oct 25 at 1:10 pm

    17. кухни от производителя спб недорого и качественно [url=https://kuhni-spb-4.ru]https://kuhni-spb-4.ru[/url] .

      kyhni spb_xoer

      7 Oct 25 at 1:10 pm

    18. помощь алкоголику на дому [url=https://www.narkolog-na-dom-1.ru]https://www.narkolog-na-dom-1.ru[/url] .

    19. наркологическая услуга москва [url=www.narkologicheskaya-klinika-20.ru/]www.narkologicheskaya-klinika-20.ru/[/url] .

    20. linebet free

      7 Oct 25 at 1:12 pm

    21. Minotaurus ICO’s whitepaper highlights balanced token release. $MTAUR holders shape via DAO—democratic and cool. Casual market entry is spot on.
      minotaurus coin

      WilliamPargy

      7 Oct 25 at 1:13 pm

    22. В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
      Детальнее – https://www.harfabusinesscenter.cz/section-detail/hbc-b-employee-friendly

      MichaelPep

      7 Oct 25 at 1:15 pm

    23. DonaldtiEls

      7 Oct 25 at 1:15 pm

    24. кухня глория [url=http://www.kuhni-spb-4.ru]http://www.kuhni-spb-4.ru[/url] .

      kyhni spb_ccer

      7 Oct 25 at 1:16 pm

    25. новости спорта россии [url=http://sportivnye-novosti-1.ru/]новости спорта россии[/url] .

    26. Hi there, just wanted to mention, I loved this article.
      It was funny. Keep on posting!

      Nordiqo

      7 Oct 25 at 1:16 pm

    27. нарколог выездной [url=https://narkolog-na-dom-1.ru/]narkolog-na-dom-1.ru[/url] .

    28. частная наркологическая клиника [url=https://www.narkologicheskaya-klinika-20.ru]https://www.narkologicheskaya-klinika-20.ru[/url] .

    29. Βy stressing conceptual mastery, OMT discloses math’ѕ internal appeal, igniting love аnd drive for tοp
      exam qualities.

      Get ready for success іn upcoming tests witһ OMT Math Tuition’ѕ exclusive curriculum, designed t᧐ cultivate crucial thinking and self-confidence іn eveгy trainee.

      As math forms thе bedrock of logical thinking ɑnd critical analytical іn Singapore’s education ѕystem, professional math tuition supplies
      tһe tailored assistance required tօ turn obstacles іnto triumphs.

      Tuition programs f᧐r primary mathematics concentrate оn error analysis from ⲣrevious PSLE papers, teaching trainees t᧐
      prevent repeating mistakes іn calculations.

      Tuition fosters sophisticated рroblem-solving abilities,
      essential fօr resolving tһe complex, multi-step questions tһat define O Level mathematics difficulties.

      Junior college math tuition іs essential fߋr A Levels as it strengthens understanding οf innovative calculus subjects ⅼike integration methods
      аnd differential equations, ԝhich аre main to tһe test curriculum.

      OMT’ѕ custom-made curriculum uniquely enhances tһe MOE structure ƅy offering thematic units that link math topics аcross primary to JC levels.

      Ӏn-depth options supplied on the internet leh, training
      you just how to solve probⅼems properly
      for muϲh better qualities.

      Singapore’ѕ focus on рroblem-solving in math tests mаkes tuition vital fоr creating critical thinking abilities рast school hourѕ.

      Visit my blog … bigtits student fuck math tutor

    30. кухня на заказ спб [url=http://www.kuhni-spb-4.ru]http://www.kuhni-spb-4.ru[/url] .

      kyhni spb_umer

      7 Oct 25 at 1:19 pm

    31. купить диплом в славянске-на-кубани [url=https://rudik-diplom15.ru/]https://rudik-diplom15.ru/[/url] .

      Diplomi_vhPi

      7 Oct 25 at 1:20 pm

    32. новости хоккея [url=https://novosti-sporta-7.ru/]новости хоккея[/url] .

    33. Thurmandwelt

      7 Oct 25 at 1:23 pm

    34. наркологическая клиника в москве [url=http://www.narkologicheskaya-klinika-20.ru]http://www.narkologicheskaya-klinika-20.ru[/url] .

    35. лечение зависимости на дому [url=http://narkolog-na-dom-1.ru]http://narkolog-na-dom-1.ru[/url] .

    36. Secondary school math tuition іs vital fߋr Secondary 1 students,helping them integrate technology in math learning.

      Ѕia, thе waу Singapore kids excel іn math globally,
      гeally ᧐ne kind!

      Dear Singapore parents, Singapore math tuition рrovides thе customized touch
      your child shоuld have. Secondary math tuition scaffolds advanced studies efficiently.
      Secondary 1 math tuition dominates inequalities, constructing ѕеlf-confidence acyion Ƅy action.

      Tһe humanitarian element ⲟf ѕome secondary 2 math
      tuition programs оffers scholarships. Secondary 2 math
      tuition һelp impoverished students. Generous secondary 2 math tuition promotes
      equity. Secondary 2 math tuition returns t᧐ society.

      Ԝith Ο-Levels on thе horizon, secondary 3 math exams stress quality.
      Тhese results affect curricula enrichment. Success promotes սseful solving.

      Тһe crucial secondary 4 exams foster international exchanges
      іn Singapore. Secondary 4 math tuition links virtual peers.

      This broaqdening boosts Ο-Level viewpoints.
      Secondary 4 math tuition internationalizes education.

      Math ցoes further tһan exam scores; it’s a vital
      talent in surging ᎪI technologies, essential fоr traffic flow optimization.

      Excelling ɑt math rеquires fostering a love fߋr the discipline ᴡhile applying іts core ideas to
      everyday situations.

      Օne key aspect is that іt helps іn appreciating
      tһe interdisciplinary linkѕ in math frоm ⅾifferent Singapore secondary papers.

      Uѕing online math tuition e-learning systems іn Singapore boosts exam performance ѡith multilingual subtitles.

      Ѕia lor, steady ah, kids thrive іn secondary school
      environment, no undue pressure рlease.

      math tuition

      7 Oct 25 at 1:25 pm

    37. Hello to every body, it’s my first pay a visit of this blog;
      this blog carries remarkable and actually good data for readers.

    38. спорт 24 часа [url=sportivnye-novosti-1.ru]sportivnye-novosti-1.ru[/url] .

    39. свежие новости спорта [url=www.novosti-sporta-7.ru/]www.novosti-sporta-7.ru/[/url] .

    40. Wow that was unusual. I just wrote an incredibly long comment
      but after I clicked submit my comment didn’t show up. Grrrr…
      well I’m not writing all that over again. Regardless,
      just wanted to say excellent blog!

      kl999

      7 Oct 25 at 1:28 pm

    41. купить легальный диплом техникума [url=www.frei-diplom8.ru/]купить легальный диплом техникума[/url] .

      Diplomi_dvsr

      7 Oct 25 at 1:28 pm

    42. новости тенниса [url=https://www.sportivnye-novosti-1.ru]новости тенниса[/url] .

    43. последние новости спорта [url=https://novosti-sporta-7.ru]https://novosti-sporta-7.ru[/url] .

    44. how to get Prednisone legally online: Prednisone tablets online USA – PredniWell Online

      Morrisluh

      7 Oct 25 at 1:32 pm

    45. I’m not sure why but this web site is loading incredibly slow
      for me. Is anyone else having this problem or is it a
      issue on my end? I’ll check back later on and see if the problem still exists.

    46. literally justified byhis vivid aspect,オナホ フィギュアwhen seen gliding at high noon through a dark bluesea,

      ラブドール

      7 Oct 25 at 1:34 pm

    47. новости олимпиады [url=http://sport-novosti-1.ru/]http://sport-novosti-1.ru/[/url] .

    48. купить диплом в волгограде [url=http://rudik-diplom15.ru/]купить диплом в волгограде[/url] .

      Diplomi_qoPi

      7 Oct 25 at 1:36 pm

    49. ラブドール(2) In your own apartment building,you can interfere with radioreception at times when the enemy wants everybody to listen.

      ラブドール

      7 Oct 25 at 1:38 pm

    Leave a Reply