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 19,705 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 , , ,

    19,705 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://novosti-sporta-2.ru/]http://novosti-sporta-2.ru/[/url] .

    2. Инфузии выполняются с помощью автоматизированных насосов, позволяющих скорректировать скорость введения в зависимости от показателей безопасности.
      Получить дополнительные сведения – http://medicinskij-vyvod-iz-zapoya.ru

      RobertExevy

      15 Aug 25 at 10:34 pm

    3. ElijahGicky

      15 Aug 25 at 10:34 pm

    4. новости спорта футбол [url=www.novosti-sporta-2.ru/]www.novosti-sporta-2.ru/[/url] .

    5. купить диплом в киеве цены [url=http://educ-ua5.ru]купить диплом в киеве цены[/url] .

      Diplomi_owKl

      15 Aug 25 at 10:37 pm

    6. Narcology Clinic в Москве оказывает экстренную наркологическую помощь дома — скорая выездная служба выполняет детоксикацию, капельницы и мониторинг до нормализации состояния. Анонимно и круглосуточно.
      Подробнее можно узнать тут – [url=https://skoraya-narkologicheskaya-pomoshch15.ru/]скорая наркологическая помощь московская область[/url]

      BernardCar

      15 Aug 25 at 10:43 pm

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

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

    9. Quality posts is the key to interest the people to pay a quick visit the website,
      that’s what this website is providing.

    10. [url=https://казанчугунный.рф ]God see[/url]

      JosephNof

      15 Aug 25 at 10:52 pm

    11. ElijahGicky

      15 Aug 25 at 10:54 pm

    12. I like what you guys are up too. This type of clever work and exposure!
      Keep up the awesome works guys I’ve incorporated you guys to my own blogroll.

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

    14. What’s Taking place i am new to this, I stumbled upon this I’ve found It positively useful
      and it has aided me out loads. I am hoping to
      give a contribution & aid other users like
      its helped me. Good job.

      agen toto togel

      15 Aug 25 at 11:05 pm

    15. Tadalify [url=https://tadalify.com/#]Tadalify[/url] Tadalify

      RobertCat

      15 Aug 25 at 11:12 pm

    16. ElijahGicky

      15 Aug 25 at 11:13 pm

    17. Ꮤhat i Ԁοn’t realize is if tгuth be told how you агe no longer actually
      a lot more well-likeɗ than you may be now. Yоu ɑre so intelligent.
      You understand thus significantly in the caѕe of this suЬject, produced me for mʏ part cоnsidеr it from ѕo many numerous angles.
      Its lіke women and men don’t seem to be fascinateⅾ except it is оne thing to
      accomplish with Lady gagɑ! Yoᥙr іndividual stuffѕ excellent.
      Always maintain it up!

      Mʏ page; green Bags

      green Bags

      15 Aug 25 at 11:13 pm

    18. Haroldbon

      15 Aug 25 at 11:14 pm

    19. I like the helpful info you provide in your articles. I’ll bookmark your blog and
      check again here frequently. I’m quite certain I will learn lots of new stuff right here!
      Best of luck for the next!

      Look into my web site zakelijke wifi nederland

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

      Jasonled

      15 Aug 25 at 11:16 pm

    21. Врачебный состав клиники “Путь к выздоровлению” состоит из высококвалифицированных специалистов в области наркологии. Наши врачи-наркологи имеют обширный опыт работы с зависимыми пациентами и постоянно совершенствуют свои навыки.
      Подробнее – http://нарко-фильтр.рф

      Billymub

      15 Aug 25 at 11:16 pm

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

    23. прикольные горшки для цветов [url=http://www.dizaynerskie-kashpo-rnd.ru]прикольные горшки для цветов[/url] .

      dizainerskie kashpo_wuEr

      15 Aug 25 at 11:31 pm

    24. I am extremely impressed with your writing skills and also with the layout on your
      weblog. Is this a paid theme or did you modify
      it yourself? Anyway keep up the nice quality writing, it’s rare to see a great blog like
      this one these days.

      bs2best

      15 Aug 25 at 11:32 pm

    25. ElijahGicky

      15 Aug 25 at 11:33 pm

    26. Для полноценного участия
      в играх на реальные деньги на платформе PokerDom
      требуется авторизация в личном кабинете.

      покердом

      15 Aug 25 at 11:34 pm

    27. Купить диплом о высшем образовании!
      Мы изготавливаем дипломы любых профессий по выгодным ценам— [url=http://kupitediplom0027.ru/]kupitediplom0027.ru[/url]

      Lazrgvh

      15 Aug 25 at 11:34 pm

    28. Запчасти для плиты Hansa FCGW62020 Запчасти для стиральной машины Ariston AVL 14 (FR) (CO): Европейский стандарт надежности. Обеспечьте бесперебойную работу вашей стиральной машины, используя оригинальные или качественные аналоги запчастей.

      Calebpes

      15 Aug 25 at 11:41 pm

    29. Скорая наркологическая служба Narcology Clinic в Москве работает круглосуточно. Выезд к пациенту, медикаментозная стабилизация, детоксикация и психологическая поддержка до выхода из кризисного состояния.
      Подробнее – [url=https://skoraya-narkologicheskaya-pomoshch-moskva.ru/]наркологическая помощь москве[/url]

      Robertkix

      15 Aug 25 at 11:46 pm

    30. Tadalify: best price for cialis – Tadalify

      PeterTEEFS

      15 Aug 25 at 11:49 pm

    31. ElijahGicky

      15 Aug 25 at 11:52 pm

    32. Haroldbon

      15 Aug 25 at 11:56 pm

    33. Найти друга на форуме знакомств https://perekrestok.1bb.ru форум без регистрации где есть тема любовь и отношения, хорошие люди, есть модерация все культурно и красиво.

      perekrestok-330

      15 Aug 25 at 11:58 pm

    34. Fastidious respond in return of this matter with genuine arguments and describing everything about that.

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

    36. Мы понимаем уникальность каждого пациента и проводим тщательную диагностику, анализируя его медицинскую историю, психологическое состояние и социальные факторы. На основе полученных данных создаем персональные планы лечения, включающие медикаментозные средства, психотерапию и социальные программы.
      Узнать больше – https://медицинский-вывод-из-запоя.рф/vyvod-iz-zapoya-v-stacionare-v-rostove-na-donu.xn--p1ai/

      Philipkam

      16 Aug 25 at 12:03 am

    37. форум общения Покупки в интернет-магазинах какие лучше выбрать? что посоветуете, обсуждение на форуме очень были полезны

      perekrestok-907

      16 Aug 25 at 12:05 am

    38. Danielchumn

      16 Aug 25 at 12:07 am

    39. Найти друга на форуме знакомств https://perekrestok.1bb.ru форум без регистрации где есть тема любовь и отношения, хорошие люди, есть модерация все культурно и красиво.

      perekrestok-311

      16 Aug 25 at 12:09 am

    40. http://kamameds.com/# Online sources for Kamagra in the United States

      Danielchumn

      16 Aug 25 at 12:11 am

    41. Zasto se javlja bol u bubregu: od kamenaca i infekcija do prehlade. Kako prepoznati opasne simptome i brzo zapoceti lecenje. Korisne informacije.

    42. ElijahGicky

      16 Aug 25 at 12:11 am

    43. как купить диплом с проведением [url=http://arus-diplom32.ru/]как купить диплом с проведением[/url] .

    44. Wow, this piece of writing is good, my sister is analyzing these kinds of things,
      therefore I am going to tell her.

    45. With unrestricted accessibility tο exercise worksheets, OMT equips pupils tߋo master mathematics via repetition,
      constructing love f᧐r tһe subject and test confidence.

      Experience versatile knowing anytime, аnywhere through OMT’ѕ tһorough online e-learning platform, featuring unrestricted access tօ video
      lessons ɑnd interactive tests.

      As math forms tһе bedrock ᧐f rational
      thinking and critical analytical іn Singapore’s education ѕystem, expert math tuition ⲟffers tһe personalized guidance neeԁed to tսrn difficulties іnto
      accomplishments.

      Tuition in primary school mathematics is essential fߋr PSLE preparation, ɑѕ it
      introduces innovative methods fоr dealing with non-routine ρroblems tһаt stump ⅼots of candidates.

      Secondary school math tuition іs essential foг O Levels aѕ it enhances mastery ᧐f algebraic adjustment, ɑ core element that օften sһows up in test inquiries.

      Ιn an affordable Singaporean education аnd learning system,
      junior college math tuition ɡives pupils tһe sidxe to achieve
      high qualities required fⲟr university admissions.

      Ꭲhe exclusive OMT curriculum stands ɑpart by
      prolonging MOE curriculum with enrichment ߋn analytical modeling, ideal for data-driven exam concerns.

      Limitless accessibility tο worksheets indicates үou exercise till shiok, improving yߋur math self-confidence and qualities quіckly.

      Math tuition ρrovides enrichment beyond the basics, challenging
      gifted Singapore trainees tօ aim foг difference іn exams.

      Also visit my homepage – new york act math tutoring

    46. I was curious if you ever considered changing
      the structure of your blog? Its very well written; I love what youve got
      to say. But maybe you could a little more in the way
      of content so people could connect with it better. Youve got an awful
      lot of text for only having 1 or two images. Maybe you could space it
      out better?

      KL99

      16 Aug 25 at 12:15 am

    47. Kamagra reviews from US customers: Safe access to generic ED medication – Kamagra oral jelly USA availability

      RichardTit

      16 Aug 25 at 12:15 am

    48. I’m really loving the theme/design of your site. Do you ever run into
      any internet browser compatibility issues? A few of my blog visitors
      have complained about my site not working correctly in Explorer
      but looks great in Safari. Do you have any solutions to help fix this issue?

    49. Таким образом, наш подход направлен на создание комплексной системы поддержки, которая помогает каждому пациенту справиться с зависимостью и вернуться к полноценной жизни.
      Получить дополнительную информацию – [url=https://srochnyj-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-cena-v-kazani.ru/]вывод из запоя вызов[/url]

      Richardfowly

      16 Aug 25 at 12:18 am

    50. Zasto se javlja https://www.bol-u-bubrezima.com: od kamenaca i infekcija do prehlade. Kako prepoznati opasne simptome i brzo zapoceti lecenje. Korisne informacije.

    Leave a Reply