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 23,508 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 , , ,

    23,508 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://transformatornye-podstancii-kupit2.ru]https://transformatornye-podstancii-kupit2.ru[/url] .

    2. диплом реестр купить [url=http://arus-diplom35.ru]диплом реестр купить[/url] .

    3. Eugeneimatt

      21 Aug 25 at 5:17 pm

    4. buy amoxicillin over the counter uk: amoxicillin from canada – amoxicillin price canada

      JerryLinee

      21 Aug 25 at 5:17 pm

    5. It’s in fact very difficult in this full of activity
      life to listen news on Television, so I just use web for
      that purpose, and obtain the hottest news.

    6. Thanks for the auspicious writeup. It in fact was once a entertainment account
      it. Glance advanced to more added agreeable
      from you! By the way, how can we communicate?

      FB68.COM

      21 Aug 25 at 5:27 pm

    7. buy amoxicillin online uk: amoxicillin buy online canada – TrustedMeds Direct

      WayneViemo

      21 Aug 25 at 5:29 pm

    8. купить трансформаторные подстанции [url=www.transformatornye-podstancii-kupit2.ru]www.transformatornye-podstancii-kupit2.ru[/url] .

    9. купить аттестат 11 класс спб [url=http://www.arus-diplom24.ru]купить аттестат 11 класс спб[/url] .

      Diplomi_xosa

      21 Aug 25 at 5:32 pm

    10. I will immediately seize your rss as I can’t to find your e-mail subscription link or newsletter service.

      Do you have any? Kindly permit me know in order that I may subscribe.
      Thanks.

      link

      21 Aug 25 at 5:35 pm

    11. Eugeneimatt

      21 Aug 25 at 5:38 pm

    12. I’m truly enjoying the design and layout of your website.

      It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire out a developer to create your theme?
      Excellent work!

      58win

      21 Aug 25 at 5:38 pm

    13. ктп киосковая трансформаторная подстанция [url=www.transformatornye-podstancii-kupit2.ru/]www.transformatornye-podstancii-kupit2.ru/[/url] .

    14. Умные цитаты про любовь. Красивые слова о жизни. Лучшие цитаты о жизни. Цитата это. Лучшие цитаты твиттера. Позитивный человек цитаты. Цитаты счастье. Краткие цитаты великих людей.

      citaty-top-938

      21 Aug 25 at 5:39 pm

    15. купить аттестат за 11 класс рязань [url=http://www.arus-diplom24.ru]http://www.arus-diplom24.ru[/url] .

      Diplomi_atsa

      21 Aug 25 at 5:40 pm

    16. NewEra Protect is gaining attention as a supplement that supports immune strength and overall well-being.

      With its natural ingredients, it’s designed to help the body
      fight off everyday challenges, reduce tiredness, and promote vitality.
      Many people appreciate it as an easy, reliable way to stay
      healthy and energized year-round.

      NewEra Protect

      21 Aug 25 at 5:41 pm

    17. купить диплом с занесением в реестр [url=www.arus-diplom33.ru]купить диплом с занесением в реестр[/url] .

      Diplomi_oxSa

      21 Aug 25 at 5:46 pm

    18. SushiSwap is a decentralized unpleasantness (DEX) and DeFi ecosystem contribution permissionless cosmetic swaps, takings agriculture, liquidity seemly loophole, staking,
      and governance — all powered career the SUSHI token.

      With in preferably of over with a dozen blockchains and advanced features like
      SushiXSwap and BentoBox, SushiSwap continues to incite the
      boundaries of decentralized finance.

      sushi swap crypto

      21 Aug 25 at 5:47 pm

    19. how to get clomid without rx: FertiCare Online – FertiCare Online

      JerryLinee

      21 Aug 25 at 5:48 pm

    20. buy ivermectin tablets: how to buy stromectol – IverGrove

      FrankCax

      21 Aug 25 at 5:50 pm

    21. Academypoker.ru исключительно информационный
      ресурс.

    22. Eugeneimatt

      21 Aug 25 at 5:59 pm

    23. Затяжной запой опасен для жизни. Врачи наркологической клиники в Санкт-Петербурге проводят срочный вывод из запоя — на дому или в стационаре. Анонимно, безопасно, круглосуточно.
      Подробнее тут – [url=https://vyvod-iz-zapoya-v-sankt-peterburge.ru/]вывод из запоя на дому недорого санкт-петербург[/url]

      DavidVow

      21 Aug 25 at 6:01 pm

    24. комплектные трансформаторные подстанции купить [url=http://www.transformatornye-podstancii-kupit1.ru]http://www.transformatornye-podstancii-kupit1.ru[/url] .

    25. Посетитель сам решает нужен ему бонус или нет
      и в любое время может отказаться от поощрения.

    26. Nice post. I was checking continuously this blog and
      I am impressed! Extremely helpful information specially the
      last part 🙂 I care for such info a lot. I was looking for this particular information for a very long time.

      Thank you and best of luck.

    27. AquaSculpt is a breakthrough solution designed to activate
      the body’s natural fat-burning process by mimicking the effects of cold exposure—without the need for ice baths
      or strict crash diets. It helps boost metabolism,
      support weight management, and improve energy levels.

      Many people like it because it offers a simple, convenient, and non-invasive way to reach their fitness goals.

      AquaSculpt

      21 Aug 25 at 6:07 pm

    28. как купить легально диплом о высшем образовании [url=http://arus-diplom34.ru/]как купить легально диплом о высшем образовании[/url] .

      Diplomi_nier

      21 Aug 25 at 6:10 pm

    29. Ищете быструю доставку свежих цветов Минску, Беларуси и миру? Посетите сайт https://sendflowers.by/ и вы найдете самый широкий ассортимент свежих цветов с доставкой на дом. Ознакомьтесь с нашим огромным каталогом, и вы обязательно найдете те цветы, которые вы захотите подарить! Также у нас вы можете заказать доставку роз и букетов в любую точку мира, а букеты составляют только самые опытные флористы! Подробнее на сайте.

      SonersLar

      21 Aug 25 at 6:11 pm

    30. Диагностика включает общий и биохимический анализ крови, оценку работы печени и почек, электрокардиографию и психологическое тестирование для выявления уровня мотивации.
      Изучить вопрос глубже – https://kodirovanie-ot-alkogolizma-pushkino4.ru/kodirovanie-ot-alkogolizma-ceny-v-pushkino

      SteveKnody

      21 Aug 25 at 6:12 pm

    31. трансформаторные подстанции купить [url=https://www.transformatornye-podstancii-kupit1.ru]https://www.transformatornye-podstancii-kupit1.ru[/url] .

    32. купить аттестаты за 11 вечерней школе 1992 2002 п яр или глазов [url=https://www.arus-diplom25.ru]купить аттестаты за 11 вечерней школе 1992 2002 п яр или глазов[/url] .

      Diplomi_pcot

      21 Aug 25 at 6:15 pm

    33. купить аттестат 11 классов москва [url=http://arus-diplom24.ru]http://arus-diplom24.ru[/url] .

      Diplomi_zzsa

      21 Aug 25 at 6:17 pm

    34. I seriously love your site.. Pleasant colors & theme. Did you develop this site yourself?
      Please reply back as I’m hoping to create my own personal blog and would like to learn where you got this from or exactly what the theme is named.
      Thank you!

      ok365

      21 Aug 25 at 6:18 pm

    35. Чем выше активность геймера в Он-Икс Казино, тем больше преимуществ он имеет.

    36. ставки прогнозы [url=stavki-prognozy-one.ru]stavki-prognozy-one.ru[/url] .

    37. JamesWek

      21 Aug 25 at 6:21 pm

    38. Thank you for the good writeup. It in reality was once a amusement
      account it. Look complex to far delivered agreeable from
      you! However, how could we keep in touch?

      roofers near me

      21 Aug 25 at 6:22 pm

    39. Luxury1288 Merupakan Sebuah Link
      Situs Slot Gacor Online Yang Sangat Banyak Peminatnya Dikarenakan Permainan Yang Tersedia Sangat Lengkap.

      Luxury1288

      21 Aug 25 at 6:29 pm

    40. Way cool! Some very valid points! I appreciate you writing this post and the rest of the website is very good.

      Kalevantrex

      21 Aug 25 at 6:31 pm

    41. ставки прогнозы [url=www.stavki-prognozy-one.ru]www.stavki-prognozy-one.ru[/url] .

    42. Everyone loves what you guys are up too. Such clever work and coverage!
      Keep up the wonderful works guys I’ve incorporated you guys to my personal blogroll.

    43. наружная трансформаторная подстанция купить [url=http://transformatornye-podstancii-kupit1.ru/]http://transformatornye-podstancii-kupit1.ru/[/url] .

    44. купить аттестат за 11 класс отзывы [url=http://arus-diplom24.ru/]купить аттестат за 11 класс отзывы[/url] .

      Diplomi_lasa

      21 Aug 25 at 6:40 pm

    45. купить аттестат за 11 класс в сыктывкаре [url=arus-diplom24.ru]купить аттестат за 11 класс в сыктывкаре[/url] .

      Diplomi_uxKn

      21 Aug 25 at 6:41 pm

    46. JamesWek

      21 Aug 25 at 6:42 pm

    47. I always used to study post in news papers but now as I am a user of net therefore from now I am using net for posts, thanks to web.

      My web blog :: OnebetAsia Prediksi SGP

    48. Stavki Prognozy [url=https://stavki-prognozy-one.ru/]https://stavki-prognozy-one.ru/[/url] .

    49. Cabinet IQ Austin
      2419 Ꮪ Bell Blvd, Cedar Park,
      TX 78613, Unitwd Ⴝtates
      +12543183528
      Bookmarks

      Bookmarks

      21 Aug 25 at 6:46 pm

    50. This is a topic that is close to my heart… Take care!
      Where are your contact details though?

    Leave a Reply