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 73,264 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 , , ,

    73,264 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. reinspiregreece – I’ll return often, this feels like a space filled with inspiration and beauty.

    2. Jeromeliz

      3 Oct 25 at 5:46 am

    3. DragonMoney – онлайн-казино с лицензией, предлагает выгодные бонусы, разнообразные игры от ведущих провайдеров, мгновенные выплаты и круглосуточную поддержку
      драгон мани

      Richardusags

      3 Oct 25 at 5:47 am

    4. «Комфорт-Сервис» в Орле специализируется на уничтожении насекомых холодным туманом по авторской запатентованной технологии, заявляя отсутствие необходимости повторной обработки через две недели. На http://www.xn—57-fddotkqrbwclei3a.xn--p1ai/ подробно описано оборудование итальянского класса, перечень вредителей, регламент работ и требования безопасности; используются препараты Bayer, BASF, FMC с нейтральным запахом. Понравилась прозрачность: время экспозиции и проветривания, конфиденциальный выезд без маркировки, сервисное обслуживание и разъяснения по гарантиям.

      belaftcam

      3 Oct 25 at 5:47 am

    5. Wow! This blog looks exactly like my old one! It’s on a totally different topic but it has pretty much
      the same page layout and design. Outstanding choice of colors!

    6. новости олимпиады [url=http://www.novosti-sporta-16.ru]http://www.novosti-sporta-16.ru[/url] .

    7. прогнозы на сегодня футбол [url=http://prognozy-na-futbol-9.ru/]http://prognozy-na-futbol-9.ru/[/url] .

    8. bigprintnewspapers – The brand projection seems serious, visuals support the message strongly.

      Luther Willmore

      3 Oct 25 at 5:52 am

    9. Casinos that accept a wide range of cryptocurrencies provide greater flexibility.

      web site

      3 Oct 25 at 5:53 am

    10. ставка прогноз ру [url=www.stavka-10.ru/]www.stavka-10.ru/[/url] .

      stavka_dcSi

      3 Oct 25 at 5:54 am

    11. Обратился за продвижением сайта в поисковых системах, потому что клиентов практически не было. После проведённых работ пошёл рост позиций и увеличился поток заказов. Сейчас бизнес чувствует себя гораздо увереннее, спасибо за качественную работу: https://mihaylov.digital/

      Steventob

      3 Oct 25 at 5:54 am

    12. OMT’s appealing video clip lessons tᥙrn complex math concepts іnto amazing stories,
      helping Singapore trainees love tһe subject and rеally feel influenced to
      ace tһeir tests.

      Prepare fօr success іn upcoming examinations witһ OMT Math Tuition’ѕ exclusive curriculum, developed to foster crucial thinking аnd confidence іn every
      trainee.

      Cօnsidered thɑt mathematics plays a critical function in Singapore’ѕ
      economic advancement and development, investing in specialized math tuition gears սp trainees
      ԝith the prоblem-solving abilities required tο thrive in а
      competitive landscape.

      primary school math tuition builds exam endurance tһrough timed drills,
      imitating tһe PSLE’s two-paper format and assisting trainees handle tіme effectively.

      Tuition assists secondary students ⅽreate exam strategies, ѕuch
      as time allowance foг Ƅoth O Level mathematics papers, ƅring about much better generaⅼ
      efficiency.

      Tuition incorporates pure ɑnd applied mathematics effortlessly, preparing students fⲟr the interdisciplinary nature оf A Level issues.

      The distinctiveness ᧐f OMT comes from its proprietary math curriculum tһat
      prolongs MOE material ᴡith project-based knowing f᧐r functional application.

      Multi-device compatibility leh, ѕo change
      from laptop to phone and keep increasing tһose grades.

      With limited class time іn schools, math tuition expands finding ߋut hօurs, essential fߋr understanding tһe substantial Singapore mathematics curriculum.

      Տtop by my ρage best jc math tuition

    13. DragonMoney – лицензированное казино с щедрыми бонусами, топовыми играми, быстрыми выплатами и круглосуточной поддержкой
      драгон мани официальный сайт

      EdgarPak

      3 Oct 25 at 5:54 am

    14. прогнозы на ставки спорт [url=www.stavka-12.ru]www.stavka-12.ru[/url] .

      stavka_ldSi

      3 Oct 25 at 5:55 am

    15. JEETA से जुड़ें और ऑनलाइन गेमिंग की एक नई
      दुनिया का अनुभव करें।

    16. Hi I am so excited I found your blog page, I really found you by error, while I was searching on Google for something else, Anyhow I
      am here now and would just like to say thanks for a fantastic post and a all round exciting blog (I also love the theme/design),
      I don’t have time to read through it all at the moment but I
      have book-marked it and also included your RSS feeds, so when I have time I will be back to read a lot more, Please do keep up the
      superb work.

      Visit Website

      3 Oct 25 at 5:56 am

    17. купить свидетельство о заключении брака [url=https://rudik-diplom1.ru]купить свидетельство о заключении брака[/url] .

      Diplomi_qwer

      3 Oct 25 at 5:57 am

    18. прогноз ставки [url=https://stavka-12.ru/]прогноз ставки[/url] .

      stavka_ccSi

      3 Oct 25 at 6:01 am

    19. футбол сегодня прогнозы [url=https://prognozy-na-futbol-9.ru/]prognozy-na-futbol-9.ru[/url] .

    20. прогнозы ставки на спорт сайт [url=https://stavka-10.ru/]https://stavka-10.ru/[/url] .

      stavka_pwSi

      3 Oct 25 at 6:02 am

    21. Generic Cialis without a doctor prescription [url=https://tadalmedspharmacy.shop/#]Generic Cialis without a doctor prescription[/url] Buy Tadalafil 20mg

      TimothyArrar

      3 Oct 25 at 6:04 am

    22. в прогнозе [url=stavka-12.ru]stavka-12.ru[/url] .

      stavka_gzSi

      3 Oct 25 at 6:05 am

    23. JEETA-তে যোগ দিন এবং অনলাইন গেমিংয়ের এক নতুন জগতের অভিজ্ঞতা নিন।

    24. ставки и прогнозы букмекеров на футбол сегодня [url=www.stavka-10.ru/]www.stavka-10.ru/[/url] .

      stavka_fsSi

      3 Oct 25 at 6:06 am

    25. GeraldObedo

      3 Oct 25 at 6:07 am

    26. прогнозы на сегодня футбол [url=www.prognozy-na-futbol-9.ru/]www.prognozy-na-futbol-9.ru/[/url] .

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

      Diplomi_cpPi

      3 Oct 25 at 6:08 am

    28. true vital meds: Sildenafil 100mg price – sildenafil

      BruceMaivy

      3 Oct 25 at 6:10 am

    29. ставки на спорт прогноз [url=https://stavka-10.ru/]stavka-10.ru[/url] .

      stavka_obSi

      3 Oct 25 at 6:10 am

    30. новости футбольных клубов [url=https://novosti-sporta-16.ru]https://novosti-sporta-16.ru[/url] .

    31. I think that is among the most important info for me.

      And i’m glad studying your article. However wanna commentary on some common issues, The
      website taste is perfect, the articles is actually great : D.
      Good process, cheers

    32. Jeromeliz

      3 Oct 25 at 6:11 am

    33. прогноз ставок на футбол [url=www.prognozy-na-futbol-9.ru/]www.prognozy-na-futbol-9.ru/[/url] .

    34. tadalafil: Generic tadalafil 20mg price – tadalafil uk generic

      MartinJaive

      3 Oct 25 at 6:14 am

    35. Kaizenaire.com is yⲟur go-to resource in Singapore fоr the most current shopping promotions, unique deals,
      аnd muѕt-attend events.

      Singaporeans ɑlways focus оn worth, flourishing іn Singapore’ѕ environment аs
      a promotions-packed shopping heaven.

      Singaporeans typically participate іn digital photography walks t᧐ record the city’ѕ stunning horizon, and keep
      іn mind to remаin updated on Singapore’ѕ
      most current promotions ɑnd shopping deals.

      Bigo ɡives online streaming аnd social amusement applications, enjoyed Ƅy Singaporeans for tһeir interactive ϲontent and aгea involvement.

      Klarra сreates contemporary women’ѕ clothes with clean lines one, treasured
      byy mіnimal Singaporeans fоr tһeir versatile, premium items mah.

      Benefit Tong Kee conveniences ᴡith silky poultry rice
      ɑnd sideѕ, cherished by family membeгѕ for pleasant flavors and generous sections.

      Aiyo, sharp leh, brand-neᴡ ρrice cuts on Kaizenaire.сom
      one.

      Also visit my web blog … singapore promos

    36. прогноз на спорт на сегодня от профессионалов [url=www.prognozy-na-sport-11.ru/]www.prognozy-na-sport-11.ru/[/url] .

    37. купить аттестат за классов [url=www.rudik-diplom14.ru/]купить аттестат за классов[/url] .

      Diplomi_vtea

      3 Oct 25 at 6:16 am

    38. спорт онлайн [url=https://novosti-sporta-16.ru/]novosti-sporta-16.ru[/url] .

    39. stavka prognoz [url=http://www.stavka-10.ru]http://www.stavka-10.ru[/url] .

      stavka_cgSi

      3 Oct 25 at 6:17 am

    40. Hey are using WordPress for your blog platform?
      I’m new to the blog world but I’m trying to get started and create my
      own. Do you require any html coding knowledge to make your
      own blog? Any help would be really appreciated!

    41. прогнощы [url=www.stavka-12.ru]www.stavka-12.ru[/url] .

      stavka_mcSi

      3 Oct 25 at 6:20 am

    42. прогнозы на спорт с высокой проходимостью бесплатно [url=http://prognozy-na-sport-11.ru/]http://prognozy-na-sport-11.ru/[/url] .

    43. sliv.fun [url=www.sliv.fun/]www.sliv.fun/[/url] .

    44. GeraldObedo

      3 Oct 25 at 6:22 am

    45. новости чемпионатов [url=http://novosti-sporta-15.ru]http://novosti-sporta-15.ru[/url] .

    46. прогнозы букмекеров на сегодня [url=https://www.stavka-10.ru]https://www.stavka-10.ru[/url] .

      stavka_iwSi

      3 Oct 25 at 6:22 am

    47. купить диплом в бузулуке [url=https://rudik-diplom3.ru]купить диплом в бузулуке[/url] .

      Diplomi_jhei

      3 Oct 25 at 6:22 am

    48. I think that is one of the most significant information for me.

      And i am satisfied studying your article. But wanna observation on few common things, The site taste is ideal, the articles is in point of fact great : D.
      Just right process, cheers

    Leave a Reply