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 42,645 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 , , ,

    42,645 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. aviator money [url=https://www.aviator-igra-1.ru]https://www.aviator-igra-1.ru[/url] .

    2. [url=https://www.zaymer.ru/]АФЕРИСТ[/url]
      [url=https://zaimer.kz/]аферисты[/url]

      Ronaldfed

      11 Sep 25 at 10:28 am

    3. Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
      Все материалы собраны здесь – https://cartavillaluisa.com/logo

      HaroldHex

      11 Sep 25 at 10:28 am

    4. Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
      Более того — здесь – https://www.mayiti.net/214477-2

      HectoreXore

      11 Sep 25 at 10:28 am

    5. авиатор игра 1хбет [url=https://aviator-igra-5.ru/]авиатор игра 1хбет[/url] .

    6. Kellynom

      11 Sep 25 at 10:29 am

    7. где играть в авиатор [url=https://aviator-igra-1.ru/]где играть в авиатор[/url] .

    8. Today, I went to the beachfront with my kids. I found a sea shell and gave it
      to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to
      her ear and screamed. There was a hermit crab inside and it pinched her ear.
      She never wants to go back! LoL I know this is completely off topic but
      I had to tell someone!

      RonexisPro

      11 Sep 25 at 10:30 am

    9. Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех!
      Посмотреть подробности – https://glenwin.com/lorem-ipsum-dolor-sit-amet

      Charlesfeerm

      11 Sep 25 at 10:31 am

    10. Do you have any video of that? I’d care to find out more details.

      Magda

      11 Sep 25 at 10:32 am

    11. Мы предлагаем вам подробное руководство, основанное на проверенных источниках и реальных примерах. Каждая часть публикации направлена на то, чтобы помочь вам разобраться в сложных вопросах и применить знания на практике.
      Переходите по ссылке ниже – https://dssports.com.hk/product/swim

      MiguelDwero

      11 Sep 25 at 10:34 am

    12. EdwardTix

      11 Sep 25 at 10:35 am

    13. 1уин [url=www.1win12002.ru]www.1win12002.ru[/url]

      1win_tuKa

      11 Sep 25 at 10:35 am

    14. Thanks for ones marvelous posting! I quite enjoyed reading
      it, you might be a great author.I will make certain to bookmark your blog and will often come back in the future.
      I want to encourage yourself to continue your great work, have a nice morning!

      Norris

      11 Sep 25 at 10:35 am

    15. plane game money [url=https://aviator-igra-5.ru/]aviator-igra-5.ru[/url] .

    16. Этот информативный текст выделяется своими захватывающими аспектами, которые делают сложные темы доступными и понятными. Мы стремимся предложить читателям глубину знаний вместе с разнообразием интересных фактов. Откройте новые горизонты и развивайте свои способности познавать мир!
      Обратиться к источнику – https://www.vastavkatta.com/index.php/2022/11/26/opting-out

      Charlesfeerm

      11 Sep 25 at 10:36 am

    17. They wish to know if you can construct buy-in for your ideas and lead with out formal authority.

      My web-site; How do SPA pools enhance wellness experiences?

    18. Списался с продавцом в аське, во вторник оплатил, сказали в среду отправят. когда спросил, сказали что не отправили по тех причинам из-за СПСР, обещали в четверг. Должно было придти в течении 3х рабочих дней. Сегодня понедельник, сижу на работе, и вот мне звонят, мол вам письмо пришло, куда доставить? То есть все верно, 3 дня как и говорили! Настроение теперь на весь день поднялось)) Вечером буду делать 1к10 (ам2233), потом отпишусь как и чего!!)) В общем доволен, но пока говорю только про доставку. Позднее отпишу доволен ли я всем остальным))
      https://wirtube.de/a/barbaraadkinson5135/video-channels
      и Антошке пару точек,

      RogerCer

      11 Sep 25 at 10:36 am

    19. клиенты знают нас и нашу работу [url=http://www.soglasovanie-pereplanirovki-kvartiry17.ru]http://www.soglasovanie-pereplanirovki-kvartiry17.ru[/url] .

    20. как зарегистрироваться в мостбет [url=mostbet12001.ru]как зарегистрироваться в мостбет[/url]

      mostbet_vsOr

      11 Sep 25 at 10:45 am

    21. dark web market links nexus site official link nexus darknet market url [url=https://darkmarketsgate.com/ ]darkmarket url [/url]

      Jamespem

      11 Sep 25 at 10:46 am

    22. darknet market list darknet drug market dark web market links [url=https://darkmarketlegion.com/ ]dark websites [/url]

      Robertalima

      11 Sep 25 at 10:46 am

    23. plane game money [url=http://www.aviator-igra-5.ru]http://www.aviator-igra-5.ru[/url] .

    24. aviator играть [url=https://aviator-igra-1.ru]aviator играть[/url] .

    25. перепланировка офиса [url=www.soglasovanie-pereplanirovki-kvartiry17.ru]перепланировка офиса[/url] .

    26. авиатор игра на деньги скачать [url=http://www.aviator-igra-5.ru]авиатор игра на деньги скачать[/url] .

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

      Diplomi_rlPi

      11 Sep 25 at 10:51 am

    28. Nice post. I was checking continuously this blog and I am inspired!
      Very helpful info particularly the remaining part 🙂 I maintain such info a lot.
      I was looking for this particular info for a very lengthy time.
      Thanks and best of luck.

      Nordic Future AI

      11 Sep 25 at 10:52 am

    29. MichaelTot

      11 Sep 25 at 10:54 am

    30. I used to be recommended this website by my cousin. I’m no longer sure whether this submit is written by him as nobody else know
      such unique approximately my trouble. You are wonderful!
      Thanks!

    31. помощь в согласовании перепланировки квартиры [url=soglasovanie-pereplanirovki-kvartiry17.ru]soglasovanie-pereplanirovki-kvartiry17.ru[/url] .

    32. Everything is very open with a clear explanation of the issues.
      It was definitely informative. Your website is
      useful. Many thanks for sharing!

    33. We are a group of volunteers and starting a new scheme in our community.

      Your website offered us with valuable info to work on. You have done an impressive job
      and our whole community will be grateful to you.

      site

      11 Sep 25 at 11:00 am

    34. магазин ровнеый,за что им спасибо,если сами тупить не будете всё пройдёт ровно и без проблем.Товар тоже порадовал,довольно таки неплохо))
      https://ilm.iou.edu.gm/members/brombloodfire835/
      Запулил:$: ждёмс… отпишу…. Селер адекватный:voo-hoo:

      RogerCer

      11 Sep 25 at 11:00 am

    35. Harveyham

      11 Sep 25 at 11:01 am

    36. Very shortly this web page will be famous among all blogging
      users, due to it’s fastidious articles

      Teguh777

      11 Sep 25 at 11:01 am

    37. Attractive section of content. I just stumbled upon your weblog and in accession capital to assert that I get in fact enjoyed account your blog posts.
      Any way I’ll be subscribing to your feeds and even I achievement you access consistently rapidly.

      Stop by my web blog … stem cell therapy for hair loss thailand

    38. aviator играть на деньги [url=https://aviator-igra-1.ru/]https://aviator-igra-1.ru/[/url] .

    39. Публикация приглашает вас исследовать неизведанное — от древних тайн до современных достижений науки. Вы узнаете, как случайные находки превращались в революции, а смелые мысли — в новые эры человеческого прогресса.
      Следуйте по ссылке – https://www.bultepop.nl/2013/03/02/bultepop-2013-op-zaterdag-28-september-2013

      SamuelGef

      11 Sep 25 at 11:07 am

    40. перепланировка согласование [url=soglasovanie-pereplanirovki-kvartiry17.ru]перепланировка согласование[/url] .

    41. Этот информационный материал собраны данные, которые помогут лучше понять текущие тенденции и процессы в различных сферах жизни. Мы предоставляем четкий анализ, графики и примеры, чтобы информация была не только понятной, но и практичной для принятия решений.
      Детальнее – https://tylerthecreatormerchofficial.com/lembaga-pengelola-dana-pendidikan-mewujudkan-akses-dan-kualitas-pendidikan-yang-lebih-baik

      SamuelGef

      11 Sep 25 at 11:09 am

    42. Aw, this was an incredibly nice post. Spending some time and actual effort to generate a really
      good article… but what can I say… I hesitate a lot and don’t seem to get anything done.

    43. Эта публикация дает возможность задействовать различные источники информации и представить их в удобной форме. Читатели смогут быстро найти нужные данные и получить ответы на интересующие их вопросы. Мы стремимся к четкости и доступности материала для всех!
      Доступ к полной версии – https://lvan.in/product/faith-over-fear-with-back-design

      Carlosthive

      11 Sep 25 at 11:10 am

    44. онлайн игра авиатор [url=http://aviator-igra-1.ru/]онлайн игра авиатор[/url] .

    45. авиатор игра онлайн [url=http://aviator-igra-5.ru/]авиатор игра онлайн[/url] .

    46. Howdy very cool blog!! Guy .. Beautiful .. Superb ..

      I will bookmark your blog and take the feeds additionally?
      I’m glad to seek out so many helpful information here in the put up, we want develop extra techniques on this regard, thank you for sharing.
      . . . . .

      escorte paris

      11 Sep 25 at 11:13 am

    47. Эта публикация завернет вас в вихрь увлекательного контента, сбрасывая стереотипы и открывая двери к новым идеям. Каждый абзац станет для вас открытием, полным ярких примеров и впечатляющих достижений. Подготовьтесь быть вовлеченными и удивленными каждый раз, когда продолжите читать.
      Перейти к статье – https://smartiptv-tv.com/iptv-le-futur-de-la-tv

      DonaldVab

      11 Sep 25 at 11:14 am

    48. 1win crash [url=https://aviator-igra-1.ru/]aviator-igra-1.ru[/url] .

    49. Howdy! Do you use Twitter? I’d like to follow you if that would be
      ok. I’m absolutely enjoying your blog and look forward to new posts.

      Here is my site: Sportsbooks

      Sportsbooks

      11 Sep 25 at 11:16 am

    50. confidential delivery pharmacy UK [url=https://mediquickuk.shop/#]order medicines online discreetly[/url] trusted UK digital pharmacy

      Albertmoone

      11 Sep 25 at 11:17 am

    Leave a Reply