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 8,076 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 , , ,

    8,076 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. дивитися фільми без реклами безкоштовне кіно Full HD

      uakino-817

      30 Jul 25 at 2:22 pm

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

    3. I don’t know if it’s just me or if perhaps everybody else experiencing issues with your website.
      It looks like some of the written text within your content are running off the screen. Can somebody else
      please provide feedback and let me know if this is happening
      to them too? This could be a issue with my web browser because I’ve had this happen before.
      Cheers

    4. Lucianowhess

      30 Jul 25 at 2:40 pm

    5. прогнозы на периоды в хоккее [url=https://luchshie-prognozy-na-khokkej6.ru]https://luchshie-prognozy-na-khokkej6.ru[/url] .

    6. аренда яхты сайт [url=yacht-rental-oae.com]yacht-rental-oae.com[/url] .

    7. Затяжной запой опасен для жизни. Врачи наркологической клиники в Ростове-На-Дону проводят срочный вывод из запоя — на дому или в стационаре. Анонимно, безопасно, круглосуточно.
      Слушай внимательно — тут важно – [url=https://vyvod-iz-zapoya-rostov12.ru/]vyvod-iz-zapoya-rostov12.ru[/url]

      GeraldNuh

      30 Jul 25 at 2:44 pm

    8. прогнозы на хоккей от профессионалов бесплатно [url=www.luchshie-prognozy-na-khokkej6.ru]www.luchshie-prognozy-na-khokkej6.ru[/url] .

    9. Компоненты капельницы
      Получить дополнительную информацию – [url=https://kapelnica-ot-zapoya-krasnoyarsk6.ru/]сколько стоит капельница от запоя красноярск[/url]

      Miguelodora

      30 Jul 25 at 2:44 pm

    10. Когда организм на пределе, важна срочная помощь в Ростове-На-Дону — это команда опытных наркологов, которые помогут быстро и мягко выйти из запоя без вреда для здоровья.
      Это ещё не всё… – [url=https://vyvod-iz-zapoya-rostov16.ru/]нарколог вывод из запоя[/url]

      KeithJab

      30 Jul 25 at 2:46 pm

    11. кайтинг “Одеяние Посейдона”: гидрокостюм, защита от “ледяных объятий”

      RamonLiata

      30 Jul 25 at 2:55 pm

    12. Чем дольше и интенсивнее продолжается запой, тем выше становится риск возникновения широкого спектра серьезных и потенциально смертельных осложнений, начиная от тяжелых нарушений работы сердечно-сосудистой системы и заканчивая необратимым повреждением жизненно важных внутренних органов, что требует немедленной и комплексной медицинской помощи
      Подробнее тут – [url=https://vyvod-iz-zapoya-arkhangelsk66.ru/]вывод из запоя недорого архангельск[/url]

      TamikaNounc

      30 Jul 25 at 2:56 pm

    13. прогноз на теннис на сегодня от профессионалов [url=https://www.prognoz-na-segodnya-na-sport9.ru]https://www.prognoz-na-segodnya-na-sport9.ru[/url] .

    14. аренда яхты на сутки [url=http://yacht-rental-oae.com/]http://yacht-rental-oae.com/[/url] .

    15. Наши специалисты работают круглосуточно, помогая пациентам справиться с абстинентным синдромом, восстановить здоровье и снизить риски осложнений.
      Получить больше информации – https://vyvod-iz-zapoya-novokuznetsk6.ru/vyvod-iz-zapoya-na-domu-novokuzneczk

      Eduardoflamn

      30 Jul 25 at 2:59 pm

    16. Стоимость услуг по установке капельницы определяется индивидуально и зависит от нескольких факторов. В первую очередь, цена обусловлена тяжестью состояния пациента: при более сильной интоксикации и выраженных симптомах абстинентного синдрома может потребоваться расширенная терапия. Кроме того, итоговая сумма зависит от продолжительности запоя, так как длительное употребление спиртного ведет к более серьезному накоплению токсинов, требующему дополнительных лечебных мероприятий.
      Получить больше информации – [url=https://kapelnica-ot-zapoya-nizhniy-novgorod000.ru/]капельница от запоя на дому цена в нижний новгороде[/url]

      EugeneSow

      30 Jul 25 at 3:00 pm

    17. прогнозы на периоды в хоккее [url=luchshie-prognozy-na-khokkej6.ru]luchshie-prognozy-na-khokkej6.ru[/url] .

    18. лучшие прогнозы на спорт [url=https://prognoz-na-segodnya-na-sport10.ru/]лучшие прогнозы на спорт[/url] .

    19. дивлячись фільми онлайн HD фільми українською онлайн

      ua-bay-563

      30 Jul 25 at 3:03 pm

    20. I am not sure where you’re getting your info, but good topic.

      I needs to spend some time learning much more or
      understanding more. Thanks for wonderful information I was looking for this information for my mission.

    21. Услуга “Нарколог на дом” в Уфе охватывает широкий спектр лечебных мероприятий, направленных как на устранение токсической нагрузки, так и на работу с психоэмоциональным состоянием пациента. Комплексная терапия включает в себя медикаментозную детоксикацию, корректировку обменных процессов, а также психотерапевтическую поддержку, что позволяет не только вывести пациента из состояния запоя, но и помочь ему справиться с наркотической зависимостью.
      Изучить вопрос глубже – [url=https://narcolog-na-dom-ufa000.ru/]narkolog na dom ufa[/url]

      Bruceprort

      30 Jul 25 at 3:04 pm

    22. Введение препаратов осуществляется внутривенно, что обеспечивает оперативное действие медикаментов. В состав лечебного раствора входят средства для детоксикации организма, нормализации водно-электролитного и кислотно-щелочного баланса. При необходимости врач дополнительно вводит препараты, защищающие печень, стабилизирующие работу сердца и успокаивающие нервную систему. Вся процедура проводится под строгим контролем нарколога, который следит за состоянием пациента и корректирует терапию при необходимости. По завершении процедуры врач дает пациенту и его родственникам подробные рекомендации по дальнейшему восстановлению и профилактике повторных запоев.
      Ознакомиться с деталями – [url=https://kapelnica-ot-zapoya-nizhniy-novgorod0.ru/]капельница от запоя нижний новгород[/url]

      RobertFum

      30 Jul 25 at 3:05 pm

    23. мастер класс по нейросетям [url=www.sites.google.com/view/neyroseti-obuchenie-s-nulya//]www.sites.google.com/view/neyroseti-obuchenie-s-nulya//[/url] .

      888starz_wupa

      30 Jul 25 at 3:06 pm

    24. кайтсёрфинг Кайтсёрфинг – это не только спорт, но и образ жизни. Он привлекает людей, любящих приключения, природу и свободу. Многие кайтсёрферы путешествуют по миру в поисках лучших ветровых условий и красивых спотов.

      RamonLiata

      30 Jul 25 at 3:06 pm

    25. Pretty element of content. I just stumbled upon your web site and in accession capital to claim that
      I acquire in fact enjoyed account your blog posts.
      Any way I’ll be subscribing in your feeds or even I fulfillment you get
      admission to consistently quickly.

      Feel free to visit my website :: internet voor emigranten zonder gedoe

    26. После поступления звонка нарколог оперативно выезжает по указанному адресу и прибывает в течение 30–60 минут. Врач незамедлительно приступает к оказанию помощи по четко отработанному алгоритму, состоящему из следующих этапов:
      Детальнее – https://narcolog-na-dom-voronezh00.ru/vyzov-narkologa-na-dom-voronezh

      AlbertVal

      30 Jul 25 at 3:10 pm

    27. ua-bay-754

      30 Jul 25 at 3:11 pm

    28. I was recommended this website by my cousin. I’m not sure whether this post is written by him as
      no one else know such detailed about my difficulty.

      You’re wonderful! Thanks!

      Visit my page – easiest internet for foreigners Hungary

    29. прогнозы на хоккей с подробным анализом [url=https://luchshie-prognozy-na-khokkej6.ru/]https://luchshie-prognozy-na-khokkej6.ru/[/url] .

    30. аренда яхты [url=http://www.yachts-charter-dubai.com]http://www.yachts-charter-dubai.com[/url] .

    31. PatrickNeelp

      30 Jul 25 at 3:13 pm

    32. I don’t even know how I ended up here, but I thought this post was good.
      I do not know who you are but certainly you are going to a famous blogger if you are not already 😉 Cheers!

      Trade 350 App

      30 Jul 25 at 3:17 pm

    33. Actually no matter if someone doesn’t be aware of after that its up to other visitors
      that they will help, so here it takes place.

      Feel free to visit my web site; expat internet Hungary

    34. I read tһis post completely regarding the difference of newest
      and earlier technolоgies, it’s amazing articⅼe.

      Taкe a look at my web site; opus Anglicanum

      opus Anglicanum

      30 Jul 25 at 3:18 pm

    35. Incredibly individual friendly site. Enormous info available
      on couple of clicks.
      https://nysainfo.pl

    36. кайтинг Кайт путешествия: Откройте для себя новые горизонты. Исследуйте экзотические кайт споты и наслаждайтесь красотой природы.

      RamonLiata

      30 Jul 25 at 3:23 pm

    37. cheap generic prednisone: can i order prednisone – prednisone 40 mg

      LarryBoymn

      30 Jul 25 at 3:26 pm

    38. Hi exceptional website! Does running a blog such as this require a massive amount work?

      I have absolutely no expertise in computer programming however I had been hoping to
      start my own blog in the near future. Anyhow, if
      you have any ideas or tips for new blog owners please
      share. I know this is off subject nevertheless I just had to ask.
      Kudos!

    39. дивитися фільми без реклами новинки кіно 2025 дивитися безкоштовно

      uakino-707

      30 Jul 25 at 3:32 pm

    40. Relief Meds USA: prednisone 200 mg tablets – Relief Meds USA

      LarryBoymn

      30 Jul 25 at 3:34 pm

    41. It is perfect time to make some plans for the future and it’s time to be happy.
      I have read this post and if I could I wish to suggest you few interesting things or tips.
      Maybe you can write next articles referring to this article.
      I desire to read even more things about it!

    42. фільми онлайн без реклами новинки кіно 2025 дивитися безкоштовно

      uakino-140

      30 Jul 25 at 3:45 pm

    43. Vous pouvez choisir des couleurs vives et des motifs élaborés pour un look plus décontracté, ou des couleurs
      plus sobres et des lignes épurées pour un look plus sophistiqué.

    44. Les détails comme les manches bouffantes, les encolures bateau ou les dos nus étaient également très populaires à cette époque.

    45. Без медицинской помощи запой может перерасти в тяжёлую форму алкогольной интоксикации, вызывая серьёзные сбои в работе всех систем организма.
      Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-arkhangelsk6.ru/]вывод из запоя на дому круглосуточно в архангельске[/url]

      CharlesRam

      30 Jul 25 at 3:53 pm

    46. cost of prednisone 5mg tablets: order corticosteroids without prescription – anti-inflammatory steroids online

      LarryBoymn

      30 Jul 25 at 4:07 pm

    47. В таких случаях своевременный вызов нарколога на дом позволяет быстро стабилизировать состояние больного и предотвратить тяжелые последствия.
      Углубиться в тему – [url=https://narcolog-na-dom-novosibirsk00.ru/]врач нарколог на дом в новосибирске[/url]

      DanielHah

      30 Jul 25 at 4:09 pm

    Leave a Reply