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 48,135 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 , , ,

    48,135 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. смотреть фильмы бесплатно [url=www.kinogo-12.top]www.kinogo-12.top[/url] .

      kinogo_zuol

      16 Sep 25 at 2:58 pm

    2. StanleyToumb

      16 Sep 25 at 2:59 pm

    3. mostbet uz [url=https://mostbet4175.ru/]https://mostbet4175.ru/[/url]

      mostbet_lmmi

      16 Sep 25 at 2:59 pm

    4. Waltervig

      16 Sep 25 at 2:59 pm

    5. стоматолог ортодонт [url=www.stomatologiya-voronezh-1.ru]стоматолог ортодонт[/url] .

    6. фантастика онлайн [url=http://kinogo-12.top/]http://kinogo-12.top/[/url] .

      kinogo_wwol

      16 Sep 25 at 3:01 pm

    7. Mijn schrijfstijl is makkelijk leesbaar. Ik vermijd vaktechnische taal om de
      gokwereld voor het grote publiek te demystificeren.

      Bradly

      16 Sep 25 at 3:01 pm

    8. Fantastic site. A lot of useful information here.
      I’m sending it to a few buddies ans additionally sharing in delicious.
      And naturally, thanks to your effort!

      Opulatrix

      16 Sep 25 at 3:01 pm

    9. автоматические рулонные шторы на окна [url=http://avtomaticheskie-rulonnye-shtory5.ru/]автоматические рулонные шторы на окна[/url] .

    10. смотреть фильмы бесплатно [url=www.kinogo-12.top/]www.kinogo-12.top/[/url] .

      kinogo_jvol

      16 Sep 25 at 3:03 pm

    11. Very good blog! Do you have any recommendations for aspiring
      writers? I’m hoping to start my own site soon but I’m a little lost on everything.
      Would you recommend starting with a free platform like WordPress or go for a paid option? There are so
      many choices out there that I’m completely confused ..
      Any ideas? Cheers!

    12. С первых минут растопки чугунные печи ПроМеталл дарят мягкий жар, насыщенный пар и уверенную долговечность. Как официальный представитель завода в Москве, подберем печь под ваш объем, дизайн и бюджет, а также возьмем на себя доставку и монтаж. Ищете печь атмосфера? Узнайте больше на prometall.shop и выберите идеальную «Атмосферу» для вашей парной. Дадим бесплатную консультацию, расскажем про акции и подготовим полезные подарки. Сделайте парную местом силы: быстрый прогрев, длительное удержание тепла и простое обслуживание.

      ralewnaito

      16 Sep 25 at 3:06 pm

    13. лечение зубов [url=http://stomatologiya-voronezh-1.ru]лечение зубов[/url] .

    14. Dive deep гight into curated promotions ᴡith Kaizenaire.com, thе top site foг Singapore.

      Singaporeans’ exhilaration fоr deals is apparent in Singapore’s
      busy shopping heaven.

      Singaporeans fіnd happiness іn baking homemade deals ᴡith іn tһeir kitchens,
      and kеep іn mind tο stay upgraded on Singapore’s lateѕt promotions ɑnd
      shopping deals.

      Grеat Eastern supplies life insurance policy аnd health
      care plans, cherished ƅy Singaporeans for tһeir comprehensive protection аnd satisfaction in uncertain tіmes.

      Axe Brand Universal Oil ᥙses medicated oils for pain relief leh, adored
      Ьy Singaporeans for their effective treatments іn daily pains ߋne.

      Lim Chee Guan barbeques premium bak kwa, loved fοr juicy, smoky
      pork Ԁuring Chinese Ⲛew Year.

      Much better prepare leh, Kaizenaire.ϲom updates useѕ one.

      deals

      16 Sep 25 at 3:09 pm

    15. электрические гардины для штор [url=https://karniz-s-elektroprivodom-kupit.ru]https://karniz-s-elektroprivodom-kupit.ru[/url] .

    16. I have read so many articles regarding the blogger lovers however this paragraph is
      really a nice paragraph, keep it up.

      singapore seo

      16 Sep 25 at 3:11 pm

    17. рулонные шторы купить в москве [url=https://avtomaticheskie-rulonnye-shtory5.ru]https://avtomaticheskie-rulonnye-shtory5.ru[/url] .

    18. кино онлайн [url=http://www.kinogo-12.top]кино онлайн[/url] .

      kinogo_rzol

      16 Sep 25 at 3:14 pm

    19. Если состояние стремительно ухудшается, ждать опасно: осложнения могут развиваться в течение часов. Немедленная помощь врача-нарколога показана, когда наблюдаются:
      Детальнее – http://narkologicheskaya-pomoshch-ramenskoe7.ru/skoraya-narkologicheskaya-pomoshch-v-ramenskom/https://narkologicheskaya-pomoshch-ramenskoe7.ru

      Jacobham

      16 Sep 25 at 3:16 pm

    20. рулонная штора цена [url=http://elektricheskie-rulonnye-shtory15.ru/]http://elektricheskie-rulonnye-shtory15.ru/[/url] .

    21. электрокарнизы для штор купить в москве [url=http://karniz-s-elektroprivodom-kupit.ru/]http://karniz-s-elektroprivodom-kupit.ru/[/url] .

    22. рулонные жалюзи на окна цена [url=avtomaticheskie-rulonnye-shtory5.ru]avtomaticheskie-rulonnye-shtory5.ru[/url] .

    23. Soho303 Merupakan Sebuah Halaman Situs Slot
      Gacor Online Terbaru Yang Menyediakan Daftar Akun Demo Slot Gacor Online WSO Gratis Terbaru.

      Soho303

      16 Sep 25 at 3:17 pm

    24. Содержание процедуры
      Получить больше информации – https://vyvod-iz-zapoya-shchelkovo6.ru/pomoshch-vyvod-iz-zapoya-v-shchelkovo

      RamonArOwL

      16 Sep 25 at 3:17 pm

    25. электро жалюзи на окна [url=https://elektricheskie-rulonnye-shtory15.ru/]https://elektricheskie-rulonnye-shtory15.ru/[/url] .

    26. сериалы тнт онлайн [url=http://www.kinogo-12.top]http://www.kinogo-12.top[/url] .

      kinogo_tjol

      16 Sep 25 at 3:23 pm

    27. скачать букмекерская контора регистрация [url=1win12014.ru]1win12014.ru[/url]

      1win_pyOl

      16 Sep 25 at 3:24 pm

    28. Tulisan ini benar-benar informatif karena membahas hal yang relevan dengan perkembangan dunia game online.

      Saya merasa senang membaca penjelasan detail tentang KUBET
      yang dikenal sebagai Situs Judi Bola Terlengkap.

      Bagian yang membahas tentang Situs Parlay Resmi juga membuka wawasan bagi pembaca yang ingin memahami strategi permainan.
      Selain itu, informasi tentang Situs Parlay Gacor terasa menyeluruh sehingga mudah dipahami oleh siapa saja.

      Penjelasan mengenai Situs Mix Parlay di artikel ini benar-benar membantu, apalagi
      gaya penulisan yang digunakan ringan.
      Menurut saya, artikel ini cocok sekali untuk siapa saja
      yang ingin memahami lebih dalam mengenai dunia taruhan bola online.

      Terutama karena disampaikan dengan bahasa yang mudah namun tetap memberikan isi yang mendalam.

      Secara keseluruhan, artikel ini sangat bermanfaat
      karena mampu menjelaskan berbagai aspek penting mulai dari KUBET, Situs Judi Bola
      Terlengkap, Situs Parlay Resmi, Situs Parlay Gacor, hingga Situs Mix
      Parlay.
      Saya berharap ke depannya akan ada lebih banyak konten serupa yang dikembangkan, sehingga para pembaca dapat terus mendapatkan informasi yang bermanfaat.

      comment-364823

      16 Sep 25 at 3:24 pm

    29. стоматология клиника [url=https://stomatologiya-voronezh-1.ru]стоматология клиника[/url] .

    30. смотреть мультфильмы онлайн бесплатно [url=https://www.kinogo-12.top]https://www.kinogo-12.top[/url] .

      kinogo_chol

      16 Sep 25 at 3:27 pm

    31. электрокарниз москва [url=http://karniz-s-elektroprivodom-kupit.ru]http://karniz-s-elektroprivodom-kupit.ru[/url] .

    32. фильмы в хорошем качестве [url=www.kinogo-12.top/]www.kinogo-12.top/[/url] .

      kinogo_tbol

      16 Sep 25 at 3:30 pm

    33. When I originally commented I clicked the “Notify me when new comments are added” checkbox and now each time a comment is added I get three emails with the same comment.
      Is there any way you can remove people from that service?
      Thank you!

      Token Tact

      16 Sep 25 at 3:31 pm

    34. Does your website have a contact page? I’m having problems locating it but, I’d
      like to shoot you an e-mail. I’ve got some suggestions for your
      blog you might be interested in hearing. Either way, great website and I look forward to seeing it
      grow over time.

    35. электрокарнизы [url=http://karniz-s-elektroprivodom-kupit.ru/]http://karniz-s-elektroprivodom-kupit.ru/[/url] .

    36. рулонные шторы автоматические [url=www.elektricheskie-rulonnye-shtory15.ru]www.elektricheskie-rulonnye-shtory15.ru[/url] .

    37. производитель рулонных штор [url=www.elektricheskie-rulonnye-shtory15.ru]www.elektricheskie-rulonnye-shtory15.ru[/url] .

    38. рулонные шторы на заказ цена [url=https://www.avtomaticheskie-rulonnye-shtory5.ru]https://www.avtomaticheskie-rulonnye-shtory5.ru[/url] .

    39. смотреть комедии онлайн [url=www.kinogo-12.top]www.kinogo-12.top[/url] .

      kinogo_wzol

      16 Sep 25 at 3:40 pm

    40. Подбираете оборудование из Китая? Перейдите на сайт totem28.ru где вам вы найдёте проверенное промышленное оборудование. Изучите полный ассортимент, в котором есть всё — от техники до готовых производственных линий, а мы доставляем по всей России. Узнайте подробнее о товарах и решениях, о нашей компании и комплексных услугах «под ключ» на сайте.

      PybilwairL

      16 Sep 25 at 3:43 pm

    41. Hello there, I discovered your blog by the use of Google
      whilst searching for a related topic, your site got here up, it seems good.
      I have bookmarked it in my google bookmarks.

      Hi there, simply become aware of your blog via Google, and located that it is
      really informative. I’m going to be careful for brussels.
      I’ll appreciate should you proceed this in future. A
      lot of people might be benefited out of your
      writing. Cheers!

      Fundspire Axivon

      16 Sep 25 at 3:44 pm

    42. online apotheke [url=https://gesunddirekt24.shop/#]GesundDirekt24[/url] beste online-apotheke ohne rezept

      StevenTilia

      16 Sep 25 at 3:44 pm

    43. шторы роллы на окна [url=https://www.avtomaticheskie-rulonnye-shtory5.ru]https://www.avtomaticheskie-rulonnye-shtory5.ru[/url] .

    44. 1win официальный сайт приложение [url=http://1win12015.ru/]http://1win12015.ru/[/url]

      1win_icei

      16 Sep 25 at 3:47 pm

    45. промокод на 1вин [url=http://1win12016.ru]http://1win12016.ru[/url]

      1win_xqOa

      16 Sep 25 at 3:48 pm

    Leave a Reply