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 8,134 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 , , ,

    8,134 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. Does your website have a contact page? I’m having problems locating it but, I’d like to shoot
      you an email. I’ve got some recommendations for your blog you might be interested in hearing.

      Either way, great site and I look forward to seeing it improve over time.

      Trenqor Logic AI

      30 Jul 25 at 4:16 pm

    2. кайт школа Аренда кайта: плюсы и минусы

      RamonLiata

      30 Jul 25 at 4:25 pm

    3. NeuroRelief Rx [url=https://neuroreliefrx.com/#]NeuroRelief Rx[/url] NeuroRelief Rx

      JamesAmola

      30 Jul 25 at 4:31 pm

    4. ua-bay-239

      30 Jul 25 at 4:31 pm

    5. Воспользуйтесь капельницей от запоя в стационаре в Частном Медике?24 (Коломна) — подробнее по ссылке.
      Детальнее – [url=https://kapelnica-ot-zapoya-kolomna.ru/]капельница от запоя выезд[/url]

      Eddiedrell

      30 Jul 25 at 4:40 pm

    6. Узнайте про выведение из запоя в стационаре в Частном Медике 24 (Балашиха) по ссылке.
      Осуществить глубокий анализ – [url=https://vyvod-iz-zapoya-v-stacionare-balashiha12.ru/]вывод из запоя недорого город балашиха[/url]

      ElbertCox

      30 Jul 25 at 4:43 pm

    7. кайт Обучение кайтсёрфингу

      RamonLiata

      30 Jul 25 at 4:44 pm

    8. В Коломне клиника Частный Медик?24 предлагает капельницу от запоя в стационаре — подробности на сайте клиники.
      Подробнее тут – [url=https://kapelnica-ot-zapoya-kolomna14.ru/]капельница от запоя клиника в коломне[/url]

      HenryFem

      30 Jul 25 at 4:50 pm

    9. В этом интересном тексте собраны обширные сведения, которые помогут вам понять различные аспекты обсуждаемой темы. Мы разбираем детали и факты, делая акцент на важности каждого элемента. Не упустите возможность расширить свои знания и взглянуть на мир по-новому!
      Получить дополнительные сведения – https://quick-vyvod-iz-zapoya-1.ru/

      Darrellcex

      30 Jul 25 at 4:53 pm

    10. When choosing a crypto casino, look for those that emphasize provably fair gaming to
      enhance your trust and confidence in the platform.

      Candra

      30 Jul 25 at 4:55 pm

    11. Надёжная капельница от запоя в стационаре в клинике Частный Медик?24 (Коломна) — полный курс лечения, узнайте больше.
      Получить дополнительную информацию – [url=https://kapelnica-ot-zapoya-kolomna16.ru/]kapelnicza-ot-zapoya kolomna[/url]

      AlbertEsold

      30 Jul 25 at 4:55 pm

    12. We have been helping Canadians Borrow Money Against Their Car Title Since March 2009 and
      are among the very few Completely Online Lenders in Canada.

      With us you can obtain a Loan Online from anywhere in Canada as long as
      you have a Fully Paid Off Vehicle that is 8 Years old or newer.
      We look forward to meeting all your financial needs.

    13. Hello would you mind sharing which blog platform you’re using?
      I’m planning to start my own blog soon but I’m having a tough time choosing between BlogEngine/Wordpress/B2evolution and Drupal.
      The reason I ask is because your design and style seems different then most blogs and I’m looking for something
      unique. P.S Apologies for being off-topic but I had to ask!

    14. Hello! Do you know if they make any plugins to protect against hackers?
      I’m kinda paranoid about losing everything I’ve worked hard on. Any suggestions?

      Fluxor Beam AI

      30 Jul 25 at 5:16 pm

    15. прогнозы на спорт бесплатно от профессионалов на сегодня [url=www.prognoz-na-segodnya-na-sport10.ru/]www.prognoz-na-segodnya-na-sport10.ru/[/url] .

    16. MartinShale

      30 Jul 25 at 5:18 pm

    17. ClearMeds Direct: ClearMeds Direct – buy amoxicillin 500mg capsules uk

      BrianTub

      30 Jul 25 at 5:18 pm

    18. Very informative, I found it very useful. Can’t wait to read more. Cheers.

      Scarlett Podolsky

      30 Jul 25 at 5:21 pm

    19. аренда большой яхты [url=https://yachts-charter-dubai.com/]https://yachts-charter-dubai.com/[/url] .

    20. Join millions of traders worldwide with the pocketoptionmobileapp.app. Open trades in seconds, track market trends in real time, and access over 100 assets including forex, stocks, crypto, and commodities. Enjoy fast deposits and withdrawals, clear charts, and a beginner-friendly interface. Perfect for both new and experienced traders – trade on the go with confidence

      Robertaxodo

      30 Jul 25 at 5:26 pm

    21. My family every time say that I am wasting my time here at web, except I know I am getting experience all the time by reading
      such pleasant content.

      Here is my site :: Hungary home WiFi easy setup

    22. прогнозы на спорт онлайн [url=https://prognoz-na-segodnya-na-sport10.ru]https://prognoz-na-segodnya-na-sport10.ru[/url] .

    23. Клиника Частный Медик 24 в Балашихе — профессиональный стационарный вывод из запоя, подробности на сайте.
      Хочу знать больше – [url=https://vyvod-iz-zapoya-v-stacionare-balashiha11.ru/]наркология вывод из запоя[/url]

      RichardBut

      30 Jul 25 at 5:30 pm

    24. кайтсёрфинг “Храм знаний”: кайт школа, где рождается уверенность, где страх уступает место восторгу

      RamonLiata

      30 Jul 25 at 5:33 pm

    25. скачать 1win на андроид с официального сайта [url=1win1140.ru]1win1140.ru[/url]

      1win_egMi

      30 Jul 25 at 5:36 pm

    26. сколько стоит аренда яхты в дубае [url=https://www.yachts-charter-dubai.com]https://www.yachts-charter-dubai.com[/url] .

    27. ставки прогнозы на теннис сегодня [url=www.prognoz-na-segodnya-na-sport9.ru/]www.prognoz-na-segodnya-na-sport9.ru/[/url] .

    28. Hello There. I found your blog using msn. This is an extremely well written article.
      I’ll make sure to bookmark it and come back to
      read more of your useful information. Thanks for the post.
      I will certainly return.

      slot gacor

      30 Jul 25 at 5:39 pm

    29. uakino-702

      30 Jul 25 at 5:40 pm

    30. прогнозы на спорт онлайн [url=https://www.prognoz-na-segodnya-na-sport10.ru]https://www.prognoz-na-segodnya-na-sport10.ru[/url] .

    31. order amoxicillin without prescription [url=https://clearmedsdirect.com/#]order amoxicillin without prescription[/url] Clear Meds Direct

      JamesAmola

      30 Jul 25 at 5:44 pm

    32. Когда организм на пределе, важна срочная помощь в Ростове-На-Дону — это команда опытных наркологов, которые помогут быстро и мягко выйти из запоя без вреда для здоровья.
      Изучите внимательнее – http://vyvod-iz-zapoya-rostov11.ru/

      Gregorysunda

      30 Jul 25 at 5:44 pm

    33. RichardPep

      30 Jul 25 at 5:46 pm

    34. супер прогнозы на футбол [url=https://kompyuternye-prognozy-na-futbol8.ru]https://kompyuternye-prognozy-na-futbol8.ru[/url] .

    35. Пациенты, которые обращаются в нашу клинику, получают целый комплекс преимуществ, благодаря которым лечение проходит максимально эффективно и комфортно:
      Детальнее – http://narcolog-na-dom-novosibirsk0.ru/narkolog-na-dom-czena-novosibirsk/

      Jameshit

      30 Jul 25 at 5:48 pm

    36. прогнозы на спорт с описанием [url=https://prognoz-na-segodnya-na-sport9.ru/]https://prognoz-na-segodnya-na-sport9.ru/[/url] .

    37. uakino-740

      30 Jul 25 at 5:51 pm

    38. прогнозы на спорт [url=https://prognoz-na-segodnya-na-sport10.ru/]прогнозы на спорт[/url] .

    39. MartinShale

      30 Jul 25 at 5:53 pm

    40. مرکز بلیچینگ اسمایل هوم کلینیک

    41. 20
      Углубиться в тему – [url=https://kapelnica-ot-zapoya-kolomna15.ru/]капельница от запоя[/url]

      MatthewNouff

      30 Jul 25 at 5:54 pm

    42. прогноз профессионалов на баскетбол на сегодня [url=http://prognoz-na-segodnya-na-sport10.ru/]http://prognoz-na-segodnya-na-sport10.ru/[/url] .

    43. обучение кайтсёрфингу Кайт лагерь: каникулы с адреналином

      RamonLiata

      30 Jul 25 at 5:57 pm

    44. Hello! I know this is somewhat off topic but I
      was wondering if you knew where I could get a captcha plugin for
      my comment form? I’m using the same blog platform as yours and I’m having difficulty finding one?

      Thanks a lot!

      Also visit my page … internet zonder Hongaars adres

    45. Купить диплом о высшем образовании поспособствуем. Купить диплом тренера – [url=http://diplomybox.com/diplom-trenera/]diplomybox.com/diplom-trenera[/url]

      Cazrhbv

      30 Jul 25 at 6:02 pm

    46. Thanks for the good writeup. It in truth used to be a enjoyment account it. Look complex to more delivered agreeable from you! By the way, how could we keep up a correspondence?
      https://www.google.com.tn/url?q=https://seattlelimorates.com/

      StephenGlona

      30 Jul 25 at 6:02 pm

    47. Наши специалисты используют проверенные медикаменты, которые подбираются индивидуально для каждого пациента:
      Углубиться в тему – [url=https://narcolog-na-dom-voronezh0.ru/]выезд нарколога на дом[/url]

      ArthurVes

      30 Jul 25 at 6:02 pm

    48. обучение кайтсёрфингу “Покупка кайта”: Что нужно знать при покупке кайта

      RamonLiata

      30 Jul 25 at 6:03 pm

    49. Клиника в Балашихе — Частный Медик 24: стационарный вывод из запоя с комфортом и медицинским сопровождением.
      Расширить кругозор по теме – [url=https://vyvod-iz-zapoya-v-stacionare-balashiha13.ru/]срочный вывод из запоя[/url]

      DonaldGueni

      30 Jul 25 at 6:05 pm

    50. Современные методы лечения при выводе из запоя включают как медикаментозную детоксикацию, так и психологическую реабилитацию. В Уфе наркологи используют капельничное введение лекарственных средств, которые помогают быстро вывести токсины, нормализовать обмен веществ и стабилизировать работу внутренних органов. Одновременно с этим проводится психологическая поддержка для снижения эмоционального стресса, связанного с запоем.
      Выяснить больше – https://narcolog-na-dom-ufa0.ru/narkolog-na-dom-czena-ufa

      Williamtathy

      30 Jul 25 at 6:05 pm

    Leave a Reply