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 52,674 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 , , ,

    52,674 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://futbolki-s-printom.ru/

      Gregorysnisp

      19 Sep 25 at 6:52 pm

    2. cocaine in prague buy drugs in prague

      prague-drugs-848

      19 Sep 25 at 6:53 pm

    3. займы все [url=zaimy-16.ru]zaimy-16.ru[/url] .

      zaimi_okMi

      19 Sep 25 at 6:54 pm

    4. https://martinmzmwg.pointblog.net/consultoria-en-diagnostico-de-necesidades-de-capacitacion-fundamentos-explicaciГіn-84227123

      El diagnostico de necesidades de capacitacion es la piedra angular para disenar programas de formacion que impacten. En el mercado chileno, muchas organizaciones invierten millones en talleres que pasan sin impacto porque nunca hicieron un levantamiento claro de lo que sus colaboradores requieren.

      Motivos de hacer un diagnostico de necesidades de capacitacion?

      Detecta las carencias reales de competencias.

      Previene inversiones inutiles en cursos.

      Conecta la inversion con la vision corporativa.

      Aumenta la satisfaccion de los trabajadores.

      Formas para aplicar un diagnostico de necesidades de capacitacion

      Formularios internos: simples de aplicar, ideales para levantar la percepcion de los empleados.

      Entrevistas con lideres: permiten detectar expectativas de cada unidad.

      Monitoreo: ver el flujo real para reconocer oportunidades invisibles en papel.

      Mediciones de desempeno: conectan objetivos con las habilidades que se deben mejorar.

      Beneficios de un diagnostico de necesidades de capacitacion bien hecho

      Cursos que responden con las brechas reales.

      Eficiencia de dinero.

      Evolucion profesional alineado con la vision de la empresa.

      Efectos visibles en productividad.

      Errores comunes al hacer un diagnostico de necesidades de capacitacion

      Imitar modelos de otras empresas sin personalizar.

      Reducir deseos de jefaturas con brechas reales.

      Ignorar la voz de los colaboradores.

      Analizar solo una vez y no revisar.

      Un diagnostico de necesidades de capacitacion es la herramienta para construir una estrategia de desarrollo transformadora.

      JuniorShido

      19 Sep 25 at 6:55 pm

    5. диплом реестр купить [url=http://frei-diplom2.ru/]диплом реестр купить[/url] .

      Diplomi_hgEa

      19 Sep 25 at 6:57 pm

    6. Hey There. I found your blog using msn. This is an extremely well written article.
      I’ll make sure to bookmark it and return to read more of
      your useful info. Thanks for the post. I will definitely comeback.

      Stepanie

      19 Sep 25 at 6:57 pm

    7. bs2best at, bs2web at и bs2 market: глубокий анализ технологий 2025 года

      blsp at
      bs2best.at blacksprut marketplace Official

      CharlesNarry

      19 Sep 25 at 6:58 pm

    8. Davidfes

      19 Sep 25 at 6:59 pm

    9. Hello there I am so excited I found your blog, I really found you by accident, while I was looking on Askjeeve for
      something else, Regardless I am here now and would just like
      to say kudos for a tremendous post and a all round entertaining blog (I also love the theme/design), I don’t
      have time to go through it all at the moment but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read a great
      deal more, Please do keep up the great b.

      kontol pendek

      19 Sep 25 at 6:59 pm

    10. купить диплом в донском [url=rudik-diplom7.ru]rudik-diplom7.ru[/url] .

      Diplomi_vePl

      19 Sep 25 at 6:59 pm

    11. займы онлайн все [url=https://zaimy-16.ru/]https://zaimy-16.ru/[/url] .

      zaimi_qgMi

      19 Sep 25 at 6:59 pm

    12. купить диплом средне техническое [url=http://rudik-diplom11.ru]купить диплом средне техническое[/url] .

      Diplomi_sjMi

      19 Sep 25 at 7:00 pm

    13. HarryPaync

      19 Sep 25 at 7:01 pm

    14. Your mode of telling all in this paragraph is in fact good,
      all be able to effortlessly understand it, Thanks a lot.

    15. I’m really impressed with your writing skills as well as with
      the layout on your blog. Is this a paid theme or did you modify it
      yourself? Anyway keep up the excellent quality writing, it’s rare to see a great
      blog like this one these days.

    16. купить диплом менеджера [url=https://rudik-diplom1.ru/]купить диплом менеджера[/url] .

      Diplomi_czer

      19 Sep 25 at 7:04 pm

    17. микрозайм всем [url=www.zaimy-16.ru/]www.zaimy-16.ru/[/url] .

      zaimi_oiMi

      19 Sep 25 at 7:07 pm

    18. купить диплом о среднем техническом образовании [url=http://www.educ-ua7.ru]http://www.educ-ua7.ru[/url] .

      Diplomi_jyea

      19 Sep 25 at 7:08 pm

    19. MatthewRow

      19 Sep 25 at 7:10 pm

    20. все микрозаймы на карту [url=https://zaimy-16.ru]https://zaimy-16.ru[/url] .

      zaimi_ouMi

      19 Sep 25 at 7:12 pm

    21. купить диплом врача с занесением в реестр [url=https://www.frei-diplom1.ru]купить диплом врача с занесением в реестр[/url] .

      Diplomi_uuOi

      19 Sep 25 at 7:12 pm

    22. займы [url=http://zaimy-16.ru]http://zaimy-16.ru[/url] .

      zaimi_muMi

      19 Sep 25 at 7:12 pm

    23. купить диплом маляра [url=rudik-diplom8.ru]купить диплом маляра[/url] .

      Diplomi_sbMt

      19 Sep 25 at 7:15 pm

    24. купить диплом в черкесске [url=www.rudik-diplom11.ru]купить диплом в черкесске[/url] .

      Diplomi_oxMi

      19 Sep 25 at 7:15 pm

    25. Quality articles or reviews is the secret to be a focus for the users to visit the web site,
      that’s what this site is providing.

    26. Jeffreycen

      19 Sep 25 at 7:16 pm

    27. Hi there superb blog! Does running a blog such as this require a massive amount work?
      I have absolutely no expertise in coding but I
      had been hoping to start my own blog soon. Anyhow, if you have
      any recommendations or techniques for new blog
      owners please share. I know this is off topic nevertheless I simply needed to ask.

      Cheers!

    28. займы все [url=http://zaimy-16.ru]http://zaimy-16.ru[/url] .

      zaimi_gzMi

      19 Sep 25 at 7:17 pm

    29. Рекламные носители остаются одним из самых действенных инструментов рекламы. Среди них важным решением считается [url=https://format-ms.ru/catalog/roll-up/]ролл ап заказать с печатью[/url] ведь такой баннер сочетает эргономичность и заметность. Он заметно усиливает бренд на форуме, в шоуруме или на презентации товаров. Модель продумана для транспортировки, быстро монтируется и даёт мгновенный эффект на лояльность клиентов.

      Компания Format-MS уже много лет занимается изготовлением и печатью роллапов. В студии используют экологичные ткани, новейшие методы печати и добиваются ярких цветов. Клиенты доверяют нам быстрое изготовление заказов, профессиональную установку и консультации. Адрес офиса: Москва, Нагорный проезд, дом 7, стр 1, офис 2320. Для оформления заказа всегда доступен телефон +7 (499) 390-19-85. На сайте format-ms.ru можно ознакомиться с услугами и сделать заявку.

      Если вам требуется [url=https://format-ms.ru/catalog/roll-up/]roll up стоимость[/url] специалисты подберут конструкции с повышенной устойчивостью к осадкам и сырости. Плотные баннерные полотна, надёжные механизмы и стойкость красок делают такие изделия практичными даже при уличных условиях. Это решение станет важным элементом продвижения, который привлекает клиентов круглосуточно и не теряет своей выразительности.

      Formaticam

      19 Sep 25 at 7:17 pm

    30. микрозаймы все [url=https://zaimy-16.ru/]https://zaimy-16.ru/[/url] .

      zaimi_ncMi

      19 Sep 25 at 7:18 pm

    31. купить медицинский диплом медсестры [url=http://www.frei-diplom13.ru]купить медицинский диплом медсестры[/url] .

      Diplomi_dxkt

      19 Sep 25 at 7:20 pm

    32. все займы ру [url=https://www.zaimy-16.ru]https://www.zaimy-16.ru[/url] .

      zaimi_agMi

      19 Sep 25 at 7:20 pm

    33. JoshuaStism

      19 Sep 25 at 7:23 pm

    34. JerryBealo

      19 Sep 25 at 7:24 pm

    35. HarryPaync

      19 Sep 25 at 7:26 pm

    36. Заказать диплом университета мы поможем. Купить диплом техникума, колледжа в Сургуте – [url=http://diplomybox.com/kupit-diplom-tekhnikuma-kolledzha-v-surgute/]diplomybox.com/kupit-diplom-tekhnikuma-kolledzha-v-surgute[/url]

      Cazrjyi

      19 Sep 25 at 7:28 pm

    37. buy coke in prague buy cocaine prague

      prague-drugs-140

      19 Sep 25 at 7:28 pm

    38. купить диплом в славянске-на-кубани [url=http://rudik-diplom10.ru/]http://rudik-diplom10.ru/[/url] .

      Diplomi_neSa

      19 Sep 25 at 7:30 pm

    39. купить диплом сварщика [url=http://rudik-diplom7.ru/]купить диплом сварщика[/url] .

      Diplomi_liPl

      19 Sep 25 at 7:30 pm

    40. Состав подбирается персонально, без шаблонов: корректируется гидратация, электролиты, витамины, антиоксидантная и гепатопротекторная поддержка. Ниже приведены ориентировочные модели, иллюстрирующие подход к детоксу при разных клинических сценариях.
      Разобраться лучше – [url=https://vyvod-iz-zapoya-ulan-ude0.ru/]вывод из запоя на дому недорого улан-удэ[/url]

      SimonTon

      19 Sep 25 at 7:31 pm

    41. liquid prohormones for sale

      References:

      Anadrol Weight Gain (Forum.Issabel.Org)

      Forum.Issabel.Org

      19 Sep 25 at 7:33 pm

    42. I blog frequently and I genuinely thank you for your content.
      The article has truly peaked my interest. I am going to take a
      note of your website and keep checking for new information about once a week.
      I subscribed to your RSS feed too.

    43. Meaning, oriigin ɑnd history оf tһe name Evangelina

      Also visit my blog … Dorinda Merley Ѕays Sonja Morgan’s “Complete Meltdown” Wass Scary, frankiepeach.com,

      frankiepeach.com

      19 Sep 25 at 7:35 pm

    44. все займы онлайн [url=https://www.zaimy-16.ru]все займы онлайн[/url] .

      zaimi_cvMi

      19 Sep 25 at 7:35 pm

    45. Jeffreycen

      19 Sep 25 at 7:38 pm

    46. Way cool! Some very valid points! I appreciate you writing this article
      and the rest of the site is extremely good.

    47. все микрозаймы на карту [url=https://zaimy-16.ru/]https://zaimy-16.ru/[/url] .

      zaimi_oeMi

      19 Sep 25 at 7:40 pm

    48. Quality content is the key to invite the people to go to
      see the web site, that’s what this web site is providing.

      OrtevalexAi TEST

      19 Sep 25 at 7:41 pm

    49. займы онлайн все [url=https://zaimy-16.ru/]https://zaimy-16.ru/[/url] .

      zaimi_dhMi

      19 Sep 25 at 7:43 pm

    50. Hello just wanted to give you a brief heads up and let you know a few of the pictures aren’t loading correctly.

      I’m not sure why but I think its a linking issue.
      I’ve tried it in two different internet browsers and both show the same outcome.

    Leave a Reply