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 20,072 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 , , ,

    20,072 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://www.arus-diplom34.ru]купить диплом с реестром отзывы[/url] .

      Diplomi_fier

      17 Aug 25 at 2:22 am

    2. купить аттестат за 11 класс ярославль [url=https://arus-diplom23.ru]купить аттестат за 11 класс ярославль[/url] .

      Diplomi_yaSr

      17 Aug 25 at 2:23 am

    3. спортивные новости [url=http://www.novosti-sporta-2.ru]http://www.novosti-sporta-2.ru[/url] .

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

      Diplomi_aeei

      17 Aug 25 at 2:30 am

    5. В Москве к вашим услугам скорая наркологическая помощь от Narcology Clinic — выезд врача 24/7, качественная помощь при алкогольной интоксикации, стабилизация состояния и организация дальнейших этапов детоксикации.
      Подробнее тут – [url=https://skoraya-narkologicheskaya-pomoshch-moskva11.ru/]круглосуточная наркологическая помощь[/url]

      TerryPROOT

      17 Aug 25 at 2:32 am

    6. Kamagra oral jelly USA availability: Compare Kamagra with branded alternatives – ED treatment without doctor visits

      RichardTit

      17 Aug 25 at 2:38 am

    7. купить диплом легальный о высшем образовании [url=https://www.arus-diplom33.ru]https://www.arus-diplom33.ru[/url] .

      Diplomi_ycSa

      17 Aug 25 at 2:38 am

    8. Наркологическая клиника “Чистый Путь” — это специализированное медицинское учреждение, предоставляющее помощь людям, страдающим от алкогольной и наркотической зависимости. Наша цель — помочь пациентам справиться с зависимостью, вернуться к здоровой и полноценной жизни, используя эффективные методы лечения и всестороннюю поддержку.
      Разобраться лучше – https://срочно-вывод-из-запоя.рф/vyvod-iz-zapoya-v-kruglosutochno-v-chelyabinske.xn--p1ai

      Elmerlar

      17 Aug 25 at 2:40 am

    9. Если требуется экстренная помощь при алкогольном кризисе — Narcology Clinic Москва предоставляет срочную помощь на дому: выезд нарколога, купирование симптомов, мониторинг состояния, без очередей и задержек.
      Разобраться лучше – [url=https://skoraya-narkologicheskaya-pomoshch-moskva.ru/]круглосуточная наркологическая помощь московская область[/url]

      Robertkix

      17 Aug 25 at 2:46 am

    10. prix du viagra 50mg [url=https://sildenapeak.shop/#]SildenaPeak[/url] pharmacy rx viagra

      RobertCat

      17 Aug 25 at 2:46 am

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

      Diplomi_kner

      17 Aug 25 at 2:47 am

    12. My partner and I stumbled over here by a different web address and thought
      I might as well check things out. I like what I see so now i am following you.
      Look forward to going over your web page repeatedly.

    13. This paragraph gives clear idea designed for the new users of
      blogging, that in fact how to do running a blog.

      trang chủ 69VN

      17 Aug 25 at 2:52 am

    14. купить аттестат за 11 класс в нижнем тагиле на [url=http://www.arus-diplom23.ru]купить аттестат за 11 класс в нижнем тагиле на[/url] .

      Diplomi_lwSr

      17 Aug 25 at 2:53 am

    15. купить аттестат за 11 класс в школе [url=https://arus-diplom23.ru]купить аттестат за 11 класс в школе[/url] .

      Diplomi_niol

      17 Aug 25 at 2:56 am

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

      Diplomi_xzSa

      17 Aug 25 at 2:59 am

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

      Diplomi_koSa

      17 Aug 25 at 3:05 am

    18. прогнозы на хоккей с высокой проходимостью [url=https://luchshie-prognozy-na-khokkej13.ru/]luchshie-prognozy-na-khokkej13.ru[/url] .

    19. Online sources for Kamagra in the United States: Online sources for Kamagra in the United States – Safe access to generic ED medication

      PeterTEEFS

      17 Aug 25 at 3:08 am

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

      Diplomi_geer

      17 Aug 25 at 3:08 am

    21. купить легальный аттестат за 11 классов [url=https://arus-diplom21.ru/]купить легальный аттестат за 11 классов[/url] .

      Diplomi_bhPr

      17 Aug 25 at 3:10 am

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

      ParisCappy

      17 Aug 25 at 3:10 am

    23. Nice post. I was checking constantly this weblog and I’m inspired!
      Very helpful information specially the remaining phase 🙂 I maintain such information much.
      I used to be looking for this certain information for a
      long time. Thanks and best of luck.

      red dog casino

      17 Aug 25 at 3:12 am

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

    25. купить аттестат за 11 класс новосибирск [url=http://arus-diplom23.ru]http://arus-diplom23.ru[/url] .

      Diplomi_gdSr

      17 Aug 25 at 3:14 am

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

      Diplomi_wver

      17 Aug 25 at 3:15 am

    27. купить аттестаты за 11 класс курган [url=https://arus-diplom22.ru]купить аттестаты за 11 класс курган[/url] .

      Diplomi_mvKt

      17 Aug 25 at 3:15 am

    28. купить свидетельство о расторжении брака [url=http://educ-ua1.ru]http://educ-ua1.ru[/url] .

      Diplomi_izei

      17 Aug 25 at 3:16 am

    29. новости спорта сегодня [url=http://novosti-sporta-3.ru]http://novosti-sporta-3.ru[/url] .

    30. Оптимально для пациентов в стабильном состоянии. Процедура начинается с приезда врача, осмотра и постановки капельницы с индивидуально подобранными растворами.
      Исследовать вопрос подробнее – https://narko-zakodirovan2.ru

      MarvinGon

      17 Aug 25 at 3:28 am

    31. купить аттестат за 11 класс в иркутске [url=www.arus-diplom9.ru]www.arus-diplom9.ru[/url] .

      Diplomi_plEi

      17 Aug 25 at 3:30 am

    32. What i don’t realize is actually how you are now not really much more smartly-preferred than you may be right now.
      You’re so intelligent. You know thus considerably relating to this
      matter, made me in my view believe it from a
      lot of varied angles. Its like women and men don’t seem to be interested except it is one thing to accomplish with Woman gaga!
      Your personal stuffs outstanding. Always take care of it up!

      Dog Collar

      17 Aug 25 at 3:31 am

    33. купить диплом украина [url=http://www.educ-ua1.ru]купить диплом украина[/url] .

      Diplomi_zkei

      17 Aug 25 at 3:33 am

    34. OMT’s standalone e-learning options empower independent exploration, supporting аn individual love for mathematics аnd
      exam aspiration.

      Օpen yoᥙr child’ѕ full capacity іn mathematics with OMT Math Tuition’ѕ expert-led
      classes, tailored tօ Singapore’s MOE syllabus foг primary, secondary, ɑnd JC students.

      The holistic Singapore Math method, ѡhich develops multilayered рroblem-solving capabilities,
      highlights ԝhy math tuition iѕ vital for mastering the curriculum аnd preparing foг future professions.

      Ϝօr PSLE success, tuition prⲟvides tailored guidance
      tο weak locations, like ratio and portion problems, avoiding common risks during the exam.

      Secondary math tuition conquers tһе restrictions оf largе class dimensions, ցiving concentrated interеѕt that boosts
      understanding fߋr Օ Level preparation.

      In a competitive Singaporean education ѕystem, junior college math
      tuition οffers pupils the ѕide to attain hіgh qualities necеssary for university admissions.

      Ꮃhat sets арart OMT іѕ its proprietary program tһat matches MOE’ѕ viа emphasis
      on moral analytical іn mathematical contexts.

      Specialist pointers іn videos offer faster ᴡays lah, assisting you fіx
      questions faster and rack up mսch more in tests.

      Witһ global competition increasing, math tuition settings Singapore
      trainees ɑѕ tօp entertainers in worldwide math analyses.

      Нere iѕ my webpage :: junior college maths tuition

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

      Diplomi_rvSa

      17 Aug 25 at 3:36 am

    36. Современная наркология предлагает два основных формата вывода из запоя:
      Углубиться в тему – https://nadezhnyj-vyvod-iz-zapoya.ru/

      MichaelMes

      17 Aug 25 at 3:37 am

    37. Наркологическая клиника “Маяк надежды” — специализированное медицинское учреждение, предназначенное для оказания помощи лицам, страдающим от алкогольной и наркотической зависимости. Наша цель — предоставить эффективные методы лечения и поддержку, чтобы помочь пациентам преодолеть пагубное пристрастие и вернуть их к здоровой и полноценной жизни.
      Узнать больше – https://алко-лечение24.рф/vivod-iz-zapoya-v-stacionare-v-Sankt-Peterburge

      JasonLoorm

      17 Aug 25 at 3:42 am

    38. Magnificent items from you, man. I’ve take note your stuff prior to
      and you are simply extremely wonderful. I actually like what you have bought right here, really like what you are stating and the best way in which you say it.

      You are making it enjoyable and you still take care
      of to keep it wise. I can not wait to read far more from you.
      This is actually a great site.

    39. Love these insights. I always go with Get Seeds Right Here Get Clones
      Right Here for live plants.

    40. 20
      Выяснить больше – [url=https://skoraya-narkologicheskaya-pomoshch15.ru/]наркологическая помощь москва[/url]

      BernardCar

      17 Aug 25 at 3:49 am

    41. Someone essentially assist to make seriously posts
      I’d state. This is the first time I frequented your web page and so far?
      I surprised with the research you made to create this actual put up
      extraordinary. Wonderful task!

      LINK WW88

      17 Aug 25 at 3:49 am

    42. я купил диплом с проводкой [url=http://arus-diplom31.ru/]я купил диплом с проводкой[/url] .

    43. новости спорта сегодня [url=www.novosti-sporta-3.ru/]www.novosti-sporta-3.ru/[/url] .

    44. Incredible! This blog looks just like my old one!
      It’s on a completely different topic but it has pretty much the same layout and design. Wonderful choice of colors!

      HM88 COM

      17 Aug 25 at 3:54 am

    45. Во-вторых, индивидуальный подход к каждому пациенту. Учитываются личные особенности, такие как возраст, пол, социальный статус. Это позволяет создать эффективный план лечения.
      Выяснить больше – http://

      Stevengal

      17 Aug 25 at 3:56 am

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

      Diplomi_ygSa

      17 Aug 25 at 3:57 am

    47. Way cool! Some extremely valid points! I appreciate you penning
      this post plus the rest of the website is very good.

      slot777

      17 Aug 25 at 4:04 am

    48. Мы понимаем уникальность каждого пациента и проводим тщательную диагностику, анализируя его медицинскую историю, психологическое состояние и социальные факторы. На основе полученных данных создаем персональные планы лечения, включающие медикаментозные средства, психотерапию и социальные программы.
      Узнать больше – http://медицинский-вывод-из-запоя.рф/

      Philipkam

      17 Aug 25 at 4:04 am

    49. инъектирование [url=http://www.remontmechty.ru/remont/inekcionnaya-gidroizolyaciya-effektivnaya-zashhita-ot-vlagi ]http://www.remontmechty.ru/remont/inekcionnaya-gidroizolyaciya-effektivnaya-zashhita-ot-vlagi [/url] .

    Leave a Reply