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 37,745 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 , , ,

    37,745 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://internet-agentstvo-prodvizhenie-sajtov-seo.ru/]заказать продвижение сайта в москве[/url] .

    2. Raymondvop

      5 Sep 25 at 12:04 am

    3. Когда следует немедленно обращаться за помощью:
      Изучить вопрос глубже – http://алко-ребцентр.рф

      Gerardohob

      5 Sep 25 at 12:04 am

    4. поисковое seo в москве [url=https://poiskovoe-seo-v-moskve.ru/]poiskovoe-seo-v-moskve.ru[/url] .

    5. Raymondvop

      5 Sep 25 at 12:05 am

    6. Thanks for the auspicious writeup. It if truth
      be told used to be a leisure account it. Glance advanced to far introduced
      agreeable from you! By the way, how could we keep in touch?

      website

      5 Sep 25 at 12:06 am

    7. продвижения сайта в google [url=internet-agentstvo-prodvizhenie-sajtov-seo.ru]продвижения сайта в google[/url] .

    8. Create Rss Feed For Your Website And Display Rss Feed website, Jami,

      Jami

      5 Sep 25 at 12:08 am

    9. seo partners [url=https://poiskovoe-seo-v-moskve.ru/]https://poiskovoe-seo-v-moskve.ru/[/url] .

    10. 평소에는 참아내기 바빴던 감정들이 여성전용마사지의 따뜻한 손길 앞에서는 조심스레 스며
      나와, 다시 나답게 살아갈 용기를 얻을
      수 있었어요.

    11. букмекерская. контора. мостбет. [url=http://mostbet4130.ru/]http://mostbet4130.ru/[/url]

    12. https://pharmaexpressfrance.shop/# trouver un mГ©dicament en pharmacie

      WilliamTeeli

      5 Sep 25 at 12:11 am

    13. мостбет на футбол ставки [url=http://mostbet4167.ru/]http://mostbet4167.ru/[/url]

      mostbet_xzKa

      5 Sep 25 at 12:11 am

    14. Мы предлагаем документы университетов, которые находятся на территории всей России. Приобрести диплом о высшем образовании:
      [url=http://wp.nootheme.com/jobmonster/dummy2/companies/ukrdiplom/]купить аттестат за 11 классов оригинал[/url]

      Diplomi_xuPn

      5 Sep 25 at 12:11 am

    15. Вывод из запоя — это комплексная медицинская процедура, направленная на очищение организма, стабилизацию психоэмоционального состояния и восстановление нормального самочувствия. В клинике «Операция Здоровье» пациенты могут получить помощь в стационаре или с выездом врача на дом. Мы работаем круглосуточно, обеспечивая безопасность и анонимность лечения.
      Подробнее можно узнать тут – https://наркология-дома.рф/vyvod-iz-zapoya-czena-v-krasnodare/

      RaymondTup

      5 Sep 25 at 12:12 am

    16. Brandongal

      5 Sep 25 at 12:17 am

    17. Ищете источник ежедневной мотивации заботиться о себе? «Здоровье и гармония» — это понятные советы по красоте, здоровью и психологии, которые делают жизнь легче и радостнее. Даем разборы привычек, практичные лайфхаки и истории для вдохновения — никакой воды и сложностей. Посмотрите свежие статьи и сохраните понравившиеся для практики уже сегодня: https://xn--80aafh2aajttqcc0jrc.xn--p1ai/ Делайте маленькие шаги — результат удивит, а поддержка экспертных материалов поможет не свернуть с пути.

      NisipScusa

      5 Sep 25 at 12:17 am

    18. купить диплом об образовании с реестром [url=https://educ-ua13.ru]купить диплом об образовании с реестром[/url] .

      Diplomi_fapn

      5 Sep 25 at 12:19 am

    19. продвижение сайтов в москве [url=http://internet-agentstvo-prodvizhenie-sajtov-seo.ru]продвижение сайтов в москве[/url] .

    20. поисковое продвижение сайта в интернете москва [url=poiskovoe-seo-v-moskve.ru]poiskovoe-seo-v-moskve.ru[/url] .

    21. После первичной диагностики начинается активная фаза лечения. Современные медикаменты вводятся капельничным методом для быстрого выведения токсинов из организма и восстановления нормальных обменных процессов. Этот этап критически важен для нормализации работы печени, почек и сердечно-сосудистой системы.
      Ознакомиться с деталями – [url=https://reabcentr-narko.ru/]наркологический вывод из запоя[/url]

      KennethHet

      5 Sep 25 at 12:26 am

    22. мостбет скачать приложение [url=https://www.mostbet4165.ru]https://www.mostbet4165.ru[/url]

      mostbet_qfMn

      5 Sep 25 at 12:29 am

    23. комплектная трансформаторная подстанция купить [url=http://dimitrov.forum24.ru/?1-8-0-00000222-000-0-0]комплектная трансформаторная подстанция купить[/url] .

      transformatornie podstancii _pver

      5 Sep 25 at 12:30 am

    24. узи аппарат купить цена [url=www.kupit-uzi-apparat27.ru]узи аппарат купить цена[/url] .

    25. Мы предлагаем документы ВУЗов, которые расположены в любом регионе России. Купить диплом о высшем образовании:
      [url=http://bnsgh.com/read-blog/21233_attestat-o-polnom-srednem-obrazovanii-kupit.html/]купить аттестат за 11 класс спб отзывы[/url]

      Diplomi_gyPn

      5 Sep 25 at 12:33 am

    26. 고된 일상 속, 토닥이에서의
      시간은 저만의 작은 휴가처럼 느껴졌습니다.

      토닥이

      5 Sep 25 at 12:35 am

    27. No matter whether your roofing project is big or small, you can count on our commitment and use of the finest roofing materials to handle the job correctly.

    28. 303Hoki adalah layanan pengiriman terpercaya yang menawarkan kecepatan, keamanan, dan harga terjangkau.
      Dengan 303Hoki, pelanggan dapat mengirim barang
      ke seluruh Indonesia dengan kualitas pelayanan terbaik.

      303hoki

      5 Sep 25 at 12:37 am

    29. В Люберцах капельница от запоя может спасти здоровье — в Stop Alko работают опытные наркологи, которые точно знают, как снять интоксикацию без вреда.
      Подробнее тут – [url=https://kapelnica-ot-zapoya-lyubercy13.ru/]капельница от запоя цена подольск[/url]

      MichaelAreld

      5 Sep 25 at 12:39 am

    30. Dive гight into Kaizenaire.com, Singapore’s premier aggregator
      ߋf shopping promotions аnd unique brand name deals.

      Singaporeans embrace tһeir internal deal hunters іn Singapore, the shopping heaven overflowing ᴡith promotions and
      unique deals.

      Attending health resorts rejuvenates tired Singaporeans, аnd keeρ in mind to remaіn upgraded
      on Singapore’s latеst promotions and shopping deals.

      Ԍreat Eastern սses life insurance policy and health care plans, beloved
      Ƅy Singaporeans fߋr their detailed protection ɑnd comfort in unsure timeѕ.

      Sabrin Goh develops lasting fashion pieces leh, preferred Ƅy
      ecologically mindful Singaporeans fߋr theіr eco-chic
      layouts օne.

      SIS Sugar sweetens ᴡith improved sugars, enjoyed
      fⲟr cooking basics in Singaporean households.

      Auntie ѕuggest leh, check Kaizenaire.com daily fߋr cost savings one.

      Here is my web blog Promotions Singapore

    31. Мы можем предложить документы любых учебных заведений, которые расположены в любом регионе России. Приобрести диплом любого ВУЗа:
      [url=http://job4thai.com/profile/marcelo900295/]купить аттестат 11 классов челябинск[/url]

      Diplomi_mkPn

      5 Sep 25 at 12:40 am

    32. продвижение сайтов интернет магазины в москве [url=http://www.internet-agentstvo-prodvizhenie-sajtov-seo.ru]продвижение сайтов интернет магазины в москве[/url] .

    33. распродажа дизайнерской мебели [url=www.dizajnerskaya-mebel-1.ru/]распродажа дизайнерской мебели[/url] .

    34. защитная пленка для поверхностей [url=http://samokleyushchayasya-plenka-1.ru/]http://samokleyushchayasya-plenka-1.ru/[/url] .

    35. продвижения сайта в google [url=www.poiskovoe-seo-v-moskve.ru/]www.poiskovoe-seo-v-moskve.ru/[/url] .

    36. Brandongal

      5 Sep 25 at 12:45 am

    37. трансформаторные подстанции купить [url=http://www.www.bisound.com/forum/showthread.php?t=1984168]трансформаторные подстанции купить[/url] .

      transformatornie podstancii _uder

      5 Sep 25 at 12:45 am

    38. аудит продвижения сайта [url=https://internet-agentstvo-prodvizhenie-sajtov-seo.ru/]аудит продвижения сайта[/url] .

    39. mostbet uz ilova bilan ro‘yxatdan o‘tish [url=mostbet4169.ru]mostbet uz ilova bilan ro‘yxatdan o‘tish[/url]

      mostbet_jlSt

      5 Sep 25 at 12:46 am

    40. I enjoy, cause I discovered exactly what I
      was looking for. You’ve ended my 4 day long hunt!
      God Bless you man. Have a nice day. Bye

    41. seo network [url=http://poiskovoe-seo-v-moskve.ru]http://poiskovoe-seo-v-moskve.ru[/url] .

    42. мостбет скачать на андроид [url=http://mostbet4128.ru]http://mostbet4128.ru[/url]

    43. seo network [url=https://www.internet-agentstvo-prodvizhenie-sajtov-seo.ru]seo network[/url] .

    44. раскрутка и продвижение сайта [url=https://poiskovoe-seo-v-moskve.ru]раскрутка и продвижение сайта[/url] .

    45. аппарат узи цена [url=https://kupit-uzi-apparat27.ru/]аппарат узи цена[/url] .

    46. Boost Your Search Enginje Ranking By Weeb Copywriting Outside Your Webwite website (Melba)

      Melba

      5 Sep 25 at 1:02 am

    47. поисковое seo в москве [url=www.internet-agentstvo-prodvizhenie-sajtov-seo.ru]www.internet-agentstvo-prodvizhenie-sajtov-seo.ru[/url] .

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

      Diplomi_gxpn

      5 Sep 25 at 1:09 am

    49. Howdy! This post couldn’t be written much better!
      Looking at this post reminds me of my previous roommate!

      He constantly kept preaching about this. I’ll forward this
      information to him. Pretty sure he’s going to have a good read.
      Many thanks for sharing!

    50. поисковое продвижение москва профессиональное продвижение сайтов [url=http://poiskovoe-seo-v-moskve.ru]http://poiskovoe-seo-v-moskve.ru[/url] .

    Leave a Reply