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 38,614 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 , , ,

    38,614 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=http://www.narkologicheskaya-klinika-11.ru]http://www.narkologicheskaya-klinika-11.ru[/url] .

    2. маркетинговые стратегии статьи [url=blog-o-marketinge1.ru]маркетинговые стратегии статьи[/url] .

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

    4. купить диплом о техническом образовании с занесением в реестр [url=www.ransis.org/index.php?name=Account&op=info&uname=iliaanisimov]www.ransis.org/index.php?name=Account&op=info&uname=iliaanisimov[/url] .

      Zakazat diplom o visshem obrazovanii!_cmkt

      7 Sep 25 at 11:20 am

    5. Heya i’m for the primary time here. I came across this board and I
      to find It really helpful & it helped me out
      a lot. I hope to provide something again and aid others like you helped
      me.

      kliknij tutaj

      7 Sep 25 at 11:23 am

    6. больница наркологическая [url=www.narkologicheskaya-klinika-11.ru/]www.narkologicheskaya-klinika-11.ru/[/url] .

    7. скачать мостбет кг [url=http://mostbet4160.ru]http://mostbet4160.ru[/url]

      mostbet_alot

      7 Sep 25 at 11:24 am

    8. Нужна медицинскую книжку сегодня по городу недорого? В медицинском центре [url=https://hearth-health.ru]https://hearth-health.ru[/url] можно быстро оформить новую медкнижку от 1 200 ?, продлить существующую по цене от 1 800 ? или получить медицинский документ по цене 1 000 ?, включая сдачу анализов по цене 500 ?. Всё — легально, по всем правилам и без лишних забот. Удобный режим работы, можно подать заявку онлайн и забрать справки быстро. Подробнее на сайте — медкнижка срочно, онлайн заказ, справка по низкой цене.

      Spravkielq

      7 Sep 25 at 11:24 am

    9. Hello, just wanted to say, I liked this article. It was practical.
      Keep on posting!

      P.C.

      7 Sep 25 at 11:25 am

    10. наркологическая больница [url=http://narkologicheskaya-klinika-12.ru]http://narkologicheskaya-klinika-12.ru[/url] .

    11. ск домстрой [url=http://stroitelstvo-domov-irkutsk-2.ru/]http://stroitelstvo-domov-irkutsk-2.ru/[/url] .

    12. Заказать диплом ВУЗа!
      Наши специалисты предлагаютвыгодно и быстро приобрести диплом, который выполняется на оригинальном бланке и заверен печатями, водяными знаками, подписями. Наш диплом пройдет лубую проверку, даже с применением специальных приборов. Решайте свои задачи максимально быстро с нашими дипломами- [url=http://lada-xray.net/member.php?u=2434/]lada-xray.net/member.php?u=2434[/url]

      Jariorzcr

      7 Sep 25 at 11:26 am

    13. Получить диплом ВУЗа поспособствуем. Куплю диплом: цены на документы – [url=http://diplomybox.com/tseny-na-dokumenty/]diplomybox.com/tseny-na-dokumenty[/url]

      Cazriiw

      7 Sep 25 at 11:28 am

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

    15. купить диплом в черкассах [url=www.educ-ua4.ru/]www.educ-ua4.ru/[/url] .

      Diplomi_puPl

      7 Sep 25 at 11:29 am

    16. best darknet markets darkmarket url darknet sites [url=https://darknetmarketstore.com/ ]dark web market [/url]

      Jamespem

      7 Sep 25 at 11:29 am

    17. darknet markets darknet markets onion dark web market list [url=https://darknetmarketsgate.com/ ]dark market 2025 [/url]

      Donaldfup

      7 Sep 25 at 11:30 am

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

    19. мосвет казино [url=mostbet4158.ru]mostbet4158.ru[/url]

      mostbet_xoEn

      7 Sep 25 at 11:31 am

    20. номер наркологии [url=www.narkologicheskaya-klinika-11.ru/]www.narkologicheskaya-klinika-11.ru/[/url] .

    21. Georgehot

      7 Sep 25 at 11:33 am

    22. Thank you for sharing your thoughts. I really appreciate your efforts and
      I am waiting for your next write ups thanks once again.

    23. дом под ключ иркутск цена [url=stroitelstvo-domov-irkutsk-2.ru]stroitelstvo-domov-irkutsk-2.ru[/url] .

    24. цифровой маркетинг статьи [url=http://blog-o-marketinge1.ru]цифровой маркетинг статьи[/url] .

    25. строительство дома [url=stroitelstvo-domov-irkutsk-2.ru]stroitelstvo-domov-irkutsk-2.ru[/url] .

    26. наркология анонимно [url=http://narkologicheskaya-klinika-11.ru/]http://narkologicheskaya-klinika-11.ru/[/url] .

    27. Hey! Someone in my Facebook group shared this
      site with us so I came to look it over. I’m definitely enjoying
      the information. I’m bookmarking and will be tweeting this to my followers!
      Exceptional blog and amazing style and design.

      my web blog: aviamasters

      aviamasters

      7 Sep 25 at 11:39 am

    28. статьи про продвижение сайтов [url=https://www.blog-o-marketinge1.ru]статьи про продвижение сайтов[/url] .

    29. клиника вывод из запоя [url=www.narkologicheskaya-klinika-12.ru]www.narkologicheskaya-klinika-12.ru[/url] .

    30. дом строительство [url=www.stroitelstvo-domov-irkutsk-2.ru/]www.stroitelstvo-domov-irkutsk-2.ru/[/url] .

    31. купить легальный диплом техникума [url=www.forum.l2c4.com/member.php?u=18296/]www.forum.l2c4.com/member.php?u=18296/[/url] .

      Vigodno zakazat diplom yniversiteta!_xokt

      7 Sep 25 at 11:43 am

    32. наркологические клиники в москве [url=https://www.narkologicheskaya-klinika-11.ru]https://www.narkologicheskaya-klinika-11.ru[/url] .

    33. контекстная реклама статьи [url=http://blog-o-marketinge1.ru]контекстная реклама статьи[/url] .

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

    35. Kangaroo Baby is a charming India-based mobile game where players care for adorable kangaroo joeys. With simple gameplay, nurturing tasks, and cute graphics, it’s perfect for kids and casual gamers: Kangaroo drawing tutorials

      BrianCiz

      7 Sep 25 at 11:48 am

    36. как купить диплом занесенный в реестр [url=forum.ozz.tv/memberlist.php?mode=viewprofile&u=12883]как купить диплом занесенный в реестр[/url] .

      Priobresti diplom ob obrazovanii!_znkt

      7 Sep 25 at 11:49 am

    37. seo статьи [url=http://www.statyi-o-marketinge1.ru]seo статьи[/url] .

    38. ск домстрой [url=www.stroitelstvo-domov-irkutsk-2.ru]www.stroitelstvo-domov-irkutsk-2.ru[/url] .

    39. анонимный наркологический центр [url=https://narkologicheskaya-klinika-12.ru/]narkologicheskaya-klinika-12.ru[/url] .

    40. Частный вебмастер https://разработка.site/ – разработка и доработка сайтов. Выполню работы по: разработке сайта, доработке, продвижении и рекламе. Разрабатываю лендинги, интернет магазины, сайты каталоги, сайты для бизнеса, сайты с системой бронирования.

      Kikupamgor

      7 Sep 25 at 11:52 am

    41. купить диплом в запорожье [url=http://educ-ua4.ru/]купить диплом в запорожье[/url] .

      Diplomi_rkPl

      7 Sep 25 at 11:52 am

    42. наркологический диспансер москва [url=https://narkologicheskaya-klinika-12.ru/]narkologicheskaya-klinika-12.ru[/url] .

    43. мостбет вход через соцсети [url=http://mostbet4156.ru/]http://mostbet4156.ru/[/url]

      mostbet_noma

      7 Sep 25 at 11:55 am

    44. Georgehot

      7 Sep 25 at 11:56 am

    45. Hi there friends, its wonderful article regarding tutoringand fully defined, keep it up all the time.

    46. наркологическая помощь [url=www.narkologicheskaya-klinika-11.ru]www.narkologicheskaya-klinika-11.ru[/url] .

    47. построить дом на заказ [url=www.stroitelstvo-domov-irkutsk-2.ru/]www.stroitelstvo-domov-irkutsk-2.ru/[/url] .

    48. Brucechait

      7 Sep 25 at 11:58 am

    49. Brucechait

      7 Sep 25 at 12:00 pm

    Leave a Reply