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,697 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,697 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. где купить аттестат за 11 классов [url=arus-diplom21.ru]где купить аттестат за 11 классов[/url] .

    2. где можно купить аттестат за 11 класс [url=http://arus-diplom24.ru/]где можно купить аттестат за 11 класс[/url] .

      Diplomi_qqsa

      18 Aug 25 at 5:49 am

    3. Stevenchode

      18 Aug 25 at 5:53 am

    4. Nikmati guide lengkap permainan slot online dari TESLATOTO.
      Dapatkan tips menang, pola efektif, saran profesional, dan verifikasi
      pembayaran. Kerjasama dengan provider ternama seperti Pragmatic
      Play dan PG Soft untuk pengalaman bermain terbaik.

      teslatoto daftar

      18 Aug 25 at 5:53 am

    5. Danielfloar

      18 Aug 25 at 5:53 am

    6. Great article, just what I wanted to find.

      Linetogel

      18 Aug 25 at 5:57 am

    7. Вызов наркологической помощи в владимире — это важная услуга, помогающая помогает людям справиться с зависимостями. Клиника наркологии в владимире предоставляет разнообразные услуги, включая лечение зависимостей и медицинскую помощь при алкоголизме. Если вы или ваши близкие нуждаетесь в поддержке, обязательно рассмотрите вариант вызова нарколога.Первичная консультация у нарколога является важным шагом на пути к исцелению. Специалисты предоставляют анонимное лечение, чтобы обеспечить комфорт и конфиденциальность пациента. Круглосуточная горячая линия готова ответить на все вопросы и оказать скорейшую помощь при отравлении. vivod-iz-zapoya-vladimir009.ru Реабилитация зависимых включает программы по лечению зависимостей и психотерапевтические методики. Вы можете вызвать нарколога в любое время, что делает процесс лечения максимально удобным. Не откладывайте обращение за помощью, ведь здоровье — это главное.

    8. Hello to every one, the contents existing at this web site
      are truly awesome for people knowledge, well,
      keep up the good work fellows.

      creelpetcare.com

      18 Aug 25 at 5:59 am

    9. мостбе [url=http://mostbet11067.ru]мостбе[/url]

      mostbet_zgon

      18 Aug 25 at 5:59 am

    10. мостбет вход через соцсети [url=http://mostbet11072.ru]http://mostbet11072.ru[/url]

      mostbet_kg_hrKr

      18 Aug 25 at 6:00 am

    11. Wonderful goods from you, man. I’ve take note
      your stuff prior to and you’re just too excellent.
      I really like what you’ve bought here, really like what you are stating
      and the way in which through which you are saying it.
      You make it entertaining and you continue
      to take care of to keep it sensible. I can not wait to learn much more from you.

      This is actually a tremendous website.

      IDM Lover

      18 Aug 25 at 6:02 am

    12. Комплексный подход: лечение зависимости — это процесс, включающий медикаментозную терапию, психотерапевтическую помощь, физиотерапию и социальную реабилитацию.
      Детальнее – [url=https://srochno-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-v-kruglosutochno-v-ufe.ru/]вывод из запоя вызов на дом в уфе[/url]

      Edgargab

      18 Aug 25 at 6:04 am

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

      Diplomi_jter

      18 Aug 25 at 6:05 am

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

    15. package delivery nyc https://delivery-new-york.com/

    16. аттестат 11 класса с куар кодом купить [url=https://www.arus-diplom24.ru]аттестат 11 класса с куар кодом купить[/url] .

      Diplomi_wpsa

      18 Aug 25 at 6:11 am

    17. Самолечение или попытка «переждать» запой дома без врача может обернуться серьёзными осложнениями. Обращение к наркологу даёт пациенту:
      Подробнее – [url=https://narko-zakodirovan.ru/]вывод из запоя капельница[/url]

      RodneyCip

      18 Aug 25 at 6:11 am

    18. buy online rifaximin

      rifaximin compare price cvs

    19. new york package delivery shipping cost from new york to florida

    20. интернет магазины сантехники [url=http://evropejskaya-santehnika2.ru/]http://evropejskaya-santehnika2.ru/[/url] .

    21. I’m extremely impressed with your writing abilities as neatly as with
      the layout to your blog. Is that this a paid subject or did you customize it your self?
      Anyway keep up the excellent quality writing, it is rare
      to peer a great weblog like this one today..

      sweet bonanza

      18 Aug 25 at 6:20 am

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

      Diplomi_xasl

      18 Aug 25 at 6:22 am

    23. купить аттестаты за 11 классов омск [url=www.arus-diplom25.ru/]купить аттестаты за 11 классов омск[/url] .

      Diplomi_nzot

      18 Aug 25 at 6:22 am

    24. Danielfloar

      18 Aug 25 at 6:24 am

    25. Hello there, You’ve done an excellent job. I will definitely digg
      it and personally recommend to my friends. I am confident they’ll be benefited from this website.

      8KBET COM

      18 Aug 25 at 6:25 am

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

      Diplomi_gver

      18 Aug 25 at 6:27 am

    27. Очень рекомендую к прочтению:

      Зацепил раздел про all-hotels-online.ru.

      Вот, делюсь ссылкой:

      [url=https://all-hotels-online.ru]https://all-hotels-online.ru[/url]

      Надеюсь, эта информация сэкономит вам время.

      rusPoito

      18 Aug 25 at 6:28 am

    28. купить аттестат 10 11 класс в сухиничах [url=http://arus-diplom21.ru/]купить аттестат 10 11 класс в сухиничах[/url] .

    29. My brother suggested I might like this website.

      He was totally right. This publish actually made my day.
      You can not imagine just how a lot time I had spent for this info!
      Thank you!

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

      Diplomi_qyer

      18 Aug 25 at 6:34 am

    31. прогноз на спорт футбол на сегодня точный [url=www.kompyuternye-prognozy-na-futbol14.ru]www.kompyuternye-prognozy-na-futbol14.ru[/url] .

    32. где купить аттестат 11 класса [url=http://arus-diplom21.ru/]где купить аттестат 11 класса[/url] .

    33. купить аттестат 11 классов украина [url=https://arus-diplom24.ru/]купить аттестат 11 классов украина[/url] .

      Diplomi_mpsa

      18 Aug 25 at 6:35 am

    34. Stevenchode

      18 Aug 25 at 6:36 am

    35. Pretty portion of content. I simply stumbled upon your weblog and in accession capital to say that I get actually loved account your weblog posts.
      Anyway I’ll be subscribing to your feeds and even I fulfillment you get entry to persistently rapidly.

    36. Great blog! Do you have any suggestions for aspiring writers?

      I’m hoping to start my own site soon but
      I’m a little lost on everything. Would you advise starting with a free platform
      like WordPress or go for a paid option? There are so
      many choices out there that I’m totally confused ..
      Any recommendations? Appreciate it!

    37. Very nice article, totally what I was looking for.

    38. спорт прогнозы на футбол [url=https://kompyuternye-prognozy-na-futbol14.ru/]спорт прогнозы на футбол[/url] .

    39. мостбет вход [url=https://www.mostbet11068.ru]https://www.mostbet11068.ru[/url]

      mostbet_xspn

      18 Aug 25 at 6:45 am

    40. мостбет ставки онлайн [url=www.mostbet11067.ru]www.mostbet11067.ru[/url]

      mostbet_twon

      18 Aug 25 at 6:47 am

    41. Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
      Как достичь результата? – https://f5fashion.vn/chia-se-51-ve-hinh-bong-hoa-dep-moi-nhat

      Michaelcar

      18 Aug 25 at 6:47 am

    42. Наши наркологи придерживаются принципов уважительного и внимательного отношения к пациентам, создавая атмосферу доверия. Они проводят детальное обследование, выявляют коренные причины зависимости и разрабатывают индивидуальные стратегии лечения. Профессионализм и компетентность врачей являются ключевыми факторами успешного восстановления пациентов.
      Подробнее – https://нарко-фильтр.рф/vivod-iz-zapoya-v-kruglosutochno-v-rostove-na-donu

      Billymub

      18 Aug 25 at 6:49 am

    43. Wow, fantastic blog layout! How long have you been blogging for?
      you make blogging look easy. The overall look of your site is magnificent, let alone the
      content!

    44. Danielfloar

      18 Aug 25 at 6:55 am

    45. компьютерные прогнозы на футбол [url=http://kompyuternye-prognozy-na-futbol14.ru/]компьютерные прогнозы на футбол[/url] .

    46. аттестат за 11 класс купить архангельск [url=arus-diplom24.ru]аттестат за 11 класс купить архангельск[/url] .

      Diplomi_cusa

      18 Aug 25 at 6:55 am

    47. Tadalify [url=https://tadalify.shop/#]Tadalify[/url] Tadalify

      RobertCat

      18 Aug 25 at 6:57 am

    48. Экстренная помощь при алкоголизме от Narcology Clinic в Москве — выезд врачей в любую точку города, купирование острых состояний, поддержка пациента до стабильного состояния, профессионально и в конфиденциальности.
      Углубиться в тему – [url=https://skoraya-narkologicheskaya-pomoshch-moskva11.ru/]частная наркологическая помощь москва[/url]

      TerryPROOT

      18 Aug 25 at 6:57 am

    49. Good way of explaining, and fastidious article to get
      information about my presentation subject, which i am going to
      deliver in university.

      Yuma Asami

      18 Aug 25 at 7:00 am

    Leave a Reply