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 22,630 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 , , ,

    22,630 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. Unquestionably believe that which you stated. Your favorite reason seemed to be on the
      internet the easiest thing to be aware of. I say to you, I definitely get irked while people consider
      worries that they plainly do not know about.
      You managed to hit the nail upon the top as well as defined out the whole
      thing without having side effect , people could take a signal.
      Will likely be back to get more. Thanks

      Trueflip Casino

      20 Aug 25 at 3:37 pm

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

      Diplomi_dwpl

      20 Aug 25 at 3:38 pm

    3. It’s the best time to make some plans for the long run and it’s time to be happy.
      I have read this submit and if I could I wish to recommend you some attention-grabbing issues or
      tips. Perhaps you can write subsequent articles referring to this article.

      I want to read even more things about it!

      phim con heo

      20 Aug 25 at 3:39 pm

    4. Нey There. I found your weblog uѕing msn. That іs
      a very well written artiсle. I will be sure tօ ƅookmarқ it and return to read extrа
      of your helpful informatіon. Thank you for thе post.
      I will certainly comеback.

      my web site … uniform Apparel companies

    5. Howardhib

      20 Aug 25 at 3:42 pm

    6. Generally I don’t read post on blogs, however I would like to say that this write-up very pressured me to take a look at and do
      it! Your writing taste has been surprised me. Thank you, quite nice post.

    7. viagra 100 coupon: sildenafil uk best price – sildenafil 100mg canada

      PeterTEEFS

      20 Aug 25 at 3:51 pm

    8. Chriszek

      20 Aug 25 at 3:53 pm

    9. Excellent write-up. I certainly love this website.
      Stick with it!

      Lizoradex

      20 Aug 25 at 4:00 pm

    10. Valuable info. Fortunate me I found your website by accident, and I’m
      shocked why this twist of fate didn’t took place earlier!
      I bookmarked it.

      Thanks

      20 Aug 25 at 4:01 pm

    11. There іs certainly а lot to know aƄout thiѕ subject.
      Ι love аll of the points you’ve made.

      Taкe a look at my webpage … scrub suits

      scrub suits

      20 Aug 25 at 4:01 pm

    12. Very nice write-up. I definitely love this website.

      Thanks!

    13. Wow! At last I got a blog from where I can actually get useful facts concerning
      my study and knowledge.

    14. оценка ценных бумаг москва https://ocenochnaya-kompaniya1.ru

    15. Kamagra oral jelly USA availability: Online sources for Kamagra in the United States – Online sources for Kamagra in the United States

      RichardTit

      20 Aug 25 at 4:13 pm

    16. горшок для растений с автополивом [url=http://kashpo-s-avtopolivom-spb.ru/]горшок для растений с автополивом[/url] .

      gorshok s avtopolivom_kgsr

      20 Aug 25 at 4:14 pm

    17. Chriszek

      20 Aug 25 at 4:14 pm

    18. 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.

    19. plinko kz [url=www.plinko-kz2.ru]plinko kz[/url]

      plinko_kz_ufer

      20 Aug 25 at 4:20 pm

    20. The main one is the ease of installation, domfenshuy.net which is achieved through a special profile.

      Henrysom

      20 Aug 25 at 4:20 pm

    21. Howardhib

      20 Aug 25 at 4:22 pm

    22. Admiring the dedication you put into your blog
      and in depth information you present. It’s awesome to come across a blog every once in a while that isn’t the same out
      of date rehashed information. Wonderful read! I’ve saved
      your site and I’m adding your RSS feeds to my Google account.

      NOHU

      20 Aug 25 at 4:22 pm

    23. fantastic put up, very informative. I ponder why the other specialists of this sector do not understand this.

      You should proceed your writing. I’m sure, you’ve a
      huge readers’ base already!

      NorthBridge AI

      20 Aug 25 at 4:23 pm

    24. плинко [url=https://plinko3002.ru]https://plinko3002.ru[/url]

      plinko_kz_zhPa

      20 Aug 25 at 4:23 pm

    25. Its like you read my mind! You appear to
      know a lot about this, like you wrote the book in it or something.
      I think that you could do with some pics to drive the message home a bit, but other
      than that, this is magnificent blog. An excellent read.

      I will certainly be back.

    26. Thermal insulation of pipelines also plays a key role besttoday.org in reducing operating costs. Thanks to effective thermal insulation, heat loss is significantly reduced, which directly affects heating costs.

      Nathangresk

      20 Aug 25 at 4:26 pm

    27. What’s up, this weekend is nice for me, as this occasion i am reading this enormous educational article
      here at my home.

    28. melbet apps [url=http://melbet3006.com]melbet apps[/url]

      melbet_nvpa

      20 Aug 25 at 4:30 pm

    29. Hola! I’ve been following your web site for some time now and finally got
      the bravery to go ahead and give you a shout out from New Caney Tx!
      Just wanted to say keep up the great work!

    30. Chriszek

      20 Aug 25 at 4:36 pm

    31. Выгодные условия доступны в Казино Ramenbet слот 10000 Wonders MultiMax.

      KennethWet

      20 Aug 25 at 4:37 pm

    32. When someone writes an article he/she keeps the idea of a user in his/her mind
      that how a user can know it. So that’s why this article
      is perfect. Thanks!

    33. SildenaPeak [url=https://sildenapeak.com/#]SildenaPeak[/url] SildenaPeak

      RobertCat

      20 Aug 25 at 4:50 pm

    34. Excellent post. I was checking constantly this blog and I’m
      impressed! Very helpful information specially the last part 🙂 I care for such info
      a lot. I was seeking this certain information for
      a very long time. Thank you and best of luck.

      ameliyati

      20 Aug 25 at 4:51 pm

    35. Hi there, after reading this amazing article i am as well happy
      to share my familiarity here with colleagues.

    36. Chriszek

      20 Aug 25 at 4:57 pm

    37. My coder is trying to convince me to move to .net from PHP.
      I have always disliked the idea because of the expenses.

      But he’s tryiong none the less. I’ve been using Movable-type
      on various websites for about a year and am worried about switching to another platform.
      I have heard very good things about blogengine.net. Is there a way I can transfer
      all my wordpress content into it? Any kind of help would be really appreciated!

    38. салон красоты санкт петербург beauty-salon-spb.ru/

      beauty-salon-909

      20 Aug 25 at 4:58 pm

    39. Howardhib

      20 Aug 25 at 5:01 pm

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

      DavidVok

      20 Aug 25 at 5:04 pm

    41. Согласен с предыдущим оратором, и в дополнение хочу сказать:

      Для тех, кто ищет информацию по теме “clasifieds.ru”, нашел много полезного.

      Вот, делюсь ссылкой:

      [url=https://clasifieds.ru]https://clasifieds.ru[/url]

      Спасибо за внимание.

      rusPoito

      20 Aug 25 at 5:07 pm

    42. Charliesoall

      20 Aug 25 at 5:08 pm

    43. melbet казино [url=https://melbet3006.com]melbet казино[/url]

      melbet_bhpa

      20 Aug 25 at 5:09 pm

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

      JesseBut

      20 Aug 25 at 5:15 pm

    45. This article gives clear idea for the new viewers of blogging, that really how to do blogging and site-building.

    46. Chriszek

      20 Aug 25 at 5:18 pm

    47. При таких проявлениях самостоятельное вмешательство не рекомендуется, так как это может привести к ухудшению состояния. Своевременное обращение к врачу позволит предотвратить тяжелые осложнения и эффективно стабилизировать состояние больного.
      Подробнее можно узнать тут – [url=https://narcolog-na-dom-novosibirsk0.ru/]нарколог на дом недорого[/url]

      ThomasReT

      20 Aug 25 at 5:20 pm

    48. Hi there all, here every person is sharing these kinds of knowledge, so it’s good to read this
      weblog, and I used to pay a visit this weblog every day.

    49. plinko game online [url=www.plinko-kz2.ru]www.plinko-kz2.ru[/url]

      plinko_kz_mwer

      20 Aug 25 at 5:22 pm

    Leave a Reply