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 21,650 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 , , ,

    21,650 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. Авто портал https://avtomobilist.kyiv.ua всё об автомобилях: новые модели, цены, рынок подержанных авто, тюнинг и автотехнологии. Полезные материалы для автовладельцев.

      Ronaldhoard

      19 Aug 25 at 9:53 am

    2. Этот информационный обзор станет отличным путеводителем по актуальным темам, объединяющим важные факты и мнения экспертов. Мы исследуем ключевые идеи и представляем их в доступной форме для более глубокого понимания. Читайте, чтобы оставаться в курсе событий!
      Узнать из первых рук – https://www.ankaramerdiven.com/hello-world

      MyronTrasE

      19 Aug 25 at 9:54 am

    3. Pierrequade

      19 Aug 25 at 9:54 am

    4. Онлайн авто-журнал https://mirauto.kyiv.ua с актуальными новостями, аналитикой и обзорами. Тесты автомобилей, тюнинг, технологии и советы по эксплуатации.

      JamesNUT

      19 Aug 25 at 9:55 am

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

    6. Great web site you’ve got here.. It’s difficult to find good quality writing like yours these days.
      I seriously appreciate people like you! Take care!!

    7. What we’re covering
      • Zelensky in Washington: European leaders will join Ukrainian President Volodymyr Zelensky at the White House, as he meets with US President Donald Trump this afternoon. Trump said Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
      [url=https://kra36at.com]kra34 at[/url]
      • Potential security guarantees: At last week’s summit with Trump, Russian President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
      [url=https://kra-37cc.net]kra35 СЃСЃ[/url]
      • On the ground: Zelensky condemned Russia’s latest strikes across Ukraine, which killed at least 10 people, saying the Kremlin intends to “humiliate diplomatic efforts” and underscores “why reliable security guarantees are required.”
      kra37
      https://kra38cc.com

      JorgeKesia

      19 Aug 25 at 9:57 am

    8. WilliamTop

      19 Aug 25 at 9:58 am

    9. What we’re covering
      • Zelensky in Washington: European leaders will join Ukrainian President Volodymyr Zelensky at the White House, as he meets with US President Donald Trump this afternoon. Trump said Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
      [url=https://kra33cc.net]kra32 СЃСЃ[/url]
      • Potential security guarantees: At last week’s summit with Trump, Russian President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
      [url=https://kra36-at.cc]kra30 СЃСЃ[/url]
      • On the ground: Zelensky condemned Russia’s latest strikes across Ukraine, which killed at least 10 people, saying the Kremlin intends to “humiliate diplomatic efforts” and underscores “why reliable security guarantees are required.”
      kra38 cc
      https://kraken35at.com

      Francisrob

      19 Aug 25 at 9:59 am

    10. Авто портал https://avtomobilist.kyiv.ua всё об автомобилях: новые модели, цены, рынок подержанных авто, тюнинг и автотехнологии. Полезные материалы для автовладельцев.

      Ronaldhoard

      19 Aug 25 at 10:00 am

    11. We stumbled over here by a different page and thought I might check things out.
      I like what I see so i am just following you. Look forward to looking over your web page yet again.

      Gunst Bitmark

      19 Aug 25 at 10:00 am

    12. Онлайн авто-журнал https://mirauto.kyiv.ua с актуальными новостями, аналитикой и обзорами. Тесты автомобилей, тюнинг, технологии и советы по эксплуатации.

      JamesNUT

      19 Aug 25 at 10:02 am

    13. Because the admin of this web page is working, no question very shortly it will be renowned,
      due to its quality contents.

      MonitrexPRO

      19 Aug 25 at 10:06 am

    14. Мужской портал https://hooligans.org.ua новости, лайфхаки, обзоры техники, спорт, здоровье и авто. Советы для уверенной и гармоничной жизни.

      Robertinody

      19 Aug 25 at 10:08 am

    15. Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
      Более того — здесь – https://tecla.com.ar/impresora-hp-tintas-latex

      JamesTup

      19 Aug 25 at 10:08 am

    16. Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
      Обратиться к источнику – https://www.badmintonclubtotes.fr/2024/08/26/forum-des-associations-5

      EdwinWep

      19 Aug 25 at 10:08 am

    17. аттестат за 11 класс 2013 купить [url=http://arus-diplom22.ru]аттестат за 11 класс 2013 купить[/url] .

      Diplomi_vdsl

      19 Aug 25 at 10:10 am

    18. Looking for betandreas aviator? Betandreas-official.com is a huge selection of online games. Here you will find a welcome bonus! On our portal you can learn more about BetAndreas: how to top up your balance and withdraw money, how to download and register a mobile application, as well as what games and slots there are. Get full instructions on how to enter the site. We have the best casino games in Bangladesh!

      xatufgom

      19 Aug 25 at 10:10 am

    19. купить аттестат 11 классов в москве [url=arus-diplom25.ru]купить аттестат 11 классов в москве[/url] .

      Diplomi_ocot

      19 Aug 25 at 10:10 am

    20. Мужской портал https://hooligans.org.ua новости, лайфхаки, обзоры техники, спорт, здоровье и авто. Советы для уверенной и гармоничной жизни.

      Robertinody

      19 Aug 25 at 10:15 am

    21. This information is worth everyone’s attention. When can I find out more?

      23winfishing

      19 Aug 25 at 10:15 am

    22. купить аттестат за 11 класс омск [url=www.arus-diplom23.ru]www.arus-diplom23.ru[/url] .

      Diplomi_vjol

      19 Aug 25 at 10:15 am

    23. WilliamTop

      19 Aug 25 at 10:19 am

    24. Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
      Это стоит прочитать полностью – https://sreetravels.online/nature-holiday-quotes

      Juliusquied

      19 Aug 25 at 10:20 am

    25. купить диплом в уфе с реестром [url=www.arus-diplom35.ru]www.arus-diplom35.ru[/url] .

    26. Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
      Погрузиться в научную дискуссию – https://www.africopanigeria.com/standard-image-post

      Juliusquied

      19 Aug 25 at 10:23 am

    27. https://tadalify.shop/# cialis or levitra

      Danielchumn

      19 Aug 25 at 10:23 am

    28. купить аттестаты за 11 класс в томске [url=www.arus-diplom23.ru/]www.arus-diplom23.ru/[/url] .

      Diplomi_oool

      19 Aug 25 at 10:23 am

    29. Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
      Секреты успеха внутри – http://www.brambillacarlocenter.com/news/prova-news

      MyronTrasE

      19 Aug 25 at 10:24 am

    30. где купить диплом с занесением реестр [url=arus-diplom35.ru]где купить диплом с занесением реестр[/url] .

    31. When someone writes an paragraph he/she maintains the
      thought of a user in his/her mind that how a user can know it.
      Thus that’s why this post is perfect. Thanks!

    32. I have been surfing on-line greater than three hours
      as of late, yet I by no means found any interesting article like yours.

      It’s pretty value enough for me. In my opinion, if all site owners and bloggers made excellent content material as you probably
      did, the internet can be much more useful than ever before.

    33. First off I would like to say terrific blog!

      I had a quick question that I’d like to ask if you don’t
      mind. I was curious to find out how you center yourself and clear your mind
      prior to writing. I’ve had a difficult time clearing my thoughts in getting my ideas out.
      I do take pleasure in writing however it just seems like the first 10 to 15 minutes tend to be wasted
      simply just trying to figure out how to begin. Any suggestions or hints?
      Cheers!

    34. Pierrequade

      19 Aug 25 at 10:28 am

    35. First of all I would like to say wonderful blog! I had a quick question that I’d like to ask if you don’t mind.
      I was interested to know how you center yourself and clear your mind prior to writing.
      I’ve had trouble clearing my thoughts in getting my thoughts out.

      I truly do enjoy writing but it just seems like the
      first 10 to 15 minutes are usually lost simply just
      trying to figure out how to begin. Any suggestions or tips?
      Cheers!

    36. Danielevemy

      19 Aug 25 at 10:30 am

    37. Very descriptive blog, I enjoyed that bit.

      Will there be a part 2?

      togel88 link

      19 Aug 25 at 10:33 am

    38. провайдеры интернета казань
      kazan-domashnij-internet004.ru
      интернет провайдер казань

      internetelini

      19 Aug 25 at 10:34 am

    39. как купить официальный аттестат 11 класс [url=http://arus-diplom22.ru/]как купить официальный аттестат 11 класс[/url] .

      Diplomi_ogsl

      19 Aug 25 at 10:35 am

    40. купить аттестат за 11 класс уфа [url=http://arus-diplom25.ru/]купить аттестат за 11 класс уфа[/url] .

      Diplomi_ogot

      19 Aug 25 at 10:36 am

    41. Hey! This post couldn’t be written any better!
      Reading through this post reminds me of my previous room mate!

      He always kept talking about this. I will forward
      this article to him. Pretty sure he will have a good read.

      Many thanks for sharing!

      Quantum Anwar

      19 Aug 25 at 10:36 am

    42. Good day! I just would like to offer you a huge thumbs up for
      your excellent information you’ve got here on this post.
      I will be returning to your web site for more soon.

    43. сантехника gessi [url=https://www.gessi-santehnika-5.ru]сантехника gessi[/url] .

    44. Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
      Выяснить больше – https://adverttv.ru/?paged=33

      Kevincef

      19 Aug 25 at 10:40 am

    45. WilliamTop

      19 Aug 25 at 10:40 am

    46. Публикация приглашает вас исследовать неизведанное — от древних тайн до современных достижений науки. Вы узнаете, как случайные находки превращались в революции, а смелые мысли — в новые эры человеческого прогресса.
      Открыть полностью – https://spotifybrasil.com.br/yoga-poses-for-back-pain

      LoganAlics

      19 Aug 25 at 10:41 am

    47. Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
      Только для своих – https://kansara.org/happy-birthday-k

      LoganAlics

      19 Aug 25 at 10:44 am

    48. You really make it seem so easy with your presentation but I find
      this topic to be actually something that I think I would never understand.
      It seems too complex and extremely broad for me. I’m looking forward for your next
      post, I will try to get the hang of it!

      Website

      19 Aug 25 at 10:44 am

    49. I enjoy reading through a post that can make men and women think.
      Also, many thanks for permitting me to comment!

      macauslot88 link

      19 Aug 25 at 10:49 am

    50. Medicament information. Effects of Drug Abuse.
      buy fluvoxamine without dr prescription
      Everything information about meds. Get now.

    Leave a Reply