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 39,958 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 , , ,

    39,958 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=https://blog-o-marketinge1.ru/]стратегия продвижения блог[/url] .

    2. EdwardMox

      9 Sep 25 at 3:32 am

    3. mostbet qeydiyyat olmadan giriş [url=https://mostbet4144.ru]https://mostbet4144.ru[/url]

      mostbet_bxKa

      9 Sep 25 at 3:36 am

    4. лечение запоя
      vivod-iz-zapoya-krasnodar015.ru
      лечение запоя

    5. блог seo агентства [url=https://blog-o-marketinge1.ru/]blog-o-marketinge1.ru[/url] .

    6. seo онлайн [url=https://kursy-seo-3.ru]https://kursy-seo-3.ru[/url] .

      kyrsi seo_djon

      9 Sep 25 at 3:37 am

    7. It’s an amazing article in favor of all the internet viewers; they will get advantage from it I am sure.

      Paragonix Earn

      9 Sep 25 at 3:38 am

    8. Когда организм на пределе, важна срочная помощь в Самаре — это команда опытных наркологов, которые помогут быстро и мягко выйти из запоя без вреда для здоровья.
      Подробнее можно узнать тут – https://vyvod-iz-zapoya-v-stacionare-samara.ru/

      Everetttam

      9 Sep 25 at 3:40 am

    9. стратегия продвижения блог [url=www.blog-o-marketinge1.ru/]стратегия продвижения блог[/url] .

    10. mostbet qanunidirmi [url=https://mostbet4140.ru/]mostbet qanunidirmi[/url]

      mostbet_uoKr

      9 Sep 25 at 3:41 am

    11. mostbet aviator qeydiyyat [url=https://mostbet4144.ru/]https://mostbet4144.ru/[/url]

      mostbet_yfKa

      9 Sep 25 at 3:42 am

    12. I don’t even know the way I ended up right here, but I thought this publish was great.
      I don’t realize who you’re however definitely you are going to a well-known blogger when you
      are not already. Cheers!

      赌场

      9 Sep 25 at 3:43 am

    13. продвижение обучение [url=kursy-seo-2.ru]kursy-seo-2.ru[/url] .

      kyrsi seo_ooEr

      9 Sep 25 at 3:50 am

    14. блог интернет-маркетинга [url=https://blog-o-marketinge1.ru/]блог интернет-маркетинга[/url] .

    15. блог про продвижение сайтов [url=http://statyi-o-marketinge2.ru]блог про продвижение сайтов[/url] .

    16. mostbet az giriş [url=https://mostbet4141.ru/]https://mostbet4141.ru/[/url]

      mostbet_mfPn

      9 Sep 25 at 3:54 am

    17. Oh dear, lacking solid maths іn Junior College, eѵеn prestigious institution kids
      mіght falter at next-level equations, ѕo build thɑt now leh.

      Anglo-Chinese Junior College stands ɑs a beacon of well balanced education,
      blending extensive academics ᴡith ɑ supporting Christian values that motivates moral integrity аnd individual development.

      Ƭhe college’ѕ modern centers аnd knowledgeable faculty assistance impressive
      performance іn ƅoth arts and sciences, wіth students regularly attaining top
      accolades. Ƭhrough its emphasis on sports аnd carrying out arts,
      students develop discipline, sociability, аnd an enthusiasm fⲟr excellence Ьeyond tһe classroom.
      International partnerships ɑnd exchange chances enhance tһe discovering experience, promoting worldwide awareness
      аnd cultural appreciation. Alumni grow іn diverse fields, testimony tо thе college’ѕ function іn forming principled
      leaders ready tߋ contribute positively tο society.

      Victoria Junior College ignites imagination аnd cultivates visionary
      management, empowering trainees tο create positive ϲhange through a curriculum that stimulates enthusiasms аnd motivates vibrant thinking іn a attractive seaside school setting.

      Ƭhe school’s detailed facilities, including humanities discussion гooms,
      science rеsearch study suites, ɑnd arts performance locations, support enriched programs іn arts, liberal arts, ɑnd sciences tһɑt promote interdisciplinary insights and
      scholastic mastery. Strategic alliances ᴡith secondary schools tһrough incorporated programs
      mɑke sure a smooth educational journey, providing sped uup discovering paths аnd specialized electives that deal with
      individual strengths and interests. Service-learning efforts аnd worldwide outreach tasks, ѕuch ɑs international volunteer
      expeditions ɑnd management forums, develop caring dispositions, resilience,
      аnd а dedication tߋ community well-bеing. Graduates
      lead ԝith steady conviction аnd attain extraordinary success іn universities and professions, embodying Victoria Junior College’ѕ tradition оf supporting imaginative,
      principled, and transformative people.

      Hey hey, steady pom рi pi, maths is among from the leading subjects аt Junior
      College, building foundation tо A-Level calculus.
      Ιn additіοn from institution facilities, focus ᥙpon mathematics in οrder tօ stop common pitfalls including sloppy errors ɑt assessments.

      Hey hey, calm pom ⲣi pі, mathematics proves paгt in the hіghest
      subjects ⅾuring Junior College, building groundwork to A-Level advanced math.

      Βesides beyօnd institution facilities, concentrate ᴡith mathematics fοr prevent frequent pitfalls
      ѕuch as inattentive errors at exams.

      Don’t taқe lightly lah, combine a excellent Junior
      College alongside maths excellence tߋ ensure high A Levels scores ρlus
      effortless ϲhanges.
      Mums ɑnd Dads, fear thе difference hor,
      math groundwork proves essential іn Junior College fⲟr understanding
      figures, essential for current tech-driven economy.

      Оh man, no matter іf establishment is һigh-end, mathematics acts ⅼike the decisive topic іn cultivates
      confidence іn calculations.

      Βe kiasu and join tuition іf needеԀ; А-levels arе yоur ticket tο financial
      independence sooner.

      Оh dear, minus strong mathematics ԁuring Junior College, even prestigious
      school children mіght stumble in next-level algebra,
      therefore develop tһis promptly leh.

      My web site … site

      site

      9 Sep 25 at 3:54 am

    18. mostbet uz oynalgan sayt [url=www.mostbet4173.ru]www.mostbet4173.ru[/url]

      mostbet_uoEt

      9 Sep 25 at 3:56 am

    19. dark markets dark web market links nexus darknet url [url=https://darknetmarketgate.com/ ]dark market onion [/url]

      DwayneAricE

      9 Sep 25 at 4:01 am

    20. В Люберцах капельница от запоя может спасти здоровье — в Stop Alko работают опытные наркологи, которые точно знают, как снять интоксикацию без вреда.
      Узнать больше – [url=https://kapelnica-ot-zapoya-lyubercy13.ru/]капельница от запоя анонимно подольск[/url]

      EdwardSlatt

      9 Sep 25 at 4:08 am

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

      Diplomi_ebSa

      9 Sep 25 at 4:13 am

    22. mostbet for iphone [url=http://mostbet4171.ru]mostbet for iphone[/url]

      mostbet_weEt

      9 Sep 25 at 4:14 am

    23. I always spent my half an hour to read this weblog’s content every day along
      with a cup of coffee.

      VornethPro

      9 Sep 25 at 4:15 am

    24. mostbet poker otağı [url=http://mostbet4143.ru]mostbet poker otağı[/url]

      mostbet_urkt

      9 Sep 25 at 4:16 am

    25. школа seo [url=kursy-seo-1.ru]kursy-seo-1.ru[/url] .

      kyrsi seo_dlmt

      9 Sep 25 at 4:16 am

    26. NathanNah

      9 Sep 25 at 4:19 am

    27. Анонимная помощь при запое — врачи «Alco.Rehab» (Москва) приедут к вам в течение часа.
      Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-moskva12.ru/]помощь вывод из запоя москва[/url]

      LonnieUnfor

      9 Sep 25 at 4:20 am

    28. I loved as much as you’ll receive carried out right here.

      The sketch is attractive, your authored subject matter stylish.
      nonetheless, you command get got an impatience over that you wish be delivering the following.
      unwell unquestionably come further formerly again as exactly the same nearly a lot often inside case you
      shield this hike.

      Meteor Profit

      9 Sep 25 at 4:21 am

    29. AutoRent — прокат автомобилей в Минске. Ищете прокат автомобилей Минск? На autorent.by вы можете выбрать эконом, комфорт, бизнес и SUV, оформить онлайн-бронирование и получить авто в день обращения. Честные тарифы, ухоженный автопарк и круглосуточная поддержка. Подача в аэропорт Минск, самовывоз из города. Аренда на сутки и длительный период; доступны детские кресла и дополнительное оборудование.

      ukexehob

      9 Sep 25 at 4:21 am

    30. материалы по seo [url=www.blog-o-marketinge1.ru]материалы по seo[/url] .

    31. школа seo [url=www.kursy-seo-1.ru]www.kursy-seo-1.ru[/url] .

      kyrsi seo_rukt

      9 Sep 25 at 4:25 am

    32. Hey there! I’m at work browsing your blog from my new apple iphone!
      Just wanted to say I love reading your blog and look forward to all your posts!
      Carry on the outstanding work!

    33. Chesterkerge

      9 Sep 25 at 4:26 am

    34. ltdmyru

      9 Sep 25 at 4:27 am

    35. Open deals galore ɑt Kaizenaire.com, the leading website fⲟr Singapore’s promotions.

      Promotions ɑre the lifeline ⲟf Singapore’ѕ shopping heaven,attracting deal-loving Singaporeans fгom alⅼ profession.

      Singaporeans commonly cycle νia the PCN network for breathtaking experiences, and remember tⲟ stay updated on Singapore’ѕ
      most recent promotions аnd shopping deals.

      ComfortDelGro оffers taxi and public transportation services, appreciated ƅy Singaporeans for thеir trusted rides and substantial network аcross the city.

      McDonald’ѕ offers junk food faves ⅼike hamburgers ɑnd french fries mah, preferred Ƅү Singaporeans fօr tһeir fast meals and local menu spins ѕia.

      ABR Holdings operates Swensen’ѕ and vaгious othuer eateries, enjoyed fⲟr diverse eating chains tһroughout Singapore.

      D᧐n’t lag lor, гemain updated with Kaizenaire.com siа.

      Ꮇy web page; pinoy in singapore recruitment agencies rejecting singaporean job applications

    36. mostbet şikayətlər [url=www.mostbet4141.ru]www.mostbet4141.ru[/url]

      mostbet_wjPn

      9 Sep 25 at 4:29 am

    37. материалы по маркетингу [url=http://blog-o-marketinge1.ru/]материалы по маркетингу[/url] .

    38. Robertwhego

      9 Sep 25 at 4:33 am

    39. dark market onion nexus market url dark web markets [url=https://privatedarknetmarket.com/ ]dark web drug marketplace [/url]

      Robertalima

      9 Sep 25 at 4:35 am

    40. mostbet suallar və cavablar [url=http://mostbet4145.ru/]mostbet suallar və cavablar[/url]

      mostbet_ybot

      9 Sep 25 at 4:36 am

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

      Diplomi_ddSa

      9 Sep 25 at 4:36 am

    42. обучение seo [url=http://kursy-seo-4.ru/]обучение seo[/url] .

      kyrsi seo_akPl

      9 Sep 25 at 4:39 am

    43. EverGreenRx USA: cialis coupon online – EverGreenRx USA

      Jamespycle

      9 Sep 25 at 4:40 am

    44. Nice post. I learn something new and challenging on websites I stumbleupon on a daily basis.
      It’s always helpful to read through content from
      other authors and practice something from other sites.

    45. блог о рекламе и аналитике [url=http://www.statyi-o-marketinge2.ru]http://www.statyi-o-marketinge2.ru[/url] .

    46. Good post. I learn something totally new and challenging on websites I stumbleupon everyday.
      It will always be interesting to read through content
      from other writers and practice something from their web sites.

    47. mostbet az virtual oyunlar [url=https://www.mostbet4143.ru]mostbet az virtual oyunlar[/url]

      mostbet_klkt

      9 Sep 25 at 4:48 am

    48. seo интенсив [url=http://kursy-seo-3.ru]http://kursy-seo-3.ru[/url] .

      kyrsi seo_qson

      9 Sep 25 at 4:50 am

    49. блог про продвижение сайтов [url=https://www.statyi-o-marketinge2.ru]блог про продвижение сайтов[/url] .

    50. интернет маркетинг статьи [url=blog-o-marketinge1.ru]интернет маркетинг статьи[/url] .

    Leave a Reply