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,834 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,834 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. This paragraph gives clear idea in favor of the new users of blogging, that genuinely how to do running a blog.

    2. Spot on with this write-up, I honestly think this amazing site needs a great deal more attention. I’ll
      probably be returning to read more, thanks for the info!

    3. диплом реестр купить [url=www.frei-diplom2.ru/]диплом реестр купить[/url] .

      Diplomi_ewEa

      3 Oct 25 at 10:59 pm

    4. купить диплом психолога [url=www.rudik-diplom5.ru]купить диплом психолога[/url] .

      Diplomi_woma

      3 Oct 25 at 10:59 pm

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

      Diplomi_ggkt

      3 Oct 25 at 10:59 pm

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

      Diplomi_jaea

      3 Oct 25 at 11:00 pm

    7. купить диплом строительного колледжа [url=www.frei-diplom9.ru/]www.frei-diplom9.ru/[/url] .

      Diplomi_nxea

      3 Oct 25 at 11:01 pm

    8. купить диплом в рязани [url=http://rudik-diplom4.ru/]купить диплом в рязани[/url] .

      Diplomi_waOr

      3 Oct 25 at 11:01 pm

    9. PatrickGop

      3 Oct 25 at 11:02 pm

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

      Diplomi_cbei

      3 Oct 25 at 11:03 pm

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

      Diplomi_leKt

      3 Oct 25 at 11:05 pm

    12. Доброго!
      Капибара общается с сородичами и всегда живёт в стае. Это дружелюбное и социальное животное. [url=https://www.capybara888.wordpress.com]капибара как питомец[/url] Капибара социальное животное, которое обожает компанию. Посмотри капибара фото и убедись в этом!
      Более подробно по ссылке – https://capybara888.wordpress.com/
      капибара социальное животное
      капибара дружелюбное животное
      капибара что любит есть

      Удачи!

      RobertBoK

      3 Oct 25 at 11:07 pm

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

      Diplomi_tgsr

      3 Oct 25 at 11:08 pm

    14. Группа препаратов
      Изучить вопрос глубже – http://kapelnica-ot-zapoya-sochi0.ru

      Randysealm

      3 Oct 25 at 11:08 pm

    15. купить диплом монтажника [url=https://rudik-diplom5.ru]купить диплом монтажника[/url] .

      Diplomi_kuma

      3 Oct 25 at 11:08 pm

    16. 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 11:10 pm

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

      Diplomi_txOl

      3 Oct 25 at 11:13 pm

    18. купить диплом в бузулуке [url=https://rudik-diplom3.ru/]купить диплом в бузулуке[/url] .

      Diplomi_omei

      3 Oct 25 at 11:14 pm

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

      Diplomi_pcKt

      3 Oct 25 at 11:14 pm

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

      Diplomi_gder

      3 Oct 25 at 11:14 pm

    21. хоккей сегодня прогноз [url=http://prognozy-na-khokkej5.ru/]http://prognozy-na-khokkej5.ru/[/url] .

    22. прочистка труб канализации [url=https://chistka-zasorov-kanalizatsii.kz]прочистка труб канализации[/url] .

    23. купить диплом для техникума цена [url=https://frei-diplom9.ru]купить диплом для техникума цена[/url] .

      Diplomi_fiea

      3 Oct 25 at 11:18 pm

    24. Получение лицензии «под ключ» включало подготовку документов, проверку их соответствия требованиям и полное сопровождение процесса со стороны Журавлев Консалтинг Групп – https://licenz.pro/

      BrianRomma

      3 Oct 25 at 11:18 pm

    25. OMT’s bite-sized lessons avօiⅾ overwhelm, permitting steady love fߋr math to flower аnd influence
      constant test prep ᴡork.

      Established іn 2013 byy Mr. Justin Tan, OMT Math Tuition һas aсtually assisted countless trainees
      ace tests ⅼike PSLE, O-Levels, аnd A-Levels ѡith proven analytical methods.

      Offered tһat mathematics plays a critical role in Singapore’ѕ financial development аnd
      progress, investing іn specialized math tuition equips trainees ᴡith the analytical
      skills required tօ grow in а competitive landscape.

      Tuition programs f᧐r primary mathematics concentrate
      ߋn error analysis from prеvious PSLE documents, teaching
      trainees tօ prevent repeating errors іn computations.

      Recognizing ɑnd rectifying ρarticular weak ρoints, like in chance orr coordinate geometry, mɑkes secondary tuition indispensable for О Level
      excellence.

      Addressing specific understanding designs, math
      tuition mаkes sure junior college pupils grasp subjects аt thеir oᴡn pace
      for A Level success.

      Unlike generic tuition facilities, OMT’ѕ personalized syllabus
      enhances tһe MOE structure Ƅy incorporating real-ԝorld applications,
      makіng abstract mathematics ideas extra relatable аnd understandable
      for pupils.

      Multi-device compatibility leh, ѕо switch оveг
      from laptop cߋmputer to phone and maintain enhancing tһose grades.

      Tuition teachers іn Singapore commonly have insider knowledge ⲟf examination fads,
      guiding trainees tօ concentrate on high-yield subjects.

      Look іnto my blog Singapore A levels Math Tuition

    26. купить диплом в саранске [url=www.rudik-diplom2.ru]купить диплом в саранске[/url] .

      Diplomi_idpi

      3 Oct 25 at 11:19 pm

    27. купить диплом в северске [url=https://rudik-diplom11.ru/]https://rudik-diplom11.ru/[/url] .

      Diplomi_ipMi

      3 Oct 25 at 11:19 pm

    28. медоборудование [url=xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai]xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai[/url] .

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

      Diplomi_edPa

      3 Oct 25 at 11:20 pm

    30. Howdy! I know this is kinda off topic but I was wondering which blog platform are you using for
      this website? I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at alternatives for another platform.
      I would be great if you could point me in the direction of
      a good platform.

      AU88

      3 Oct 25 at 11:20 pm

    31. Refresh Renovation Southwest Charlotte
      1251 Arrow Pine Ɗr c121,
      Charlotte, NC 28273, United Stɑtes
      +19803517882
      Services renovation kitchen

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

      DonaldFlisp

      3 Oct 25 at 11:21 pm

    33. Сразу после вызова нарколог прибывает на дом для проведения тщательного осмотра. Врач измеряет жизненно важные показатели, такие как пульс, артериальное давление и температура, а также собирает краткий анамнез для определения степени алкогольной интоксикации. Эти данные служат основой для разработки индивидуальной стратегии лечения.
      Получить дополнительную информацию – http://kapelnica-ot-zapoya-lugansk-lnr00.ru/kapelnicza-ot-zapoya-czena-lugansk-lnr/

      Scottnal

      3 Oct 25 at 11:22 pm

    34. купить диплом медсестры [url=frei-diplom13.ru]купить диплом медсестры[/url] .

      Diplomi_kfkt

      3 Oct 25 at 11:22 pm

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

      Diplomi_ouer

      3 Oct 25 at 11:23 pm

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

      Diplomi_cdOi

      3 Oct 25 at 11:24 pm

    37. купить диплом колледжа всего [url=https://frei-diplom9.ru/]https://frei-diplom9.ru/[/url] .

      Diplomi_sgea

      3 Oct 25 at 11:25 pm

    38. Minotaurus coin’s utility in boosts and customizations is practical. ICO’s community building events foster loyalty. Early stage feels opportunistic.
      minotaurus coin

      WilliamPargy

      3 Oct 25 at 11:26 pm

    39. ESLATOTO hadir sebagai platform terpercaya 2025 yang menawarkan fitur unggulan deposit QRIS
      mulai 5000. TESLATOTO menyediakan layanan online terpercaya dengan peluang Maxwin setiap hari.
      Nikmati pengalaman bermain aman, cepat, dan menguntungkan bersama situs slot resmi
      yang selalu siap memberikan hadiah besar untuk semua
      pemain.

      SLOT 5000

      3 Oct 25 at 11:26 pm

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

      Diplomi_qhMi

      3 Oct 25 at 11:27 pm

    41. PatrickGop

      3 Oct 25 at 11:27 pm

    42. 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 11:27 pm

    43. Вызов нарколога на дом становится необходимым при любых состояниях, когда отказ от алкоголя сопровождается выраженными симптомами интоксикации и абстиненции. Основные ситуации, в которых срочно требуется профессиональная помощь врача:
      Углубиться в тему – [url=https://narcolog-na-dom-sochi0.ru/]нарколог на дом клиника сочи[/url]

      Duaneopits

      3 Oct 25 at 11:28 pm

    44. If you desire to take much from this article then you have to apply these methods to your won weblog.

      mejaqq

      3 Oct 25 at 11:28 pm

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

      Diplomi_kbOl

      3 Oct 25 at 11:30 pm

    46. где купить диплом об окончании техникума [url=http://frei-diplom9.ru]где купить диплом об окончании техникума[/url] .

      Diplomi_epea

      3 Oct 25 at 11:30 pm

    47. купить диплом в йошкар-оле [url=http://www.rudik-diplom7.ru]купить диплом в йошкар-оле[/url] .

      Diplomi_iqPl

      3 Oct 25 at 11:32 pm

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

      Diplomi_hvMi

      3 Oct 25 at 11:32 pm

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

      Diplomi_alOi

      3 Oct 25 at 11:33 pm

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

      Diplomi_bgkt

      3 Oct 25 at 11:33 pm

    Leave a Reply