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 31,048 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 , , ,

    31,048 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. как купить аттестат за 11 класс сколько стоит [url=www.arus-diplom22.ru/]как купить аттестат за 11 класс сколько стоит[/url] .

      Diplomi_jqsl

      30 Aug 25 at 2:34 pm

    2. Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!

      remontkomand-665

      30 Aug 25 at 2:37 pm

    3. Luxury1288

      30 Aug 25 at 2:37 pm

    4. Attractive element of content. I simply stumbled upon your web site and in accession capital to assert that I get
      in fact enjoyed account your blog posts. Any way I will be subscribing on your feeds and even I achievement
      you get admission to constantly rapidly.

      Quantum Bextra

      30 Aug 25 at 2:40 pm

    5. Low price of wellbutrin sr vs xl , will my partner have any negative feelings? bupropion 150mg xl

      ErcsFlulk

      30 Aug 25 at 2:40 pm

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

    7. Wealth Ancestry Prayer sounds really inspiring. I like how it connects the idea of financial abundance with spiritual grounding and ancestral blessings.

      It feels more meaningful than just focusing on money—it’s about aligning with
      positive energy and guidance for lasting prosperity

    8. JamesCic

      30 Aug 25 at 2:49 pm

    9. Hey there would you mind stating which blog platform you’re working
      with? I’m looking to start my own blog in the near future
      but I’m having a hard time deciding between BlogEngine/Wordpress/B2evolution and Drupal.
      The reason I ask is because your layout seems different then most blogs and I’m looking for something
      unique. P.S Apologies for being off-topic but I had to ask!

    10. купить аттестат за 11 класс в челябинске [url=https://arus-diplom22.ru]купить аттестат за 11 класс в челябинске[/url] .

      Diplomi_ogsl

      30 Aug 25 at 2:55 pm

    11. RichardKap

      30 Aug 25 at 3:01 pm

    12. Luxury1288

      30 Aug 25 at 3:01 pm

    13. реально ли купить аттестат за 11 класс [url=http://arus-diplom23.ru]http://arus-diplom23.ru[/url] .

      Diplomi_zeSr

      30 Aug 25 at 3:02 pm

    14. Hi there, I enjoy reading through your article post. I like to write a little comment to
      support you.

      FinoTraze

      30 Aug 25 at 3:03 pm

    15. Usually I don’t read article on blogs, but I would like to say that this write-up very compelled
      me to try and do it! Your writing taste has been surprised
      me. Thank you, very great post.

      http://w5.angkakeluaran.top/

      Data Sdy

      30 Aug 25 at 3:06 pm

    16. В Красноярске доступно множество услуг для лечение алкоголизма. Наркологические клиники обеспечивают медицинскую помощь, которая включает очистку организма и лечение в стационаре. Опытные наркологи осуществляют кодирование, а также предоставляют психологическую поддержку и реабилитацию. Необходимо помнить о важности консультаций для близких, чтобы обеспечить поддержку семьи; Анонимное лечение гарантирует защиту личной информации, а реабилитационные программы содействуют зависимым вернуться к нормальной жизни. Получите дополнительную информацию на сайте vivod-iz-zapoya-krasnoyarsk012.ru.

    17. The Pineal Guardian sounds really interesting, especially with how it’s designed to support pineal gland health and overall well-being.
      I like that it focuses on natural ingredients instead of synthetic solutions.
      Definitely worth looking into if you’re curious about
      better sleep, focus, and mental clarity.

    18. JamesCic

      30 Aug 25 at 3:11 pm

    19. If some one wishes to be updated with hottest technologies then he must be
      pay a quick visit this site and be up to date all the time.

    20. Близкий человек в запое? Не ждите ухудшения. Обратитесь в клинику — здесь проведут профессиональный вывод из запоя с последующим восстановлением организма.
      Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-v-stacionare-samara14.ru/]вывод из запоя цена в самаре[/url]

      Michaelplert

      30 Aug 25 at 3:16 pm

    21. Капельница от похмелья на дому: действующее лечение и восстановление организма

    22. Организация помощи нарколога на дому в Твери построена по строгому алгоритму, который включает несколько ключевых этапов. Такой комплексный подход позволяет не только быстро вывести токсичные вещества, но и обеспечить всестороннюю поддержку для скорейшего восстановления организма.
      Узнать больше – [url=https://reabcentr-narko.ru/]вывод из запоя круглосуточно в твери[/url]

      MichaelSmurn

      30 Aug 25 at 3:19 pm

    23. купить аттестат за 11 классов в новосибирске [url=http://arus-diplom22.ru/]http://arus-diplom22.ru/[/url] .

      Diplomi_uysl

      30 Aug 25 at 3:19 pm

    24. Howdy! Do you know if they make any plugins to assist with
      SEO? I’m trying to get my blog to rank for some targeted keywords but I’m not seeing very good success.
      If you know of any please share. Thanks!

      buy

      30 Aug 25 at 3:26 pm

    25. Luxury1288

      30 Aug 25 at 3:26 pm

    26. Jorgegrect

      30 Aug 25 at 3:27 pm

    27. Hey! I just wanted to ask if you ever have any issues with hackers?
      My last blog (wordpress) was hacked and I ended up losing many months of hard work due to no backup.
      Do you have any methods to stop hackers?

      토닥이

      30 Aug 25 at 3:28 pm

    28. Этот формат позволяет пациентам получить профессиональную помощь в комфортной домашней обстановке. Такой подход не только обеспечивает удобство, но и гарантирует конфиденциальность, что особенно важно для многих людей.
      Получить дополнительную информацию – [url=https://narcolog-na-dom-v-krasnoyarske55.ru/]врач нарколог на дом красноярск[/url]

      CurtisUsalk

      30 Aug 25 at 3:32 pm

    29. JamesCic

      30 Aug 25 at 3:34 pm

    30. сколько стоит купить диплом в киеве [url=www.educ-ua2.ru/]сколько стоит купить диплом в киеве[/url] .

      Diplomi_mxOt

      30 Aug 25 at 3:39 pm

    31. I am regular visitor, how are you everybody? This paragraph posted at this web page is
      actually pleasant.

      kamboja lotto

      30 Aug 25 at 3:39 pm

    32. где купить аттестат 11 классов в нижнем новгороде [url=https://arus-diplom22.ru/]где купить аттестат 11 классов в нижнем новгороде[/url] .

      Diplomi_sssl

      30 Aug 25 at 3:40 pm

    33. For newest information you have to pay a visit world wide web
      and on the web I found this web site as a most excellent web
      site for newest updates.

    34. It’s an awesome paragraph for all the web viewers; they will take advantage from it I am sure.

      login loket88

      30 Aug 25 at 3:43 pm

    35. ???? 888starz ????? ????? ?? ????? ?? ???? ???????? . ????? ????????? ?????? ????????? ?? 888starz.

      ??? ????? 888starz ??????? ????? ?????? ??? ???? ???????. ???? 888starz ?????? ????? ?? ???????? ??? ?? ??? ??????? ?????????? ???????? .

      ????? 888starz ??????? ?????? ?????????? . ??? ??????? ?? ?????? ???????? ????? ????? .

      ??????? ???????? ????? ?? ???? ??????? ????? ??? ???????? . ????? ??? ???????? ?????? ????? ???????? ??? ???? 888starz .
      п»ї888starz [url=https://888starz-africa.pro]https://888starz-africa.pro/[/url]

      888starz_tgol

      30 Aug 25 at 3:44 pm

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

    37. купить аттестат 11 цены дипломы челябинск ком [url=https://arus-diplom22.ru]https://arus-diplom22.ru[/url] .

      Diplomi_vgsl

      30 Aug 25 at 3:47 pm

    38. Каждый день запоя увеличивает риск для жизни. Не рискуйте — специалисты в Самаре приедут на дом и окажут экстренную помощь. Без боли, стресса и ожидания.
      Подробнее тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara17.ru/]вывод из запоя цена в самаре[/url]

      Justingof

      30 Aug 25 at 3:48 pm

    39. It’s difficult to find experienced people for
      this topic, but you seem like you know what you’re talking about!
      Thanks

      Bigcrypt Edge

      30 Aug 25 at 3:53 pm

    40. купить диплом об образовании в запорожье [url=educ-ua1.ru]купить диплом об образовании в запорожье[/url] .

      Diplomi_juei

      30 Aug 25 at 3:53 pm

    41. DouglasBem

      30 Aug 25 at 3:56 pm

    42. Существуют различные методы и стратегии, которые применяются для устранения зависимостей. Каждый случай уникален, поэтому важно проводить глубокую диагностику и индивидуально разрабатывать план лечения. Мы понимаем, что борьба с зависимостью — это длительный процесс, требующий как медицинской, так и психологической поддержки.
      Подробнее можно узнать тут – [url=https://zavisim-alko.ru/]вывод из запоя на дому недорого в краснодаре[/url]

      KennethGlolo

      30 Aug 25 at 3:57 pm

    43. Use spacers to leave a jaycitynews.com small gap (8 to 12 mm) between the wall and the laminate – this will allow the coating to “breathe” and prevent it from being damaged by changes in temperature and humidity.

      DewayneCreal

      30 Aug 25 at 4:06 pm

    44. SaveTweet suporta uma ampla variedade de formatos de vídeo, incluindo MP4,
      AVI e MOV, dando a você a liberdade de escolher o formato que melhor atende
      às suas necessidades.

    45. RichardPep

      30 Aug 25 at 4:15 pm

    46. JustinRaP

      30 Aug 25 at 4:18 pm

    47. купить аттестат за 11 класс в уральске [url=https://arus-diplom22.ru/]https://arus-diplom22.ru/[/url] .

      Diplomi_rtsl

      30 Aug 25 at 4:18 pm

    48. DouglasBem

      30 Aug 25 at 4:19 pm

    49. сколько стоит купить аттестат за 9 класс [url=www.educ-ua2.ru/]www.educ-ua2.ru/[/url] .

      Diplomi_lpOt

      30 Aug 25 at 4:19 pm

    50. диплом проведенный купить [url=https://arus-diplom33.ru]диплом проведенный купить[/url] .

    Leave a Reply