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 3,568 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 , , ,

    3,568 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. 1win am [url=https://1win3074.ru]https://1win3074.ru[/url]

      1win_aget

      22 Jul 25 at 8:27 pm

    2. Accutane for sale: isotretinoin online – Isotretinoin From Canada

      Leroymex

      22 Jul 25 at 8:33 pm

    3. I’m now not positive where you are getting your information, but good topic.
      I must spend some time finding out more or working
      out more. Thank you for excellent information I used to be on the lookout for this information for my mission.

      Feel free to surf to my webpage 마사지

      마사지

      22 Jul 25 at 8:34 pm

    4. Zoloft for sale: Zoloft Company – buy Zoloft online

      KelvinHoosy

      22 Jul 25 at 8:34 pm

    5. https://lexapro.pro/# buy lexapro online india

      TommyNex

      22 Jul 25 at 8:35 pm

    6. Greetings! Very helpful advice within this article! It’s
      the little changes that produce the most important
      changes. Thanks a lot for sharing!

      my blog: zborakul01

      zborakul01

      22 Jul 25 at 8:37 pm

    7. I alwayѕ useԀ to study paragraph in news papers but now as
      I am a user of internet so from now I am using net for articles,
      thanks to web.

      my site :: towel

      towel

      22 Jul 25 at 8:37 pm

    8. 888starz tunisia [url=https://888starz-english.com/]888starz tunisia[/url] .

      888starz_dzpa

      22 Jul 25 at 8:40 pm

    9. We paired a giveaway with recycled evergreen tweets, then—right in the middle of the campaign—decided to buy twitter followers and retweets for balance.

      intercom-490

      22 Jul 25 at 8:47 pm

    10. Line chart plateaued; the simplest mid-month fix we found was to experimentally buy followers twitter in 250-user increments.

      intercom-963

      22 Jul 25 at 8:48 pm

    11. сваи винтовые для фундамента цены москве и московской области купить [url=http://ostankino-svai.ru /]http://ostankino-svai.ru /[/url] .

    12. На этом этапе врач детально выясняет, как долго продолжается запой, какие симптомы наблюдаются, и имеются ли сопутствующие заболевания. Точный анализ информации помогает оперативно определить степень интоксикации и подобрать оптимальные методы детоксикации, что является ключом к предотвращению дальнейших осложнений.
      Получить дополнительную информацию – http://narcolog-na-dom-ryazan00.ru/narkolog-na-dom-kruglosutochno-ryazan/

      Williedicky

      22 Jul 25 at 8:49 pm

    13. Budget fiend? Even cheap tiktok likes work if you layer them after a share-campaign.

      buffalonews-973

      22 Jul 25 at 8:50 pm

    14. Side hustle tip: even cheap tiktok likes can trigger the algorithm if you time them after a fresh post.

      buffalonews-630

      22 Jul 25 at 8:50 pm

    15. 1win գրանցում [url=https://www.1win3074.ru]https://www.1win3074.ru[/url]

      1win_khet

      22 Jul 25 at 8:51 pm

    16. I absolutely love your website.. Excellent colors & theme.

      Did you build this amazing site yourself? Please reply back as I’m planning to create my very
      own blog and would love to find out where you got this from or just what the theme is called.
      Thanks!

      keonhacai

      22 Jul 25 at 8:51 pm

    17. подключить домашний интернет в санкт-петербурге
      domashij-internet-spb004.ru
      интернет по адресу дома

      internetelini

      22 Jul 25 at 8:52 pm

    18. Mobile play and fast payouts were my top priorities. The bonuses didn’t hurt either. I followed Reddit advice and ended up playing on the Best Online Casino.

      GamingInsider-369

      22 Jul 25 at 8:58 pm

    19. https://isotretinoinfromcanada.com/# Isotretinoin From Canada

      TheronSnipt

      22 Jul 25 at 8:59 pm

    20. Вызов врача-нарколога на дом позволяет избежать стресса госпитализации, обеспечивая комфорт и удобство как для пациента, так и для его близких.
      Получить больше информации – [url=https://narcolog-na-dom-sankt-peterburg000.ru/]врач нарколог на дом[/url]

      DouglasBus

      22 Jul 25 at 9:03 pm

    21. Капельница – это метод внутривенной инфузии, который позволяет доставить в организм пациента растворы для детоксикации и восстановления. Основные задачи процедуры включают очищение крови от токсичных веществ, нормализацию водно-солевого баланса и улучшение общего самочувствия.
      Подробнее можно узнать тут – https://kapelnica-ot-zapoya-krasnoyarsk55.ru/kapelnicza-ot-zapoya-v-stacionare-krasnoyarsk/

      StephenWaw

      22 Jul 25 at 9:07 pm

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

      FrankAbove

      22 Jul 25 at 9:08 pm

    23. завинчивающиеся сваи [url=https://ostankino-svai.ru /]ostankino-svai.ru [/url] .

    24. app for mental health support [url=www.mental-health25.com]www.mental-health25.com[/url] .

    25. Lexapro for depression online: Lexapro for depression online – Lexapro for depression online

      Leroymex

      22 Jul 25 at 9:13 pm

    26. 888starz cameroun apk [url=http://888starz-english.com/]888starz cameroun apk[/url] .

      888starz_njpa

      22 Jul 25 at 9:14 pm

    27. Medicament information sheet. Cautions.
      where to buy generic lansoprazole without a prescription
      Best news about medicine. Read here.

    28. Метод лечения
      Получить дополнительную информацию – https://narkologicheskaya-klinika-krasnodar00.ru/narkologicheskaya-klinika-anonimno-krasnodar

      AubreySkise

      22 Jul 25 at 9:25 pm

    29. In a pinch—buy followers x; covers drip speed vs. burst drops.

      intercom-803

      22 Jul 25 at 9:29 pm

    30. Hey very interesting blog!

      vn88

      22 Jul 25 at 9:30 pm

    31. Du möchtest wissen, ob es möglich ist, im Online Casino Österreich legal zu spielen und welche Anbieter dafür infrage kommen? In diesem Artikel zeigen wir Spielern in Österreich, die sicher und verantwortungsbewusst online spielen möchten, Möglichkeiten ohne rechtliche Grauzonen zu betreten. Lies weiter, um die besten Tipps und rechtlichen Hintergründe zu entdecken: Online Casino Österreich

      MarvinLob

      22 Jul 25 at 9:30 pm

    32. mental health app [url=www.mental-health25.com/]mental health app[/url] .

    33. Solid read if you plan to buy tiktok likes and views but worry about retention dips.

      buffalonews-953

      22 Jul 25 at 9:33 pm

    34. Startup founders sometimes hesitate, but hitting launch with a modest plan to buy 1 000 twitter followers helped our beta thread gain traction.

      intercom-226

      22 Jul 25 at 9:37 pm

    35. NormansuB

      22 Jul 25 at 9:43 pm

    36. В зависимости от тяжести состояния и наличия осложнений клиника «Спасение Плюс» предлагает:
      Ознакомиться с деталями – http://

      Tracyhoott

      22 Jul 25 at 9:45 pm

    37. Your growth stack shouldn’t lean only on ads; the report shows why selective buy tiktok views can validate hooks faster.

      buffalonews-594

      22 Jul 25 at 9:45 pm

    38. After trying five shady apps, I gave Reddit a shot. That’s when I found a real legit online casino that paid me on time.

      GamingInsider-759

      22 Jul 25 at 9:45 pm

    39. cheap Accutane [url=https://isotretinoinfromcanada.com/#]Isotretinoin From Canada[/url] isotretinoin online

      BurtonCix

      22 Jul 25 at 9:47 pm

    40. Incredible points. Sound arguments. Keep up the great effort.

    41. При обращении на горячую линию пациент может получить бесплатную телефонную консультацию. Врач уточняет состояние, собирает предварительный анамнез и согласовывает время визита.
      Ознакомиться с деталями – https://narkologicheskaya-klinika-rostov13.ru/psikhiatricheskaya-narkologicheskaya-klinika-v-rostove/

      FrankVon

      22 Jul 25 at 9:53 pm

    42. «СочиМед» предлагает комплексный подход: диагностика, детоксикация, терапия сопутствующих состояний, психологическая и социальная поддержка. В стационаре доступны:
      Ознакомиться с деталями – https://narkologicheskaya-klinika-sochi00.ru/narkologicheskaya-klinika-vyvod-iz-zapoya-sochi

      TimothyBoche

      22 Jul 25 at 9:54 pm

    43. Дополнительную информацию о методах социальной реабилитации можно найти в публикациях Фонда борьбы с наркоманией и алкоголизмом.
      Подробнее тут – [url=https://narkologicheskaya-klinika-krasnodar0.ru/]наркологические клиники алкоголизм[/url]

      Brettskend

      22 Jul 25 at 9:54 pm

    44. What’s Going down i’m new to this, I stumbled upon this
      I have discovered It absolutely helpful and it has
      aided me out loads. I hope to contribute & assist other customers
      like its helped me. Good job.

      My web site … 마사지

      마사지

      22 Jul 25 at 9:54 pm

    45. After reading Reddit’s recommendations, I found a legit platform. I’ve had zero issues since switching to one of the trusted gambling sites.

      GamingInsider-828

      22 Jul 25 at 9:55 pm

    46. Metric tune-up: buy x twitter followers; support chat replied in 5 min.

      intercom-738

      22 Jul 25 at 9:56 pm

    47. Надёжный заказ авто заказать авто из владивостока. Машины с минимальным пробегом, отличным состоянием и по выгодной цене. Полное сопровождение: от подбора до постановки на учёт.

      zakazat-avto-800

      22 Jul 25 at 10:02 pm

    48. Важным этапом лечения является детоксикация организма, которая направлена на выведение токсинов и нормализацию работы внутренних органов. Применение препаратов, таких как антабус и налтрексон, доказало свою эффективность в профилактике срывов, что подтверждают клинические исследования на Клиническом портале.
      Разобраться лучше – [url=https://lechenie-alkogolizma-sochi00.ru/]центр лечения алкоголизма краснодарский край[/url]

      Jeffreybok

      22 Jul 25 at 10:02 pm

    49. Need proof? The “before & after” when newbies learn how to buy tiktok views is in section two.

      buffalonews-981

      22 Jul 25 at 10:03 pm

    50. Accutane for sale: USA-safe Accutane sourcing – isotretinoin online

      Leroymex

      22 Jul 25 at 10:03 pm

    Leave a Reply