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 22,377 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 , , ,

    22,377 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. Мы предлагаем вам подробное руководство, основанное на проверенных источниках и реальных примерах. Каждая часть публикации направлена на то, чтобы помочь вам разобраться в сложных вопросах и применить знания на практике.
      Ознакомиться с полной информацией – https://termoplasticabra.com/general-maintenance-for-your-water-heater

      Millardzoofs

      18 Aug 25 at 8:07 am

    2. Hello, Neat post. There is an issue together with your site in internet explorer, might test this?

      IE still is the market chief and a good part of folks will omit your excellent writing due to this problem.

      Axireich

      18 Aug 25 at 8:08 am

    3. В статье представлены ключевые моменты по актуальной теме, дополненные советами экспертов и ссылками на дополнительные ресурсы. Цель материала — дать читателю инструменты для самостоятельного развития и принятия осознанных решений.
      Это стоит прочитать полностью – https://madeinma-creations.fr/?product=bavoir-pour-bebe-3

      Jasonnug

      18 Aug 25 at 8:09 am

    4. I visit day-to-day a few sites and blogs to read posts, however this blog provides feature
      based articles.

      link slot 4d

      18 Aug 25 at 8:12 am

    5. I have read so many articles about the blogger lovers however this piece of writing is genuinely a fastidious post,
      keep it up.

      Continued

      18 Aug 25 at 8:15 am

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

    7. My partner and I stumbled over here coming from a different web address and
      thought I might as well check things out. I like what I
      see so now i am following you. Look forward to exploring your web page for a second time.

    8. Мы предлагаем документы университетов, которые находятся на территории всей Российской Федерации. Купить диплом ВУЗа:
      [url=http://ford-talks.ru/viewtopic.php?f=12&t=6700/]как купить аттестат за 11 класс форум[/url]

      Diplomi_inPn

      18 Aug 25 at 8:19 am

    9. Asking questions are truly fastidious thing if you are not
      understanding something completely, except
      this article offers pleasant understanding yet.

      89 BET

      18 Aug 25 at 8:27 am

    10. Посетите сайт https://room-alco.ru/ и вы сможете продать элитный алкоголь. Скупка элитного алкоголя в Москве по высокой цене с онлайн оценкой или позвоните по номеру телефона на сайте. Оператор работает круглосуточно. Узнайте на сайте основных производителей элитного спиртного, по которым возможна быстрая оценка и скупка алкоголя по выгодной для обоих сторон цене.

      kahumdining

      18 Aug 25 at 8:27 am

    11. Этот текст призван помочь читателю расширить кругозор и получить практические знания. Мы используем простой язык, наглядные примеры и структурированное изложение, чтобы сделать обучение максимально эффективным и увлекательным.
      Информация доступна здесь – https://www.bergon-nature-jardin.com/jeffrey-veen-quote

      Danielinsag

      18 Aug 25 at 8:28 am

    12. mostbet сайт регистрация [url=mostbet11074.ru]mostbet11074.ru[/url]

      mostbet_kg_kisn

      18 Aug 25 at 8:29 am

    13. AnthonySef

      18 Aug 25 at 8:35 am

    14. Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
      Ознакомиться с деталями – https://elsardinero.org/cinco-razones-para-volverse-loco-por-los-pistachos

      DaronHelia

      18 Aug 25 at 8:35 am

    15. Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
      Узнать напрямую – https://sagradoespaciointerior.com/producto/prueba1

      DavidDaype

      18 Aug 25 at 8:36 am

    16. Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
      Открыть полностью – http://centaure-faconnage.fr/cropped-imprimerie-centaure-faconnage-image-fond-header1-gif

      IsraelUnsum

      18 Aug 25 at 8:38 am

    17. Hi there, just became alert to your blog through Google,
      and found that it’s truly informative. I am gonna watch out for brussels.
      I will appreciate if you continue this in future. Lots of people will be benefited from your
      writing. Cheers!

      ĐÁ GÀ 89BET

      18 Aug 25 at 8:39 am

    18. гидроизоляция цена за м2 [url=https://offthevylc.ru/polezno-znat/ceny-na-gidroizoljaciju-v-moskve-i-regionah-rossii.html/]offthevylc.ru/polezno-znat/ceny-na-gidroizoljaciju-v-moskve-i-regionah-rossii.html[/url] .

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

      Diplomi_nvOn

      18 Aug 25 at 8:40 am

    20. Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
      Практические советы ждут тебя – https://matronastore.com/product/rainbow-moon-earrings

      Jasonnug

      18 Aug 25 at 8:40 am

    21. Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
      Ознакомьтесь с аналитикой – https://fertiggoods.com/premium-essay-writing-services

      Scottcog

      18 Aug 25 at 8:41 am

    22. Tadalify: buy cialis online in austalia – Tadalify

      ElijahKic

      18 Aug 25 at 8:42 am

    23. Мы можем предложить документы институтов, расположенных в любом регионе России. Купить диплом любого университета:
      [url=http://kherson.forum2x2.ru/login/]купить аттестат 11 класс в спб[/url]

      Diplomi_lcPn

      18 Aug 25 at 8:42 am

    24. гидроизоляция цена за м2 [url=https://offthevylc.ru/polezno-znat/ceny-na-gidroizoljaciju-v-moskve-i-regionah-rossii.html/]https://offthevylc.ru/polezno-znat/ceny-na-gidroizoljaciju-v-moskve-i-regionah-rossii.html/[/url] .

    25. мостбет сайт бк [url=http://mostbet11072.ru]мостбет сайт бк[/url]

      mostbet_kg_tnKr

      18 Aug 25 at 8:45 am

    26. VictorBex

      18 Aug 25 at 8:45 am

    27. Asking questions are actually pleasant thing if you are not understanding something fully,
      however this piece of writing gives nice understanding even.

      toto

      18 Aug 25 at 8:46 am

    28. Мы можем предложить документы институтов, расположенных на территории всей России. Заказать диплом любого ВУЗа:
      [url=http://markusragger.at/chess/index.php/kforum/jm-news-pro-module/797272-qr/]купить аттестат 11 класса 2016[/url]

      Diplomi_ktPn

      18 Aug 25 at 8:48 am

    29. как зарегистрироваться в мостбет [url=http://mostbet11070.ru]http://mostbet11070.ru[/url]

      mostbet_yoEi

      18 Aug 25 at 8:49 am

    30. Having read this I believed it was extremely informative.
      I appreciate you spending some time and effort to put this
      content together. I once again find myself personally spending way too much
      time both reading and commenting. But so what, it was still worth it!

    31. mostbet официальный сайт [url=https://mostbet11070.ru/]mostbet официальный сайт[/url]

      mostbet_ryEi

      18 Aug 25 at 8:49 am

    32. Briangow

      18 Aug 25 at 8:50 am

    33. Hey! This is kind of off topic but I need some help from an established blog.
      Is it very difficult to set up your own blog?

      I’m not very techincal but I can figure things out pretty quick.
      I’m thinking about making my own but I’m not sure where to start.
      Do you have any tips or suggestions? Thank you

    34. mostbet kz скачать [url=http://mostbet11070.ru/]mostbet kz скачать[/url]

      mostbet_ktEi

      18 Aug 25 at 8:51 am

    35. В статье представлены ключевые моменты по актуальной теме, дополненные советами экспертов и ссылками на дополнительные ресурсы. Цель материала — дать читателю инструменты для самостоятельного развития и принятия осознанных решений.
      Секреты успеха внутри – https://f5fashion.vn/chi-tiet-hon-56-ve-hinh-nen-han-quoc-de-thuong-moi-nhat

      Michaelcar

      18 Aug 25 at 8:54 am

    36. Этот увлекательный информационный материал подарит вам массу новых знаний и ярких эмоций. Мы собрали для вас интересные факты и сведения, которые обогатят ваш опыт. Откройте для себя увлекательный мир информации и насладитесь процессом изучения!
      Узнать напрямую – http://thermalreceiptprinterrolls.co.uk/looking-for-thermal-receipt-printer-rolls

      PatrickNub

      18 Aug 25 at 8:55 am

    37. Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
      Только для своих – http://www.photodim.ru/index.php?values%5Bp%5D=single_photo&values%5Bphoto_id%5D=219&values%5Bmode%5D=date

      Russellhus

      18 Aug 25 at 8:56 am

    38. mostbetapk [url=https://www.mostbet11071.ru]mostbetapk[/url]

      mostbet_heKr

      18 Aug 25 at 8:59 am

    39. freight companies nyc package delivery new york

    40. koupit kamagra bez lékařského předpisu

      kamagra cena v kanadě

      kamagra cena

      18 Aug 25 at 9:00 am

    41. Yesterday, while I was at work, my cousin stole my apple ipad and tested to see if it can survive
      a 30 foot drop, just so she can be a youtube sensation.
      My apple ipad is now broken and she has 83 views.
      I know this is completely off topic but I had to share it with someone!

    42. Этот текст сочетает в себе элементы познавательного рассказа и аналитической подачи информации. Читатель получает доступ к уникальным данным, которые соединяют прошлое с настоящим и открывают двери в будущее.
      Почему это важно? – https://www.laserantitabac.pro/index.php/2023/04/28/loms-tire-la-sonnette-dalarme-sur-la-nocivite-des-cigarettes-electroniques

      Stephensaile

      18 Aug 25 at 9:05 am

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

    44. В этой статье вы найдете познавательную и занимательную информацию, которая поможет вам лучше понять мир вокруг. Мы собрали интересные данные, которые вдохновляют на размышления и побуждают к действиям. Открывайте новую информацию и получайте удовольствие от чтения!
      Смотрите также – https://uncamientrerealitats.cat/la-consulta-del-doctor-bertran/la-consulta-del-doctor-bertran-capitol-12-aqui-o-alla

      Millardzoofs

      18 Aug 25 at 9:07 am

    45. сколько стоит купить диплом в одессе [url=http://www.educ-ua2.ru]сколько стоит купить диплом в одессе[/url] .

      Diplomi_wpOt

      18 Aug 25 at 9:07 am

    46. Online sources for Kamagra in the United States: Compare Kamagra with branded alternatives – Kamagra oral jelly USA availability

      ElijahKic

      18 Aug 25 at 9:10 am

    47. купить старый диплом техникума [url=educ-ua3.ru]купить старый диплом техникума[/url] .

      Diplomi_ghki

      18 Aug 25 at 9:11 am

    48. купить аттестаты 11 класс 2022 года [url=https://arus-diplom24.ru/]купить аттестаты 11 класс 2022 года[/url] .

      Diplomi_hiKn

      18 Aug 25 at 9:15 am

    49. гидроизоляция цена за м2 [url=http://offthevylc.ru/polezno-znat/ceny-na-gidroizoljaciju-v-moskve-i-regionah-rossii.html/]http://offthevylc.ru/polezno-znat/ceny-na-gidroizoljaciju-v-moskve-i-regionah-rossii.html/[/url] .

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

    Leave a Reply