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 36,632 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 , , ,

    36,632 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. Looking for second-hand? best thrift stores near me We have collected the best stores with clothes, shoes and accessories. Large selection, unique finds, brands at low prices. Convenient catalog and up-to-date contacts.

      second hand-177

      6 Sep 25 at 2:41 am

    2. Stunning quest there. What occurred after? Take care!

    3. Your way of describing the whole thing in this piece of writing is
      genuinely nice, all be able to easily be aware of it, Thanks a lot.

    4. Situs Togel Toto 4D [url=https://linklist.bio/inatogelbrand#]Situs Togel Toto 4D[/url] inatogel

      CharlesJam

      6 Sep 25 at 2:44 am

    5. Georgererry

      6 Sep 25 at 2:46 am

    6. Je kiffe grave Amon Casino, ca balance une vibe de jeu completement folle. Il y a une avalanche de jeux de casino varies, proposant des sessions de casino en direct qui dechirent. Le support du casino est dispo 24/7, offrant des solutions claires et instantanees. Les transactions du casino sont simples comme un jeu d’enfant, de temps en temps des bonus de casino plus reguliers ca serait top. En bref, Amon Casino est un casino en ligne qui cartonne grave pour les fans de casinos en ligne ! De surcroit le site du casino est une tuerie graphique, donne envie de replonger dans le casino non-stop.
      bonus amon casino|

      flickergoose3zef

      6 Sep 25 at 2:48 am

    7. В Химках вывести человека из запоя с выездом на дом реально — специалисты Stop Alko работают круглосуточно, оказывая профессиональную поддержку.
      Детальнее – [url=https://vyvod-iz-zapoya-himki13.ru/]анонимный вывод из запоя подольск[/url]

      Joshuachisa

      6 Sep 25 at 2:52 am

    8. Je suis accro a Celsius Casino, ca degage une ambiance de jeu torride. La selection du casino est une explosion de plaisirs, proposant des slots de casino a theme volcanique. L’assistance du casino est chaleureuse et efficace, joignable par chat ou email. Les gains du casino arrivent a une vitesse torride, quand meme des bonus de casino plus frequents seraient torrides. Dans l’ensemble, Celsius Casino promet un divertissement de casino brulant pour les explorateurs du casino ! Bonus l’interface du casino est fluide et eclatante comme une flamme, facilite une experience de casino torride.
      celsius casino|

      zestycrow4zef

      6 Sep 25 at 2:52 am

    9. Jeffreyzef

      6 Sep 25 at 2:52 am

    10. Вывод из запоя в «Сибирском Докторе» происходит в несколько взаимосвязанных этапов:
      Получить больше информации – [url=https://kachestvo-vyvod-iz-zapoya.ru/]наркологический вывод из запоя новосибирск[/url]

      Jamesfitty

      6 Sep 25 at 2:52 am

    11. what is yoga

      PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog

      what is yoga

      6 Sep 25 at 2:53 am

    12. экстренный вывод из запоя череповец
      vivod-iz-zapoya-cherepovec010.ru
      экстренный вывод из запоя череповец

    13. диплом с реестром купить [url=educ-ua13.ru]диплом с реестром купить[/url] .

      Diplomi_tipn

      6 Sep 25 at 2:55 am

    14. узнать провайдера по адресу новосибирск
      inernetvkvartiru-novosibirsk006.ru
      подключить интернет

      internetelini

      6 Sep 25 at 2:56 am

    15. The other day, while I was at work, my sister stole my
      iPad and tested to see if it can survive a 40 foot drop, just so she can be a youtube sensation. My iPad is now broken and she has 83 views.
      I know this is completely off topic but I had to share it with someone!

    16. Rolandmow

      6 Sep 25 at 3:04 am

    17. Greate post. Keep writing such kind of info on your site. Im really impressed by it.

      Hello there, You have done an incredible job.
      I will definitely digg it and in my opinion suggest to my friends.
      I’m confident they’ll be benefited from this website.

      dewascatter

      6 Sep 25 at 3:07 am

    18. dark web sites nexus darknet site darkmarket 2025 [url=https://darkmarketsdirectory.com/ ]dark web markets [/url]

      BrianWeX

      6 Sep 25 at 3:10 am

    19. nexus dark darknet markets onion address bitcoin dark web [url=https://darknetmarketstore.com/ ]darknet drugs [/url]

      Jamespem

      6 Sep 25 at 3:11 am

    20. Good day! This post couldn’t be written any better!
      Reading this post reminds me of my old room mate!

      He always kept chatting about this. I will forward this page to
      him. Fairly certain he will have a good read. Thanks for sharing!

      Also visit my blog; top real estate coach

    21. darkmarket 2025 dark market list nexus darknet access [url=https://darknetmarketgate.com/ ]nexus darknet [/url]

      DwayneAricE

      6 Sep 25 at 3:13 am

    22. youtubemfd

      6 Sep 25 at 3:13 am

    23. It’s actually a cool and useful piece of info. I’m glad that you shared this helpful info with us.
      Please stay us informed like this. Thank you for sharing.

      my blog post – top real estate coach

    24. Jeffreyzef

      6 Sep 25 at 3:15 am

    25. Jefferybig

      6 Sep 25 at 3:15 am

    26. Josephagody

      6 Sep 25 at 3:15 am

    27. Um ein Video herunterzuladen, kopiert Ihr
      die URL aus dem Browser, klickt im Anschluss auf “URL
      einfügen” und wählt das Ausgabeformat, die Qualität des Videos sowie
      den gewünschten Speicherort aus.

    28. I loved as much as you will receive carried out right here.
      The sketch is attractive, your authored subject matter stylish.
      nonetheless, you command get got an edginess over that you wish be delivering the
      following. unwell unquestionably come further formerly again as exactly the same nearly very often inside case you shield this hike.

      Casino Bonuses

      6 Sep 25 at 3:17 am

    29. Hi there every one, here every one is sharing
      such know-how, therefore it’s fastidious to read this webpage, and I used to visit this webpage every day.

      강남룸싸롱

      6 Sep 25 at 3:18 am

    30. Looking for second-hand? thrift store store near me We have collected the best stores with clothes, shoes and accessories. Large selection, unique finds, brands at low prices. Convenient catalog and up-to-date contacts.

      second hand-983

      6 Sep 25 at 3:21 am

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

      RichardPep

      6 Sep 25 at 3:22 am

    32. Je suis emballe par DBosses, ca donne un frisson inegale. La gamme est tout simplement epoustouflante, offrant des machines a sous innovantes. L’assistance est efficace et chaleureuse, repondant en un instant. Les transactions sont simples et efficaces, parfois plus de tours gratuits seraient top. Dans l’ensemble, DBosses garantit un divertissement de haut niveau pour les passionnes de sensations fortes ! Ajoutons que la navigation est intuitive et rapide, ce qui rend chaque session encore plus exaltante.
      dbosses casino|

      blazecrew2zef

      6 Sep 25 at 3:27 am

    33. youtubegil

      6 Sep 25 at 3:28 am

    34. Je suis totalement enflamme par Celsius Casino, ca degage une ambiance de jeu torride. Il y a un torrent de jeux de casino captivants, offrant des sessions de casino en direct qui crepitent. Le support du casino est disponible 24/7, assurant un support de casino immediat et flamboyant. Les transactions du casino sont simples comme une etincelle, par moments les offres du casino pourraient etre plus genereuses. Au final, Celsius Casino est une pepite pour les fans de casino pour les explorateurs du casino ! Par ailleurs la plateforme du casino brille par son style flamboyant, amplifie l’immersion totale dans le casino.
      celsius casino bonus|

      zestycrow4zef

      6 Sep 25 at 3:29 am

    35. Команда клиники «Новый шанс» состоит из опытных специалистов-наркологов, которые имеют многолетнюю практику работы с пациентами, находящимися в зависимости, и регулярно совершенствуют свои знания.
      Получить дополнительную информацию – [url=https://tajno-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-cena-v-rostove-na-donu.ru/]вывод из запоя вызов в ростове-на-дону[/url]

      Rodneytex

      6 Sep 25 at 3:37 am

    36. Thank you, I have just been looking for info about this topic for ages and yours is the greatest I’ve discovered so far.
      However, what about the conclusion? Are you certain concerning the source?

    37. Jeffreyzef

      6 Sep 25 at 3:38 am

    38. Highly energetic blog, I enjoyed that a lot.
      Will there be a part 2?

      xnxx so

      6 Sep 25 at 3:39 am

    39. Нужен удобный вариант оформить медсправку удалённо? [url=https://space-group-med.ru]https://space-group-med.ru[/url] На сайте Space Group Med есть возможность оформить широкий спектр справок — от документа 001-ГСУ, документа 082/у, до справок об освобождении от физической нагрузки, справок из ПНД/ОД и КЭК-заключений. Всё это можно получить удалённо с курьерской доставкой в Москве и СПб — без хлопот, быстро и законно. Все подробности на сайте — справка через интернет, медсправка курьером, справка за 1 день.

      Spravkigxr

      6 Sep 25 at 3:42 am

    40. Josephagody

      6 Sep 25 at 3:43 am

    41. Looking for second-hand? second hand stores near me We have collected the best stores with clothes, shoes and accessories. Large selection, unique finds, brands at low prices. Convenient catalog and up-to-date contacts.

      second hand-971

      6 Sep 25 at 3:44 am

    42. Howardmic

      6 Sep 25 at 3:46 am

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

      RichardPep

      6 Sep 25 at 3:49 am

    44. nexus shop darknet markets 2025 darknet markets [url=https://darknetmarketsgate.com/ ]darkmarket url [/url]

      Donaldfup

      6 Sep 25 at 3:49 am

    45. dark market url nexus shop url nexus darknet access [url=https://darknetmarketgate.com/ ]dark markets 2025 [/url]

      DwayneAricE

      6 Sep 25 at 3:51 am

    46. JamesSog

      6 Sep 25 at 3:52 am

    47. Rolandmow

      6 Sep 25 at 3:54 am

    48. Harryson

      6 Sep 25 at 3:59 am

    49. Jeffreyzef

      6 Sep 25 at 4:01 am

    50. Creating Links Via Web 2 . 0 And Web Directory Submission link (Sean)

      Sean

      6 Sep 25 at 4:01 am

    Leave a Reply