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 23,270 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 , , ,

    23,270 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. JuliusGlush

      21 Aug 25 at 9:48 am

    2. What’s up to all, as I am really keen of reading this blog’s post to be updated on a regular basis.
      It contains nice stuff.

    3. I think that is among the most significant information for me.
      And i’m glad studying your article. But wanna commentary on some basic issues,
      The web site taste is wonderful, the articles is actually excellent : D.

      Excellent task, cheers

      Nổ Hũ TT88

      21 Aug 25 at 9:50 am

    4. You actually make it seem so easy with your presentation but I find
      this matter to be really something which I think I would never understand.
      It seems too complicated and extremely broad for me.
      I’m looking forward for your next post, I’ll try to get the hang of it!

      Live Draw Taiwan

      21 Aug 25 at 9:53 am

    5. WilliamNex

      21 Aug 25 at 9:53 am

    6. устройство плоской кровли https://montazh-ploskoj-krovli.ru

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

      Diplomi_cvsl

      21 Aug 25 at 9:57 am

    8. Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
      Почему это важно? – https://grandeatomy.com.br/novidade-em-produtos

      RodneyCarse

      21 Aug 25 at 10:00 am

    9. Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
      Ознакомьтесь с аналитикой – https://kataberita.net/kerjasama-pt-enero-dengan-brin

      DavidMon

      21 Aug 25 at 10:00 am

    10. В этой информационной статье вы найдете интересное содержание, которое поможет вам расширить свои знания. Мы предлагаем увлекательный подход и уникальные взгляды на обсуждаемые темы, побуждая пользователей к активному мышлению и критическому анализу.
      Перейти к статье – https://freguesianews.com.br/2024/05/26/agencia-minas-gerais-vice-governador-participa-da-feira-multissetorial-de-santa-barbara

      TerrySnivY

      21 Aug 25 at 10:00 am

    11. Создать документы онлайн конструктор трудового договора онлайн: создайте договор, заявление или акт за 5 минут. Простая форма, готовые шаблоны, юридическая точность и возможность скачать в нужном формате.

      datadoc-787

      21 Aug 25 at 10:01 am

    12. Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
      Подробная информация доступна по запросу – https://khalidalmuheirigroup.com/connecting-with-natures-tranquil-essence

      Ricardounuse

      21 Aug 25 at 10:01 am

    13. Nathanfal

      21 Aug 25 at 10:07 am

    14. В этой публикации мы предлагаем подробные объяснения по актуальным вопросам, чтобы помочь читателям глубже понять их. Четкость и структурированность материала сделают его удобным для усвоения и применения в повседневной жизни.
      Только факты! – https://fotoreportexalapa.com/el-tranvia-2

      HenryNix

      21 Aug 25 at 10:08 am

    15. I simply could not depart your website before suggesting that I actually loved the
      standard info a person provide for your guests?
      Is going to be again frequently in order to inspect new posts

      dewa scatter

      21 Aug 25 at 10:09 am

    16. cialis over the counter usa [url=https://tadalify.com/#]where to buy liquid cialis[/url] order cialis soft tabs

      RobertCat

      21 Aug 25 at 10:09 am

    17. This paragraph gives clear idea for the new viewers of blogging, that
      actually how to do blogging.

    18. Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
      Более подробно об этом – https://radiantandbrighter.com/2018/07/15/mariarose

      JordanAbsox

      21 Aug 25 at 10:15 am

    19. купить аттестат о 11 классах [url=www.arus-diplom24.ru]купить аттестат о 11 классах[/url] .

      Diplomi_qpKn

      21 Aug 25 at 10:18 am

    20. бизнес оценка москва оценочная компания

    21. аттестат за 11 класс 2014 купить [url=www.arus-diplom22.ru]аттестат за 11 класс 2014 купить[/url] .

      Diplomi_assl

      21 Aug 25 at 10:22 am

    22. WilliamLig

      21 Aug 25 at 10:24 am

    23. JuliusGlush

      21 Aug 25 at 10:27 am

    24. Nathanfal

      21 Aug 25 at 10:29 am

    25. Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
      Смотрите также… – https://sale-box.de/2023/04/09/boost-your-online-presence-our-top-digital-marketing

      HenryNix

      21 Aug 25 at 10:34 am

    26. Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
      Получить исчерпывающие сведения – https://compagniedesenergiespropres.fr/ma-prime-renov-2022

      Jerrynox

      21 Aug 25 at 10:37 am

    27. ставки на хоккей прогнозы [url=http://prognozy-na-khokkej.ru]http://prognozy-na-khokkej.ru[/url] .

    28. Good post. I learn something totally new and challenging on websites I stumbleupon every day.

      It’s always useful to read articles from other authors and practice a little
      something from their sites.

    29. Hi there mates, how is everything, and what you wish for to say on the topic of this article,
      in my view its in fact amazing for me.

      keo nha cai

      21 Aug 25 at 10:45 am

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

      Diplomi_gtsl

      21 Aug 25 at 10:48 am

    31. A qualidade e o formato das fotos e imagens baixadas do Instagram podem variar dependendo do arquivo original que foi enviado para a rede social.

      link-Motion.com

      21 Aug 25 at 10:50 am

    32. Nathanfal

      21 Aug 25 at 10:50 am

    33. Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
      Узнать из первых рук – https://adidas-tt.ru/?paged=32&cat=1

      WayneDrist

      21 Aug 25 at 10:51 am

    34. I was suggested this blog by my cousin. I’m not certain whether
      or not this post is written through him as no one else recognise such
      certain about my problem. You are wonderful! Thank you!

      호빠

      21 Aug 25 at 10:52 am

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

      Diplomi_resl

      21 Aug 25 at 10:55 am

    36. Everyone loves it when individuals come together and share views.
      Great website, keep it up!

      Elyor Platform

      21 Aug 25 at 10:58 am

    37. Каждый гемблер ищет более выгодные условия для игры в казино, чтобы получить бонус, особые привилегии. Вот почему казино выдают бонусы. Их начисляют очень быстро, после авторизации, а потому не придется класть деньги на счет, тратить свои финансы. https://1000topbonus.website/
      – на сайте представлено огромное количество проверенных, надежных заведений, которые отличаются наличием лицензии и играют на честных условиях, радуют клиентов безупречной работой, регулярными выплатами, дружелюбной службой поддержки.

      verojafeego

      21 Aug 25 at 10:59 am

    38. Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
      Не упусти важное! – https://all4holidays.ru/?paged=23&cat=1

      Ralphmub

      21 Aug 25 at 10:59 am

    39. Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
      Ознакомьтесь с аналитикой – https://www.hotel-sugano.com/bbs/sugano.cgi/www.tovery.net/datasphere.ru/club/user/12/blog/2477/www.hip-hop.ru/forum/id298234-worksale/www.hip-hop.ru/forum/id298234-worksale/sugano.cgi?page40=val

      JordanAbsox

      21 Aug 25 at 11:02 am

    40. togel 4d

      Info Seru Kompetisi Spin Toto Slot 88 & Tebak Angka Togel 4D Unggulan – TOGELONLINE88

      toto slot

      21 Aug 25 at 11:02 am

    41. Этот увлекательный информационный материал подарит вам массу новых знаний и ярких эмоций. Мы собрали для вас интересные факты и сведения, которые обогатят ваш опыт. Откройте для себя увлекательный мир информации и насладитесь процессом изучения!
      Переходите по ссылке ниже – https://vorticeweb.com/asi-se-podra-afiliar-a-las-trabajadoras-del-hogar-al-imss

      JasonSueri

      21 Aug 25 at 11:04 am

    42. Мы предлагаем вам подробное руководство, основанное на проверенных источниках и реальных примерах. Каждая часть публикации направлена на то, чтобы помочь вам разобраться в сложных вопросах и применить знания на практике.
      Ознакомиться с полной информацией – http://www.vlamcoat.be/2013/03/21/magna-fringilla-quis-condimentum

      RickyPrima

      21 Aug 25 at 11:05 am

    43. Основные типы бетонных свайных
      изделий

    44. В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
      Узнать напрямую – https://www.brnnetwork.org/gallery/web-american-kestrel-james-poling

      RodneyCarse

      21 Aug 25 at 11:06 am

    45. JuliusGlush

      21 Aug 25 at 11:06 am

    46. can you buy viagra in mexico [url=https://sildenapeak.shop/#]SildenaPeak[/url] best otc female viagra

      RobertCat

      21 Aug 25 at 11:07 am

    47. Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
      Это стоит прочитать полностью – https://www.iso-studio.it/inail-riduzione-del-premio-ot23-interventi-entro-fine-anno

      HenryNix

      21 Aug 25 at 11:08 am

    48. Stavki Prognozy [url=stavki-prognozy-two.ru]stavki-prognozy-two.ru[/url] .

    49. Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
      Углубить понимание вопроса – https://redcrosstrainingcentre.org/2013/10/04/a-look-inside-the-protein-bar

      HenryNix

      21 Aug 25 at 11:10 am

    50. Wow, incredible blog structure! How long have you been running a blog for?

      you made blogging glance easy. The whole glance of your web site is
      magnificent, as neatly as the content material!

      https://paitomacau.top/

    Leave a Reply