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 38,144 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 , , ,

    38,144 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. Just wish to say your article is as astonishing. The clarity in your post is just spectacular and i could assume you are an expert on this
      subject. Fine with your permission allow me to grab your feed to keep updated with forthcoming post.
      Thanks a million and please carry on the rewarding work.

    2. This is a topic that is near to my heart… Thank you!
      Where are your contact details though?

    3. nexus market darknet darknet drugs nexus onion link [url=https://darknetmarketsgate.com/ ]darknet site [/url]

      Donaldfup

      5 Sep 25 at 10:31 am

    4. darknet markets darknet markets onion dark markets [url=https://darknetmarketstore.com/ ]dark market url [/url]

      Jamespem

      5 Sep 25 at 10:34 am

    5. What’s up Dear, are you truly visiting this site daily, if so afterward you
      will definitely get good knowledge.

      Feel free to visit my web page :: real estate coaching

    6. My spouse and I stumbled over here different website and thought I might check things out.
      I like what I see so now i’m following you. Look forward to looking at your web page again.

      ee88game.net

      5 Sep 25 at 10:35 am

    7. nexus onion link nexus onion mirror nexus onion [url=https://darknetmarketgate.com/ ]dark market url [/url]

      DwayneAricE

      5 Sep 25 at 10:35 am

    8. GerardCig

      5 Sep 25 at 10:36 am

    9. Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
      Более подробно об этом – https://www.verputzer.net/verputzer-bad_kreuznach

      Nathansar

      5 Sep 25 at 10:36 am

    10. E2Bet Indonesia, situs judi online terbesar di Indonesia,
      aman, terpercaya, dan inovatif, bonus menarik dan layanan pelanggan 24/7.
      #E2Bet #E2BetIndonesia #Indonesia

      E2Bet

      5 Sep 25 at 10:37 am

    11. darknet drug links darknet websites dark web market list [url=https://darkmarketsdirectory.com/ ]nexus market [/url]

      BrianWeX

      5 Sep 25 at 10:39 am

    12. Very nice post. I just stumbled upon your blog and wished to say that I’ve really enjoyed
      browsing your blog posts. After all I will be subscribing to your rss feed and I hope you write again soon!

    13. Inspiring story there. What happened after?
      Take care!

    14. Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
      Подробная информация доступна по запросу – https://lutonstay.com/product/helicopter-flight-dubai

      Samuelrag

      5 Sep 25 at 10:43 am

    15. I think the admin of this web site is truly working hard in support of his site,
      since here every data is quality based stuff.

    16. kratonbet link [url=https://linklist.bio/kratonbet777#]kratonbet link[/url] kratonbet login

      CharlesJam

      5 Sep 25 at 10:49 am

    17. купить диплом в кривом роге [url=http://educ-ua5.ru]купить диплом в кривом роге[/url] .

      Diplomi_txKl

      5 Sep 25 at 10:50 am

    18. Hi there mates, how is all, and what you wish for to
      say concerning this piece of writing, in my view its really awesome designed for
      me.

    19. I blog frequently and I truly thank you for your information. The article has truly peaked my interest.
      I’m going to book mark your website and keep checking for new information about once per week.
      I opted in for your Feed too.

      website

      5 Sep 25 at 10:52 am

    20. https://soicau247s.vip

      Very good post. I definitely love this site.

      Continue the good work!

      soicau247s.vip

      5 Sep 25 at 10:53 am

    21. Crypto sports betting has emerged as a popular
      form of gambling that allows users to engage in betting using digital
      currencies such as Bitcoin, Ethereum, and many more.

      homepage

      5 Sep 25 at 10:54 am

    22. mostbet сайт регистрация [url=https://www.mostbet4128.ru]https://www.mostbet4128.ru[/url]

    23. Этот текст призван помочь читателю расширить кругозор и получить практические знания. Мы используем простой язык, наглядные примеры и структурированное изложение, чтобы сделать обучение максимально эффективным и увлекательным.
      Изучить вопрос глубже – https://zeldzaamheid.nl/koffie

      Samuelrag

      5 Sep 25 at 10:59 am

    24. mostbet uz com [url=www.mostbet4166.ru]www.mostbet4166.ru[/url]

      mostbet_wsSr

      5 Sep 25 at 11:00 am

    25. It’s in point of fact a nice and helpful piece of information. I’m glad that you shared this helpful info with us.
      Please keep us up to date like this. Thanks for
      sharing.

      My page Lightsaber uk

      Lightsaber uk

      5 Sep 25 at 11:04 am

    26. GerardCig

      5 Sep 25 at 11:05 am

    27. Jefferybig

      5 Sep 25 at 11:08 am

    28. ClydeVOift

      5 Sep 25 at 11:10 am

    29. диплом реестр купить [url=www.arus-diplom31.ru/]диплом реестр купить[/url] .

    30. Мы изготавливаем дипломы психологов, юристов, экономистов и любых других профессий по приятным ценам. Диплом с проводкой — [url=http://kyc-diplom.com/diplom-s-provodkoj-kupit.html/]kyc-diplom.com/diplom-s-provodkoj-kupit.html[/url]

      Cazrewb

      5 Sep 25 at 11:12 am

    31. nexus onion link darknet links dark web market list [url=https://darknetmarketsgate.com/ ]darknet drug store [/url]

      Donaldfup

      5 Sep 25 at 11:12 am

    32. продвижение сайтов интернет магазины в москве [url=www.poiskovoe-prodvizhenie-sajta-v-internete-moskva.ru/]www.poiskovoe-prodvizhenie-sajta-v-internete-moskva.ru/[/url] .

    33. nexus darknet shop dark markets 2025 nexus onion mirror [url=https://darknetmarketstore.com/ ]nexus darknet site [/url]

      Jamespem

      5 Sep 25 at 11:16 am

    34. hargatoto: hargatoto – hargatoto

      StevenFes

      5 Sep 25 at 11:16 am

    35. Hello there! I could have sworn I’ve been to this blog before but after browsing through some of
      the post I realized it’s new to me. Anyways, I’m definitely happy I found
      it and I’ll be bookmarking and checking back often!

      Check This Out

      5 Sep 25 at 11:16 am

    36. Hi my family member! I wish to say that this article is
      awesome, great written and include approximately all important infos.
      I’d like to look more posts like this .

    37. dark web sites nexus onion mirror nexus onion link [url=https://darknetmarketgate.com/ ]darknet marketplace [/url]

      DwayneAricE

      5 Sep 25 at 11:18 am

    38. blacksprut зеркала blacksprut, блэкспрут, black sprut, блэк спрут, blacksprut вход, блэкспрут ссылка, blacksprut ссылка, blacksprut onion, блэкспрут сайт, blacksprut вход, блэкспрут онион, блэкспрут дакрнет, blacksprut darknet, blacksprut сайт, блэкспрут зеркало, blacksprut зеркало, black sprout, blacksprut com зеркало, блэкспрут не работает, blacksprut зеркала, как зайти на blacksprutd

      RichardPep

      5 Sep 25 at 11:21 am

    39. nexus site official link darknet drug store dark websites [url=https://darkmarketsdirectory.com/ ]darknet sites [/url]

      BrianWeX

      5 Sep 25 at 11:22 am

    40. Hello, Neat post. There’s an issue along with your web site in internet
      explorer, might check this? IE nonetheless is the market chief and a huge
      element of other people will pass over your great writing because
      of this problem.

    41. Купить диплом любого университета!
      Наши специалисты предлагаютбыстро и выгодно приобрести диплом, который выполняется на бланке ГОЗНАКа и заверен мокрыми печатями, водяными знаками, подписями. Диплом пройдет лубую проверку, даже при помощи профессионального оборудования. Достигайте свои цели быстро и просто с нашими дипломами- [url=http://tnrecruit.com/employer/aurus-diplomany/]tnrecruit.com/employer/aurus-diplomany[/url]

      Jariorcup

      5 Sep 25 at 11:24 am

    42. If your soul feels tired, I truly recommend a visit to 인천여성전용마사지.

    43. mawartoto login: mawartoto alternatif – mawartoto link

      StevenFes

      5 Sep 25 at 11:25 am

    44. mostbet com вход [url=www.mostbet4131.ru]mostbet com вход[/url]

    45. GerardCig

      5 Sep 25 at 11:33 am

    Leave a Reply