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 16,790 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 , , ,

    16,790 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. JacobNit

      13 Aug 25 at 10:51 am

    2. MichaelTut

      13 Aug 25 at 10:51 am

    3. В этой публикации мы предлагаем подробные объяснения по актуальным вопросам, чтобы помочь читателям глубже понять их. Четкость и структурированность материала сделают его удобным для усвоения и применения в повседневной жизни.
      Как достичь результата? – http://pintubahasa.com/group2/2022/02/01/how-to-maintain-a-successful-long-distance-relationship

      Jasonrhini

      13 Aug 25 at 10:51 am

    4. В статье представлены ключевые моменты по актуальной теме, дополненные советами экспертов и ссылками на дополнительные ресурсы. Цель материала — дать читателю инструменты для самостоятельного развития и принятия осознанных решений.
      Практические советы ждут тебя – https://humanityfreedom.info/heilmittel-gegen-krebs-sauerstoffwasser

      Jasonrhini

      13 Aug 25 at 10:53 am

    5. Wonderful goods from you, man. I have have in mind your stuff prior to and you are simply extremely magnificent.
      I actually like what you’ve acquired right
      here, certainly like what you are stating and the
      best way wherein you are saying it. You make it entertaining and you still care for to stay it sensible.
      I cant wait to read much more from you. That is actually a wonderful site.

    6. Good roundup. I grabbed Ice Berry from them and it’s frosty af.

    7. 1х зеркало [url=1win1168.ru]1win1168.ru[/url]

      1win_epma

      13 Aug 25 at 10:57 am

    8. My spouse and I stumbled over here coming from a different website and thought I may as
      well check things out. I like what I see so i am just following you.
      Look forward to checking out your web page repeatedly.

    9. Robertpef

      13 Aug 25 at 11:04 am

    10. CharlesVaX

      13 Aug 25 at 11:05 am

    11. Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
      Погрузиться в детали – http://tacsapka.com/product/soloturk-serit-rozeti

      Alvinbounk

      13 Aug 25 at 11:07 am

    12. Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
      Получить исчерпывающие сведения – https://mega-cul.com/index.php/2024/07/22/bonjour-tout-le-monde

      Alvinbounk

      13 Aug 25 at 11:10 am

    13. В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
      Узнать напрямую – https://henryukazu.com/dare-to-succeed-2

      Josephsib

      13 Aug 25 at 11:10 am

    14. 1win официальный сайт [url=www.1win1170.ru]1win официальный сайт[/url]

      1win_kg_lqEr

      13 Aug 25 at 11:11 am

    15. Can I just say what a relief to find someone that really understands
      what they’re discussing on the web. You definitely know how to bring an issue to
      light and make it important. More people should look at this and
      understand this side of the story. I was surprised
      that you’re not more popular given that you surely have the gift.

    16. Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
      Не упусти важное! – https://www.burg-posterstein.de/blog-2/?lang=fr

      Lanceinduh

      13 Aug 25 at 11:12 am

    17. For the reason that the admin of this web page is working, no uncertainty very soon it will be well-known, due to its quality contents.

      Наземное исполнение очистных сооружений промышленных стоков

      ShaneDrync

      13 Aug 25 at 11:13 am

    18. Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
      Подробная информация доступна по запросу – https://reyhaneco.ir/product/golbarg-girl

      MauriceEvila

      13 Aug 25 at 11:17 am

    19. CharlesVaX

      13 Aug 25 at 11:26 am

    20. Pretty section of content. I just stumbled upon your site and in accession capital to assert that I get actually enjoyed account your blog posts. Any way I will be subscribing to your feeds and even I achievement you access consistently fast.

      Блочно-модульны очистные сооружения

      LewisGuatt

      13 Aug 25 at 11:26 am

    21. JacobNit

      13 Aug 25 at 11:26 am

    22. Indian Meds One: Indian Meds One – top online pharmacy india

      JamesHeelo

      13 Aug 25 at 11:28 am

    23. Приветствую всех форумчан! Хочу поделиться своим опытом использования топливных карт. Возможно, кому-то мой отзыв окажется полезным.
      Раньше, как и многие, я тратил уйму времени на сбор чеков, составление отчетов и постоянные подсчеты. Бензин то дорожал, то дешевел, а бухгалтер, мягко говоря, не был в восторге от кипы бумажек, которые я приносил.- [url=https://vybratauto.ru/]топливные карты для юридических лиц[/url]

      ShawnSlurf

      13 Aug 25 at 11:33 am

    24. Уверен, эта информация будет для вас полезна:

      Особенно понравился материал про mersobratva.ru.

      Смотрите сами:

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

      Буду признателен за ваши отзывы.

      rusPoito

      13 Aug 25 at 11:33 am

    25. Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
      Узнать напрямую – https://espigaoalerta.com.br/2024/08/18/domingo-maior-exibe-hoje-18-08-na-globo-kingsman-servico-secreto

      JoshuaVat

      13 Aug 25 at 11:35 am

    26. I am really grateful to the owner of this website who has shared this fantastic post
      at at this time.

      My site; solar panel cost

      solar panel cost

      13 Aug 25 at 11:36 am

    27. Hey there! Do you use Twitter? I’d like to follow you if that would be okay. I’m definitely enjoying your blog and look forward to new updates.

      лучшие турецкие ткани

      EarnestAbent

      13 Aug 25 at 11:41 am

    28. Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
      Разобраться лучше – https://editssc.com/social-security-card-full-guideline

      Lanceinduh

      13 Aug 25 at 11:41 am

    29. Indian Meds One: best online pharmacy india – indian pharmacy

      JamesHeelo

      13 Aug 25 at 11:46 am

    30. I really like reading through a post that can make men and women think.
      Also, thanks for allowing for me to comment!

    31. Thanks for any other great post. The place else could anyone get that kind of information in such a perfect manner of writing? I have a presentation next week, and I am on the look for such info.

      турецкие фабрики ткани

      EarnestAbent

      13 Aug 25 at 11:52 am

    32. Robertpef

      13 Aug 25 at 11:56 am

    33. Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
      Заходи — там интересно – https://www.drshashankgupta.com/2020/07/17/mother-to-son-kidney-transplant

      JesseBeaug

      13 Aug 25 at 11:57 am

    34. Thomasmub

      13 Aug 25 at 11:58 am

    35. Today, I went to the beachfront with my kids. I found a sea shell and
      gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She placed the shell to her ear and screamed.
      There was a hermit crab inside and it pinched her ear.
      She never wants to go back! LoL I know this is completely off topic but I had to
      tell someone!

    36. Преимущество
      Углубиться в тему – http://snyatie-lomki-rnd7.ru

      BrianHeady

      13 Aug 25 at 12:01 pm

    37. Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
      Узнай первым! – https://abogadosoax.com/?attachment_id=15

      JesseBeaug

      13 Aug 25 at 12:02 pm

    38. Hi there to every , because I am actually keen of reading this web site’s post to be updated regularly.
      It carries pleasant data.

    39. В этой информационной статье вы найдете интересное содержание, которое поможет вам расширить свои знания. Мы предлагаем увлекательный подход и уникальные взгляды на обсуждаемые темы, побуждая пользователей к активному мышлению и критическому анализу.
      Уточнить детали – https://www.solni.pl/2024/05/16/witaj-swiecie

      MichaelEpipt

      13 Aug 25 at 12:05 pm

    40. 1вин бет ставки [url=1win1169.ru]1win1169.ru[/url]

      1win_kg_bbpn

      13 Aug 25 at 12:06 pm

    41. I don’t know whether it’s just me or if everybody else encountering problems with your website.

      It appears like some of the text within your posts
      are running off the screen. Can somebody else please provide feedback and let me know if this is happening to them too?
      This may be a issue with my internet browser because I’ve had this happen previously.
      Kudos

      Here is my web site … Zipline Rental Phoenix

    42. BennieSiz

      13 Aug 25 at 12:09 pm

    43. онлайн ставки на спорт с выводом денег [url=www.1win1168.ru]www.1win1168.ru[/url]

      1win_vuma

      13 Aug 25 at 12:10 pm

    44. Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
      Погрузиться в детали – https://hikayetna.com/from-stigma-to-support-why-arabic-mental-health-education-is-vital

      BrianStymn

      13 Aug 25 at 12:11 pm

    45. 1win mobile [url=https://www.1win1168.ru]https://www.1win1168.ru[/url]

      1win_wyma

      13 Aug 25 at 12:12 pm

    46. Thomasmub

      13 Aug 25 at 12:17 pm

    47. Indian Meds One: Indian Meds One – top 10 online pharmacy in india

      RoccoaritA

      13 Aug 25 at 12:17 pm

    48. В этой информационной статье вы найдете интересное содержание, которое поможет вам расширить свои знания. Мы предлагаем увлекательный подход и уникальные взгляды на обсуждаемые темы, побуждая пользователей к активному мышлению и критическому анализу.
      Нажми и узнай всё – https://millesimeworld.com/blog/gourmet/despensa-natural

      MichaelEpipt

      13 Aug 25 at 12:18 pm

    49. navarro pharmacy miami: propranolol online pharmacy – MediDirect USA

      Justinsoync

      13 Aug 25 at 12:18 pm

    Leave a Reply