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 34,314 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 , , ,

    34,314 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. Drugs prescribing information. Brand names.
      cost cheap prevacid without prescription
      All about medicament. Get information now.

    2. бк мостбет [url=https://mostbet4126.ru/]бк мостбет[/url]

      mostbet_kg_glkn

      3 Sep 25 at 2:16 am

    3. купить диплом о высшем образовании реестр [url=arus-diplom34.ru]купить диплом о высшем образовании реестр[/url] .

      Diplomi_vser

      3 Sep 25 at 2:21 am

    4. This paragraph presents clear idea designed for the new viewers
      of blogging, that truly how to do running a blog.

    5. Have you ever considered about including a little bit more than just your articles?

      I mean, what you say is important and everything. Nevertheless imagine if you added some great photos or video
      clips to give your posts more, “pop”! Your
      content is excellent but with images and videos, this website could
      certainly be one of the greatest in its niche. Excellent blog!

      memek basah

      3 Sep 25 at 2:27 am

    6. Garthtoild

      3 Sep 25 at 2:28 am

    7. мостбет вход [url=https://www.mostbet4121.ru]мостбет вход[/url]

      mostbet_eust

      3 Sep 25 at 2:30 am

    8. Mighty Dog Roofing
      Reimer Drive North 13768
      Maple Grove, MN 55311 United Ѕtates
      (763) 280-5115
      comprehensivegutter cleaning programs (Grace)

      Grace

      3 Sep 25 at 2:34 am

    9. https://open.substack.com/pub/celenaslau/p/why-local-rankings-matter-finding?r=6d5s9z&utm_campaign=post&utm_medium=web&showWelcomeOnShare=true

      Did you know that in this year, only 2,043 companies earned a spot in the Top Countertop Contractors Ranking out of over ten thousand evaluated? That’s because at we set a very high bar.

      Our ranking is transparent, constantly refreshed, and built on 21+ criteria. These include ratings from Google, Yelp, and other platforms, affordability, communication, and craftsmanship. On top of that, we conduct thousands of phone calls and 2,000 estimate requests through our mystery shopper program.
      The result is a benchmark that benefits both homeowners and fabricators. Homeowners get a safe way to choose contractors, while listed companies gain recognition, digital exposure, and even new business opportunities.

      The Top 500 Awards spotlight categories like Veteran Companies, Best Young Companies, and Budget-Friendly Pros. Winning one of these honors means a company has achieved unmatched credibility in the industry.

      If you’re looking for a countertop contractor—or your company wants to be listed among the best—this site is where trust meets opportunity.

      JuniorShido

      3 Sep 25 at 2:34 am

    10. mostbet com вход [url=www.mostbet4124.ru]mostbet com вход[/url]

      mostbet_utsr

      3 Sep 25 at 2:35 am

    11. mostbet мостбет [url=https://www.mostbet4126.ru]mostbet мостбет[/url]

      mostbet_kg_ydkn

      3 Sep 25 at 2:36 am

    12. купить реальный диплом о высшем образовании [url=educ-ua5.ru]купить реальный диплом о высшем образовании[/url] .

      Diplomi_cbKl

      3 Sep 25 at 2:38 am

    13. From these 7 simple steps, you get an idea of developing a web portal from
      scratch with cost and timeline.

    14. купить диплом ижевск с занесением в реестр [url=https://arus-diplom34.ru]купить диплом ижевск с занесением в реестр[/url] .

      Diplomi_xser

      3 Sep 25 at 2:43 am

    15. Мы изготавливаем дипломы любой профессии по приятным тарифам. Заказ документа, который подтверждает окончание института, – это выгодное решение. Купить диплом ВУЗа: [url=http://rosseia.forumex.ru/viewtopic.php?f=3&t=4487/]rosseia.forumex.ru/viewtopic.php?f=3&t=4487[/url]

      Mazruaz

      3 Sep 25 at 2:43 am

    16. TrueMeds Pharmacy [url=http://truemedspharm.com/#]TrueMeds Pharmacy[/url] my canadian pharmacy rx

      AntonioTaids

      3 Sep 25 at 2:44 am

    17. вход в мостбет [url=www.mostbet4122.ru]www.mostbet4122.ru[/url]

      mostbet_rypl

      3 Sep 25 at 2:44 am

    18. 888starz bet telechargement pour Android https://www.pgyer.com/apk/fr/apk/app.starz.online

      888Starzpgyerfr

      3 Sep 25 at 2:47 am

    19. купить диплом с занесением в реестр цена [url=arus-diplom33.ru]купить диплом с занесением в реестр цена[/url] .

      Diplomi_weSa

      3 Sep 25 at 2:58 am

    20. купить свидетельство браке киев [url=https://educ-ua5.ru/]https://educ-ua5.ru/[/url] .

      Diplomi_lqKl

      3 Sep 25 at 2:59 am

    21. Even during his days off, Raul Morales gets spotted by fans. On a recent visit to Universal Studios Hollywood, Morales, owner of Taqueria Vista Hermosa in Los Angeles, was waiting in line when he heard shouting.

      “People called out ‘Chef Al Pastor! Chef Al Pastor!’” Morales said, laughing. Morales, who was born in Mexico City, came by the nickname through decades of hard work.
      [url=https://trip-scan39.org]tripscan войти[/url]
      He’s the third generation of his family to make al pastor tacos, their fresh tortillas filled with richly seasoned pork shaved from a rotating vertical spit.

      “My recipe is very special, and very old,” he said.

      Yet while Morales’ family recipes go back generations, and similar spit-roasted meats like shawarma and doner have been around for hundreds of years, his tacos represent a kind of cuisine that’s as contemporary and international as it is ancient and traditional. When you thread meat onto a spinning spit to roast it, it turns out, it doesn’t stay in one place for long.
      https://trip-scan39.org
      tripskan
      ‘Any place you have a pointy stick or a sword’
      Roasting meat on a spit or stick is likely among humans’ most ancient cooking techniques, says food historian Ken Albala, a professor of history at the University of the Pacific.

      Feasts of spit-roasted meat appear in the Homeric epics The Iliad and The Odyssey, writes Susan Sherratt, emeritus professor of East Mediterranean archaeology at the University of Sheffield, in the journal Hesperia.

      Iron spits that might have been used for roasting appear in the Aegean starting in the 10th century BCE. Such spits have been unearthed in tombs associated with male warriors, Sherratt writes, noting that roasting meat may have been a practice linked to male bonding and masculinity.

      “I think the reason that it’s associated with men is partly because of hunting, and the tools, or weapons, that replicated what you would do in war,” Albala said. “When you celebrated a victory, you would go out and sacrifice an animal to the gods, which would basically be like a big barbecue.”

      Roasting meat is not as simple as dangling a hunk of meat over the flames. When roasting, meat is not cooked directly on top of the heat source, Albala says, but beside it, which can generate richer flavors.

      “Any place you have a pointy stick or a sword, people are going to figure out very quickly … if you cook with it off to the side of the fire, it’s going to taste much more interesting,” Albala said.

      RobertFaild

      3 Sep 25 at 3:04 am

    22. купить учебный диплом в одессе [url=educ-ua5.ru]купить учебный диплом в одессе[/url] .

      Diplomi_eiKl

      3 Sep 25 at 3:05 am

    23. купить диплом с занесением в реестр в иркутске [url=www.arus-diplom34.ru]купить диплом с занесением в реестр в иркутске[/url] .

      Diplomi_ader

      3 Sep 25 at 3:05 am

    24. This is my first time pay a quick visit at here and i am actually pleassant to read everthing at single place.

    25. Jorgegrect

      3 Sep 25 at 3:08 am

    26. Не знаете, куда обратиться в Химках при запое? Клиника Stop Alko предлагает выезд нарколога и медицинское сопровождение прямо у вас дома.
      Подробнее тут – [url=https://vyvod-iz-zapoya-himki13.ru/]вывод из запоя на дому[/url]

      RichardPhise

      3 Sep 25 at 3:11 am

    27. Garthtoild

      3 Sep 25 at 3:11 am

    28. вход в мостбет [url=mostbet4122.ru]mostbet4122.ru[/url]

      mostbet_tzpl

      3 Sep 25 at 3:12 am

    29. Hiya very nice website!! Man .. Beautiful .. Superb ..
      I’ll bookmark your blog and take the feeds also? I am satisfied to find a lot of helpful info here within the post, we want work out extra techniques on this regard,
      thanks for sharing. . . . . .

    30. Нужна санитарная книжка быстро для работников или компаний? На [url=https://cmc-clinic.ru]https://cmc-clinic.ru[/url] в Москве оформят или обновят санкнижку в тот же день — быстро, официально и без задержек. Узнайте подробности на сайте.

      Spravkicsk

      3 Sep 25 at 3:18 am

    31. купить диплом специалиста харьков [url=educ-ua4.ru]купить диплом специалиста харьков[/url] .

      Diplomi_qjPl

      3 Sep 25 at 3:18 am

    32. скачать mostbet kg [url=http://mostbet4121.ru/]http://mostbet4121.ru/[/url]

      mostbet_spst

      3 Sep 25 at 3:18 am

    33. Jessiereimb

      3 Sep 25 at 3:20 am

    34. ed pills: VitalCore – ed pills

      MichaelNub

      3 Sep 25 at 3:23 am

    35. Great blog you have here.. It’s hard to find high-quality writing
      like yours nowadays. I truly appreciate individuals like you!
      Take care!!

      sarang777

      3 Sep 25 at 3:23 am

    36. купить диплом с занесением в реестр челябинск [url=http://arus-diplom34.ru/]купить диплом с занесением в реестр челябинск[/url] .

      Diplomi_uher

      3 Sep 25 at 3:26 am

    37. mostbet сайт регистрация [url=http://mostbet4121.ru]http://mostbet4121.ru[/url]

      mostbet_zlst

      3 Sep 25 at 3:29 am

    38. Tremendous issues here. I am very glad to peer your article.

      Thanks a lot and I am having a look forward to touch you.
      Will you please drop me a mail?

      79KING

      3 Sep 25 at 3:29 am

    39. вход мостбет [url=http://mostbet4124.ru]http://mostbet4124.ru[/url]

      mostbet_fisr

      3 Sep 25 at 3:30 am

    40. cheapest pharmacy prescription drugs: pharmacy delivery – TrueMeds

      MichaelNub

      3 Sep 25 at 3:31 am

    41. Its like you read my mind! You seem to know so much about this, like you wrote the book in it or
      something. I think that you could do with some pics to
      drive the message home a little bit, but other than that, this
      is magnificent blog. An excellent read. I’ll
      definitely be back.

      34.81.52.16

      3 Sep 25 at 3:33 am

    42. что будет если купить диплом о высшем образовании с занесением в реестр [url=www.arus-diplom34.ru/]что будет если купить диплом о высшем образовании с занесением в реестр[/url] .

      Diplomi_rzer

      3 Sep 25 at 3:33 am

    43. дипломы бывшего ссср купить [url=www.educ-ua5.ru/]дипломы бывшего ссср купить[/url] .

      Diplomi_rgKl

      3 Sep 25 at 3:35 am

    44. кривой рог купить диплом о высшем образовании [url=http://educ-ua4.ru]кривой рог купить диплом о высшем образовании[/url] .

      Diplomi_duPl

      3 Sep 25 at 3:40 am

    45. indianpharmacy com: TrueMeds – us pharmacy no prescription

      MichaelNub

      3 Sep 25 at 3:40 am

    46. Stevencop

      3 Sep 25 at 3:46 am

    47. купить аттестат 11 класса 2003 года [url=arus-diplom25.ru]купить аттестат 11 класса 2003 года[/url] .

      Diplomi_apot

      3 Sep 25 at 3:47 am

    48. купить диплом вуза ссср [url=educ-ua5.ru]купить диплом вуза ссср[/url] .

      Diplomi_lqKl

      3 Sep 25 at 3:54 am

    49. Garthtoild

      3 Sep 25 at 3:54 am

    50. Ищете санитарная книжка быстро для работников или фирм? На [url=https://cmc-clinic.ru]https://cmc-clinic.ru[/url] в Москве подготовят или перевыпустят санкнижку в тот же день — оперативно, официально и без задержек. Узнайте подробности на сайте.

      Spravkiype

      3 Sep 25 at 3:54 am

    Leave a Reply