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 40,970 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 , , ,

    40,970 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. тканевый натяжной потолок [url=https://natyazhnye-potolki-lipeck-1.ru]тканевый натяжной потолок[/url] .

    2. nexus shop url nexus darknet shop nexus onion mirror [url=https://darkmarketsdirectory.com/ ]darkmarket url [/url]

      BrianWeX

      10 Sep 25 at 5:39 am

    3. да мэн правильно говоришь KEY фраернулся
      https://2a6255350b87fa16553b58fbe0.doorkeeper.jp/
      Кстати,что очень радует ,так это уровень общения продавца.Юмор лишним не бывает,ведь так:D?

      Harrysem

      10 Sep 25 at 5:41 am

    4. установить кондиционер в квартире цена [url=www.kondicioner-obninsk-1.ru/]установить кондиционер в квартире цена[/url] .

    5. Je trouve absolument enivrant PokerStars Casino, on dirait un ciel etoile de sensations. Les options de jeu au casino sont riches et palpitantes, proposant des slots de casino a theme audacieux. Le personnel du casino offre un accompagnement digne d’un croupier d’elite, offrant des solutions claires et immediates. Les retraits au casino sont rapides comme une donne gagnante, quand meme j’aimerais plus de promotions de casino qui eblouissent. En somme, PokerStars Casino offre une experience de casino palpitante pour les joueurs qui aiment parier avec flair au casino ! En plus la plateforme du casino brille par son style audacieux, facilite une experience de casino strategique.
      pokerstars open|

      zestysquid7zef

      10 Sep 25 at 5:42 am

    6. If you would like to obtain much from this piece of writing then you have to apply such
      techniques to your won blog.

      TikTok Downloader

      10 Sep 25 at 5:44 am

    7. Miltonbus

      10 Sep 25 at 5:44 am

    8. Наркологическая клиника «МедЛайн» предоставляет профессиональные услуги врача-нарколога с выездом на дом в Новосибирске и Новосибирской области. Мы оперативно помогаем пациентам справиться с тяжелыми состояниями при алкогольной и наркотической зависимости. Экстренный выезд наших специалистов доступен круглосуточно, а лечение проводится с применением проверенных методик и препаратов, что гарантирует безопасность и конфиденциальность каждому пациенту.
      Детальнее – [url=https://narcolog-na-dom-novosibirsk00.ru/]запой нарколог на дом в новосибирске[/url]

      Donaldsic

      10 Sep 25 at 5:45 am

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

      aviator igra_mqol

      10 Sep 25 at 5:46 am

    10. глянцевый натяжной потолок [url=http://natyazhnye-potolki-lipeck-1.ru]глянцевый натяжной потолок[/url] .

    11. Когда следует немедленно обращаться за помощью:
      Получить дополнительную информацию – [url=https://narcolog-na-dom-novokuznetsk0.ru/]нарколог на дом вывод из запоя[/url]

      MelvinZem

      10 Sep 25 at 5:50 am

    12. домашний кондиционер цена [url=http://kondicioner-obninsk-1.ru]домашний кондиционер цена[/url] .

    13. купить диплом с реестром [url=www.educ-ua14.ru]купить диплом с реестром[/url] .

      Diplomi_pckl

      10 Sep 25 at 5:52 am

    14. авиатор игра 1вин [url=https://aviator-igra-2.ru/]авиатор игра 1вин[/url] .

      aviator igra_xfol

      10 Sep 25 at 5:52 am

    15. Howdy! This post could not be written much better!
      Going through this post reminds me of my previous roommate!

      He continually kept talking about this. I will send
      this post to him. Pretty sure he will have a great read.
      Thanks for sharing!

      situs slot dana

      10 Sep 25 at 5:53 am

    16. Terrific work! That is the kind of info that are meant
      to be shared across the net. Disgrace on the seek engines for now not positioning this publish upper!
      Come on over and visit my web site . Thanks =)

    17. цена кв м натяжного потолка [url=http://natyazhnye-potolki-lipeck-1.ru]http://natyazhnye-potolki-lipeck-1.ru[/url] .

    18. plane crash money game [url=www.aviator-igra-3.ru/]www.aviator-igra-3.ru/[/url] .

      aviator igra_xkmi

      10 Sep 25 at 5:57 am

    19. It’s great that you are getting thoughts from this post as well as from our argument made
      at this time.

      Look at my website ACL tear treatment Florida

    20. Ищете источник ежедневной мотивации заботиться о себе? На «Здоровье и гармония» вы найдете простые советы по красоте, здоровью и психологии, чтобы жить легче и радостнее. Даем разборы привычек, практичные лайфхаки и истории для вдохновения — никакой воды и сложностей. Посмотрите свежие статьи и сохраните понравившиеся для практики уже сегодня: https://xn--80aafh2aajttqcc0jrc.xn--p1ai/ Начните с маленьких шагов — результаты удивят, а экспертные материалы помогут удержать курс.

      NisipScusa

      10 Sep 25 at 6:04 am

    21. Урал и Chemical продукт знают как сделать грязно
      https://www.divephotoguide.com/user/wydedkyyhd
      Магази лутший на рц не первый раз работаем с ним!) удачи и процветания!)

      Harrysem

      10 Sep 25 at 6:05 am

    22. установка кондиционера на фасад дома [url=www.kondicioner-obninsk-1.ru]установка кондиционера на фасад дома[/url] .

    23. установка натяжных потолков под ключ [url=natyazhnye-potolki-lipeck-1.ru]установка натяжных потолков под ключ[/url] .

    24. aviator игра на деньги [url=www.aviator-igra-3.ru/]aviator игра на деньги[/url] .

      aviator igra_qami

      10 Sep 25 at 6:08 am

    25. tor drug market dark market link nexus url [url=https://darknetmarketgate.com/ ]darknet market lists [/url]

      DwayneAricE

      10 Sep 25 at 6:11 am

    26. Very nice post. I just stumbled upon your weblog and wished to say that I
      have really enjoyed surfing around your blog posts.
      After all I’ll be subscribing to your feed and I hope you write
      again very soon!

      site

      10 Sep 25 at 6:12 am

    27. где купить натяжной потолок [url=https://www.natyazhnye-potolki-lipeck-1.ru]где купить натяжной потолок[/url] .

    28. IntimaCare UK [url=https://intimacareuk.com/#]buy ED pills online discreetly UK[/url] tadalafil generic alternative UK

      Albertmoone

      10 Sep 25 at 6:17 am

    29. Вот почему TorgVsem помогает продавать быстрее: публикуйте объявления бесплатно, привлекайте покупателей из всех регионов и выходите на сделку без лишней бюрократии. На площадке удобная рубрикация и умный поиск, поэтому ваши товары не потеряются среди конкурентов, а покупатели быстро их находят. Переходите на https://torgvsem.ru/ и начните размещать объявления уже сегодня — от недвижимости и транспорта до работы, услуг и товаров для дома. Публикуйте сколько нужно и обновляйте позиции за секунды — так вы экономите время и получаете больше откликов.

      Qeguqbrerm

      10 Sep 25 at 6:19 am

    30. After looking at a number of the blog articles on your web page,
      I really like your way of blogging. I saved as a favorite it to my bookmark site
      list and will be checking back in the near future. Please check out my website as
      well and tell me your opinion.

    31. You’re so interesting! I don’t suppose I’ve read anything like that before.

      So great to discover another person with unique thoughts on this
      subject matter. Really.. thank you for starting this up.

      This site is something that’s needed on the web, someone
      with a bit of originality!

    32. купить диплом в екатеринбург реестр [url=www.sumkin.ru/forum/member.php?u=53890]купить диплом в екатеринбург реестр[/url] .

      Zakazat diplom lubogo instityta!_xjkt

      10 Sep 25 at 6:21 am

    33. MediTrustUK [url=https://meditrustuk.com/#]MediTrust UK[/url] MediTrustUK

      Albertmoone

      10 Sep 25 at 6:25 am

    34. онлайн игра авиатор [url=www.aviator-igra-3.ru/]онлайн игра авиатор[/url] .

      aviator igra_yjmi

      10 Sep 25 at 6:26 am

    35. купить диплом занесением реестр [url=http://educ-ua14.ru/]купить диплом занесением реестр[/url] .

      Diplomi_fgkl

      10 Sep 25 at 6:28 am

    36. wonderful points altogether, you just won a logo new reader.
      What might you suggest in regards to your publish
      that you simply made some days ago? Any positive?

      Alto Bitrow

      10 Sep 25 at 6:29 am

    37. Заявление про кидал не требует обоснования, ибо это не заявление. Перечитайте внимательно. Считаю, что такие речи тоже стоит оставлять при себе, не прочитав толком.
      https://beteiligung.stadtlindau.de/profile/%D0%9A%D1%83%D0%BF%D0%B8%D1%82%D1%8C%20%D0%91%D0%BE%D1%88%D0%BA%D0%B8%20%D0%9C%D0%B0%D1%80%D0%B8%D1%85%D1%83%D0%B0%D0%BD%D1%83%20%D0%93%D0%B0%D1%88%D0%B8%D1%88%20%D0%93%D0%BE%D0%B6%D1%83%D0%B2-%D0%92%D0%B5%D0%BB%D1%8C%D0%BA%D0%BE%D0%BF%D0%BE%D0%BB%D1%8C%D1%81%D0%BA%D0%B8%D0%B9/
      Просьба не флудить. И уж тем более не развивать больные фантазии.

      Harrysem

      10 Sep 25 at 6:29 am

    38. I really like your blog.. very nice colors & theme.
      Did you make this website yourself or did you hire someone to do it for you?

      Plz reply as I’m looking to construct my own blog and would like
      to find out where u got this from. thanks a lot

      nfs199.xyz

      10 Sep 25 at 6:30 am

    39. Группа препаратов
      Разобраться лучше – [url=https://kapelnica-ot-zapoya-nizhniy-novgorod00.ru/]врач на дом капельница от запоя нижний новгород[/url]

      Ulyssesemuby

      10 Sep 25 at 6:30 am

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

      aviator igra_znmi

      10 Sep 25 at 6:32 am

    41. Хотите узнать, где срочно сделать медицинскую книжку в течение суток без толкучки и проблем? На сайте [url=https://medraskhodka.ru/]https://medraskhodka.ru/[/url] медкнижку оформят или продлят оперативно: с анализами и заключением терапевта — даже онлайн. Услуга актуальна для специалистов пищевой промышленности, сферы обслуживания и учреждений, где требуются медосмотры и аттестация. Оформление займёт минимум времени, а стоимость честная и понятная (от 1 600 ?, обновление с 1 300 ?). Узнайте подробности — оформление за сутки, онлайн оформление, без проблем.

      Spravkivbk

      10 Sep 25 at 6:33 am

    42. монтаж натяжных потолков в липецке [url=https://natyazhnye-potolki-lipeck-1.ru/]natyazhnye-potolki-lipeck-1.ru[/url] .

    43. Undeniably consider that which you stated. Your favorite justification seemed to be at the web the
      easiest thing to be mindful of. I say to you, I definitely get annoyed at the same time
      as other folks think about concerns that they plainly don’t
      realize about. You managed to hit the nail upon the
      top and also outlined out the whole thing with no need side effect ,
      other people can take a signal. Will probably be again to get more.
      Thank you

    44. Срочный вызов врача на дом необходим при появлении следующих симптомов:
      Детальнее – [url=https://narcolog-na-dom-nnovgorod8.ru/]нарколог на дом недорого[/url]

      KevinPow

      10 Sep 25 at 6:37 am

    45. купить диплом о высшем образовании реестр [url=educ-ua14.ru]купить диплом о высшем образовании реестр[/url] .

      Diplomi_ejkl

      10 Sep 25 at 6:37 am

    46. В этом обзорном материале представлены увлекательные детали, которые находят отражение в различных аспектах жизни. Мы исследуем непонятные и интересные моменты, позволяя читателю увидеть картину целиком. Погрузитесь в мир знаний и удивительных открытий!
      Ознакомиться с деталями – https://kmzic.com/industry

      Caseyfuh

      10 Sep 25 at 6:39 am

    47. What i don’t realize is in fact how you’re not really much more neatly-preferred than you might be right
      now. You are so intelligent. You realize therefore
      considerably when it comes to this subject, produced me personally consider it from numerous various angles.
      Its like men and women don’t seem to be interested except it is one
      thing to accomplish with Woman gaga! Your own stuffs outstanding.
      At all times deal with it up!

      Here is my web page; 청담쩜오

      청담쩜오

      10 Sep 25 at 6:40 am

    48. It’s hard to find educated people about this subject, however,
      you seem like you know what you’re talking about! Thanks

      Review my blog … Niagara Falls Tours from Toronto

    49. I like this site — clear and packed with great stuff.

      Glory casino app download

    50. darknet market list dark web marketplaces dark web market links [url=https://darknetmarketgate.com/ ]dark web marketplaces [/url]

      DwayneAricE

      10 Sep 25 at 6:43 am

    Leave a Reply