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 80,939 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 , , ,

    80,939 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=http://sport-novosti-1.ru]http://sport-novosti-1.ru[/url] .

    2. купить диплом техникума 1989 [url=frei-diplom8.ru]купить диплом техникума 1989[/url] .

      Diplomi_jzsr

      7 Oct 25 at 11:08 am

    3. новости легкой атлетики [url=https://novosti-sporta-7.ru]https://novosti-sporta-7.ru[/url] .

    4. вывод из запоя клиника [url=https://narkologicheskaya-klinika-20.ru/]https://narkologicheskaya-klinika-20.ru/[/url] .

    5. купить диплом техникума пять плюс [url=http://www.frei-diplom9.ru]купить диплом техникума пять плюс[/url] .

      Diplomi_kbea

      7 Oct 25 at 11:08 am

    6. купить диплом колледжа культуры в спб [url=http://www.frei-diplom12.ru]http://www.frei-diplom12.ru[/url] .

      Diplomi_tsPt

      7 Oct 25 at 11:09 am

    7. результаты матчей [url=https://sport-novosti-1.ru/]https://sport-novosti-1.ru/[/url] .

    8. pin up ilova ishlamayapti [url=https://pinup5006.ru]https://pinup5006.ru[/url]

      pin_up_niKt

      7 Oct 25 at 11:12 am

    9. новости спорта [url=https://www.sport-novosti-1.ru]https://www.sport-novosti-1.ru[/url] .

    10. спортивные аналитики [url=http://novosti-sporta-7.ru]http://novosti-sporta-7.ru[/url] .

    11. купить диплом в черногорске [url=rudik-diplom6.ru]rudik-diplom6.ru[/url] .

      Diplomi_njKr

      7 Oct 25 at 11:14 am

    12. купить диплом колледжа пермь [url=https://www.frei-diplom10.ru]https://www.frei-diplom10.ru[/url] .

      Diplomi_deEa

      7 Oct 25 at 11:14 am

    13. диплом техникума колледжа купить пять плюс [url=http://frei-diplom9.ru]диплом техникума колледжа купить пять плюс[/url] .

      Diplomi_ecea

      7 Oct 25 at 11:14 am

    14. новости мирового спорта [url=https://novosti-sporta-7.ru/]novosti-sporta-7.ru[/url] .

    15. Good post. I learn something new and challenging on sites I stumbleupon everyday.

      It’s always interesting to read articles from other writers and practice something from their
      websites.

    16. результаты матчей [url=http://sport-novosti-1.ru/]http://sport-novosti-1.ru/[/url] .

    17. купить аттестат школы [url=https://rudik-diplom15.ru]купить аттестат школы[/url] .

      Diplomi_viPi

      7 Oct 25 at 11:23 am

    18. лицензия нарколога на дом [url=http://narkolog-na-dom-1.ru/]http://narkolog-na-dom-1.ru/[/url] .

    19. Гарантия качества на все купленные велосипеды кракен даркнет kraken актуальные ссылки кракен ссылка kraken kraken официальные ссылки

      RichardPep

      7 Oct 25 at 11:24 am

    20. Can you tell us more about this? I’d like to find out some additional information.

    21. кухни на заказ в спб недорого [url=https://kuhni-spb-4.ru/]кухни на заказ в спб недорого[/url] .

      kyhni spb_xser

      7 Oct 25 at 11:26 am

    22. Parents sһould ѕee secondary school math tuition as іmportant in Singapore for fostering curiosity іn mathematical concepts.

      Can leh, wіth toρ scores, Singapore sets math benchmarks globally!

      Parents, equity empower ѡith Singapore math tuition’s promotion. Secondary
      math tuition fairness guarantees. Ꮃith secondary 1
      math tuition,skills collaborate.

      Secondary 2 math tuition promotes hydration аnd breaks for brain health.

      Secondary 2 math tuition tɑkes care of physical wellness.

      Healthy secondary 2 math tuition sustains focus. Secondary 2 math tuition balances mind
      andd body.

      Ӏn secondary 3, math exams test advanced topics tһat form thе backbone of O-Level preparation, making һigh ratings necessary
      for developing momentum tοward the laѕt year. Succeeding prevents understanding spaces tһat could impede efficiency
      in the O-Levels, ԝhere math grades heavily influence tߋtаl L1R5
      ratings. Τhis accomplishment not juѕt improves confidence һowever likеwise boosts eligibility fⲟr junior college оr polytechnic programs.

      Тhe Singapore education landscape considers secondarty
      4 exams neⅽessary fߋr holistic assessment. Secondary 4 math tuition іncludes
      mentorship fгom experienced teachers. Тhis assistance fine-tunes
      methods to calculus issues. Secondary 4 math tuition paves tһe ԝay for
      positive exam takers.

      Mathematics transcfends exam requirements; іt’s ɑ cornerstone skill in the AI surge, powering autonomous vehicle safety.

      Develop deeep love fⲟr mathematics and apply its principles
      everyday t᧐ excel.

      Students gain from practicing ρast math papers from multiple schools Ƅy enhancing their numerical fluency
      for exams.

      Singapore learners ѕee math exam improvements ᴡith online tuition е-learning tһat includes video explanations foг tricky Օ-Level concepts.

      Aiyoh leh, ⅾon’t panic lah, ʏoᥙr kid ready
      fοr secondary school, support ԝithout pressure.

      Аlso visit my website: ib math tutor online – chachamortors.com

    23. вывод из запоя в стационаре москва [url=www.vyvod-iz-zapoya-9.ru/]www.vyvod-iz-zapoya-9.ru/[/url] .

    24. сколько стоит купить диплом в колледже [url=frei-diplom10.ru]frei-diplom10.ru[/url] .

      Diplomi_zeEa

      7 Oct 25 at 11:29 am

    25. телефон наркологии [url=www.narkologicheskaya-klinika-20.ru/]www.narkologicheskaya-klinika-20.ru/[/url] .

    26. кому звонить наркологу на дом [url=https://narkolog-na-dom-1.ru]https://narkolog-na-dom-1.ru[/url] .

    27. Kaizenaire.ϲom accumulations Singapore’ѕ favored
      brand namе deals and promotions perfectly.

      Singapore’ѕ malls are sanctuaries in this shopping paradise, ԝhere deals ɑnd promotions rule supreme fօr locals.

      Exploring street art in arеas like Haji Lane influences imaginative Singaporeans, ɑnd keep iin mind to stay upgraded ߋn Singapore’s newest promotions ɑnd shopping deals.

      Mmerci Εncore gіves tidy beauty and skin care products,
      cherished ƅy wellness-oriented Singaporeans for their natural components.

      Aijek ρrovides womanly dresses ɑnd divides mah, loved Ьү elegant Singaporeans fοr tһeir soft silhouettes ɑnd charming allure sіa.

      Putien brings Fujian cuisine like fried Heng Hwa bee hoon, preferred fοr light, seafood-focused recipes ѡith hometown charm.

      Muϲh better hurry lor, go to Kaizenaire.ⅽom daily for shopping mah.

      Hеre is mу site: singapore promotions

    28. If you desire to take a great deal from this article then you have to apply these techniques to your won web site.

      tt88

      7 Oct 25 at 11:30 am

    29. новости олимпиады [url=www.sport-novosti-1.ru]www.sport-novosti-1.ru[/url] .

    30. DonaldtiEls

      7 Oct 25 at 11:30 am

    31. доставка двигателя Атмосферный двигатель – запрос на двигатель без турбонаддува. Атмосферные двигатели отличаются более линейным характером мощности и меньшей сложностью конструкции. Важно предоставить информацию о преимуществах и недостатках атмосферных двигателей.

      JamesMig

      7 Oct 25 at 11:31 am

    32. кухни на заказ в спб [url=kuhni-spb-4.ru]кухни на заказ в спб[/url] .

      kyhni spb_dver

      7 Oct 25 at 11:31 am

    33. сайт dragon money casino
      Драгон Мани – яркое казино с богатой коллекцией игр. Выгодные бонусы, быстрые выводы и удобная навигация делают платформу привлекательной для игроков

    34. спорт новости [url=https://novosti-sporta-7.ru/]спорт новости[/url] .

    35. Excited for Minotaurus presale’s 80% off deal. $MTAUR’s in-game boosts edge-giving. Community vibrant.
      minotaurus coin

      WilliamPargy

      7 Oct 25 at 11:33 am

    36. новости киберспорта [url=http://www.sport-novosti-1.ru]http://www.sport-novosti-1.ru[/url] .

    37. купить диплом об окончании техникума в самаре [url=frei-diplom9.ru]купить диплом об окончании техникума в самаре[/url] .

      Diplomi_jaea

      7 Oct 25 at 11:35 am

    38. заказать кухню спб [url=https://www.kuhni-spb-4.ru]https://www.kuhni-spb-4.ru[/url] .

      kyhni spb_zzer

      7 Oct 25 at 11:35 am

    39. клиника наркологическая платная [url=http://www.narkologicheskaya-klinika-20.ru]http://www.narkologicheskaya-klinika-20.ru[/url] .

    40. Tulisan ini menarik sekali,
      memberi perspektif berbeda tentang topik yang dibahas.

      Saya senang membacanya dan kemarin juga membaca **MPO102**
      yang membahas bahasan seputar QRIS dan pulsa dengan bahasa sederhana.

      Semoga selalu konsisten.

      MPO102

      7 Oct 25 at 11:37 am

    41. buy propecia: RegrowRx Online – Propecia buy online

      Glennchilt

      7 Oct 25 at 11:37 am

    42. Heya! I understand this is sort of off-topic but I needed to ask.

      Does managing a well-established website such as yours take a massive amount work?
      I am brand new to writing a blog however I do write in my
      diary daily. I’d like to start a blog so I will be able to share my own experience and views online.
      Please let me know if you have any ideas or tips for brand new aspiring
      blog owners. Thankyou!

    43. onlineforextrading – Good mix of educational and practical tips, very helpful.

    44. Thomasbip

      7 Oct 25 at 11:43 am

    45. https://dublikat-centr.ru/
      Драгон Мани – яркое казино с богатой коллекцией игр. Выгодные бонусы, быстрые выводы и удобная навигация делают платформу привлекательной для игроков

    46. купить диплом в пятигорске [url=https://www.rudik-diplom15.ru]купить диплом в пятигорске[/url] .

      Diplomi_twPi

      7 Oct 25 at 11:46 am

    47. Выгодные авто из Японии Японские автомобили с пробегом – запрос на информацию о подержанных автомобилях японского производства. Важно предоставить информацию о популярных моделях с пробегом, их достоинствах и недостатках, а также о проверке состояния автомобиля перед покупкой.

      Martinses

      7 Oct 25 at 11:49 am

    48. купить диплом техникум [url=www.frei-diplom10.ru]купить диплом техникум[/url] .

      Diplomi_jwEa

      7 Oct 25 at 11:49 am

    49. кухни на заказ петербург [url=www.kuhni-spb-4.ru]кухни на заказ петербург[/url] .

      kyhni spb_grer

      7 Oct 25 at 11:49 am

    50. обзор спортивных событий [url=novosti-sporta-7.ru]novosti-sporta-7.ru[/url] .

    Leave a Reply