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,712 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,712 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. 1xbet casino Ищете 1xBet официальный сайт? Он может быть заблокирован, но у 1хБет есть решения. 1xbet зеркало на сегодня — ваш главный инструмент. Это 1xbet зеркало рабочее всегда актуально. Также вы можете скачать 1xbet приложение для iOS и Android — это надежная альтернатива. Неважно, используете ли вы 1xbet сайт или 1хБет зеркало, вас ждет полный функционал: ставки на спорт и захватывающее 1xbet casino. 1хБет сегодня — это тысячи возможностей. Начните прямо сейчас!

      MatthewBoymn

      3 Oct 25 at 9:26 pm

    2. Мы понимаем, что каждая минута имеет решающее значение, поэтому наши специалисты готовы выехать на дом в кратчайшие сроки и провести все необходимые процедуры по детоксикации организма. Наша цель — помочь пациенту вернуться к нормальной жизни без лишних стрессов и рискованных попыток самостоятельного лечения.
      Углубиться в тему – http://vyvod-iz-zapoya-krasnodar00.ru

      HenryMut

      3 Oct 25 at 9:27 pm

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

      Diplomi_hoPl

      3 Oct 25 at 9:28 pm

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

      Diplomi_qiOl

      3 Oct 25 at 9:28 pm

    5. купить диплом в химках [url=https://rudik-diplom1.ru/]купить диплом в химках[/url] .

      Diplomi_iker

      3 Oct 25 at 9:28 pm

    6. где купить диплом техникума всем [url=http://www.frei-diplom9.ru]где купить диплом техникума всем[/url] .

      Diplomi_egea

      3 Oct 25 at 9:29 pm

    7. Когда запой становится угрозой для жизни и здоровья, своевременная помощь профессионала может стать решающим фактором для скорейшего восстановления. В Мурманске, где суровые климатические условия добавляют стресса и осложнений, квалифицированные наркологи оказывают помощь на дому, обеспечивая оперативную детоксикацию и индивидуальную терапию в привычной обстановке. Такой подход позволяет пациентам избежать лишних перемещений и получить поддержку в комфортной атмосфере.
      Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-murmansk0.ru/]vyvod-iz-zapoya-klinika murmansk[/url]

      TrentImarf

      3 Oct 25 at 9:29 pm

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

      Diplomi_bxOl

      3 Oct 25 at 9:29 pm

    9. Когда мы решили обновить кухню, первым делом стали сравнивать разные компании. В Кухни в Дом понравилось, что всё организовано комплексно: замер, проект, доставка и сборка включены в стоимость. Дизайнер предложил интересные идеи для небольшой кухни, чтобы сохранить максимум пространства. В итоге гарнитур сделали на заказ, и он идеально подошёл под нашу планировку. Сроки не подвели, привезли даже чуть раньше обещанного. Качество материалов оказалось на высоте, фасады смотрятся стильно и дорого. Уверены, что кухня прослужит нам долгие годы, и теперь советуем Кухни в Дом друзьям, https://kuhni-v-dom.ru/

      Eugeniostync

      3 Oct 25 at 9:29 pm

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

      Diplomi_ctSa

      3 Oct 25 at 9:30 pm

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

    12. купить диплом физика [url=https://rudik-diplom8.ru/]купить диплом физика[/url] .

      Diplomi_bwMt

      3 Oct 25 at 9:30 pm

    13. Keep on writing, great job!

      schwimmbecken

      3 Oct 25 at 9:30 pm

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

      Diplomi_uuKt

      3 Oct 25 at 9:31 pm

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

    16. I’ve been browsing online greater than three hours today, but I by no
      means discovered any interesting article like yours. It’s lovely worth
      enough for me. In my view, if all website owners and bloggers made excellent content material as you did, the internet will probably be
      a lot more useful than ever before.

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

      Diplomi_wtOi

      3 Oct 25 at 9:32 pm

    18. stavki prognozy [url=http://www.novosti-sporta-15.ru]http://www.novosti-sporta-15.ru[/url] .

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

      Diplomi_rkPl

      3 Oct 25 at 9:35 pm

    20. What i don’t understood is if truth be told how you are now not really much more neatly-liked than you may be now.
      You’re so intelligent. You realize thus considerably on the subject
      of this matter, made me in my view believe it from a lot of numerous angles.
      Its like men and women aren’t interested until it is
      one thing to do with Girl gaga! Your personal stuffs excellent.
      At all times maintain it up!

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

      Diplomi_rhoi

      3 Oct 25 at 9:36 pm

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

    23. Andreasvek

      3 Oct 25 at 9:38 pm

    24. It’s a pity you don’t have a donate button! I’d definitely donate to
      this excellent blog! I guess for now i’ll settle for bookmarking
      and adding your RSS feed to my Google account. I look forward to new updates and will
      share this blog with my Facebook group. Talk soon!

      Meteor Profit

      3 Oct 25 at 9:39 pm

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

      Diplomi_syOl

      3 Oct 25 at 9:39 pm

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

      Diplomi_hePi

      3 Oct 25 at 9:39 pm

    27. диплом техникума колледжа купить пять плюс [url=http://www.frei-diplom9.ru]http://www.frei-diplom9.ru[/url] .

      Diplomi_mjea

      3 Oct 25 at 9:40 pm

    28. прогноз футбол [url=prognozy-na-futbol-10.ru]прогноз футбол[/url] .

    29. новости хоккея [url=novosti-sporta-15.ru]novosti-sporta-15.ru[/url] .

    30. Kaizenaire.com beams aѕ tһe prime web site for Singaporeans seeking curated promotions,
      unsurpassable shopping deals, ɑnd brand-specific
      offers.

      Singapore’s shopping paradise condition іs a magnet for residents ᴡho adore discovering covert promotions аnd racking up
      great deals.

      Practicing mindfulness meditation assists stressed ߋut Singaporeans fund calm, аnd bear in mind to гemain upgraded օn Singapore’ѕ moѕt recеnt promotions and shopping deals.

      Nike ⲣrovides sports wear ɑnd footwear,
      cherished Ьy fitness-focused Singaporeans for tһeir ingenious
      layouts аnd efficiency equipment.

      Ԍreat Eastern uses life insurance coverage ɑnd health care
      plazns lor, precious Ƅy Singaporeans fⲟr theіr detailed insurance coverage ɑnd satisfaction іn uncertain tіmes leh.

      Ꮇr Coconut revitalizes witһ fresh coconut drinks,
      preferred for velvety, exotic quenchers оn hot daʏs.

      Eh, why pay full prіce mah, consistently search Kaizenaire.comfor tһe verү beѕt promotions lah.

      Мy web site japan airfare promotions

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

      Diplomi_sxMt

      3 Oct 25 at 9:43 pm

    32. ScottTem

      3 Oct 25 at 9:43 pm

    33. купить диплом образование купить проведенный диплом [url=http://www.frei-diplom2.ru]купить диплом образование купить проведенный диплом[/url] .

      Diplomi_awEa

      3 Oct 25 at 9:43 pm

    34. футбол прогнозы [url=https://www.prognozy-na-futbol-10.ru]футбол прогнозы[/url] .

    35. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically
      tweet my newest twitter updates. I’ve been looking for a plug-in like this for quite some time and was hoping maybe
      you would have some experience with something like this.

      Please let me know if you run into anything. I truly enjoy reading your blog
      and I look forward to your new updates.

    36. PatrickGop

      3 Oct 25 at 9:45 pm

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

      Diplomi_txPl

      3 Oct 25 at 9:46 pm

    38. диплом техникум купить [url=www.frei-diplom12.ru]диплом техникум купить[/url] .

      Diplomi_uhPt

      3 Oct 25 at 9:46 pm

    39. Наша наркологическая клиника предоставляет круглосуточную помощь, использует только сертифицированные медикаменты и строго соблюдает полную конфиденциальность лечения.
      Получить дополнительные сведения – [url=https://kapelnica-ot-zapoya-sochi0.ru/]капельница от запоя недорого[/url]

      Wilfredoxype

      3 Oct 25 at 9:48 pm

    40. Ich mag es, ihre Inhalte zu durchstöbern. Großen Dank!

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

      Diplomi_ncKt

      3 Oct 25 at 9:48 pm

    42. Купить диплом колледжа в Харьков [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .

      Diplomi_upea

      3 Oct 25 at 9:48 pm

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

      Diplomi_obPi

      3 Oct 25 at 9:49 pm

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

      Diplomi_ecOi

      3 Oct 25 at 9:51 pm

    45. t643947 – Everything about this feels neat, organized, and user-friendly overall.

      Ryan Kunishige

      3 Oct 25 at 9:51 pm

    46. спортивные новости [url=https://www.novosti-sporta-15.ru]https://www.novosti-sporta-15.ru[/url] .

    47. Matthewbox

      3 Oct 25 at 9:57 pm

    48. В клинике «НаркоСити» используются только сертифицированные лекарственные средства, которые подбираются индивидуально с учетом состояния пациента:
      Разобраться лучше – [url=https://vyvod-iz-zapoya-krasnodar0.ru/]вывод из запоя капельница[/url]

      Stevevab

      3 Oct 25 at 9:58 pm

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

      Diplomi_yuEa

      3 Oct 25 at 9:58 pm

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

      Diplomi_azOi

      3 Oct 25 at 9:59 pm

    Leave a Reply