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 22,452 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 , , ,

    22,452 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. I’ve been browsing on-line greater than 3 hours lately, but
      I by no means discovered any interesting article like yours.
      It is beautiful price sufficient for me. In my opinion, if all web owners and bloggers
      made just right content as you did, the web might be
      much more useful than ever before.

    2. Today, while I was at work, my sister stole my iPad and tested to see if it can survive a 30 foot drop, just so she can be a youtube sensation. My apple ipad
      is now broken and she has 83 views. I know this is entirely off topic but I had to share it with
      someone!

    3. Нужна срочная помощь? Центр «Alco.Rehab» в Москве предлагает круглосуточный вывод из запоя с выездом на дом.
      Узнать больше – [url=https://nazalnyj.ru/]вывод из запоя на дому круглосуточно город москва[/url]

      AlbertThade

      20 Aug 25 at 6:21 am

    4. SildenaPeak: SildenaPeak – how to purchase viagra pills

      ElijahKic

      20 Aug 25 at 6:22 am

    5. Hello there, just became aware of your blog through Google,
      and found that it’s really informative. I’m gonna watch out for brussels.
      I’ll be grateful if you continue this in future.
      A lot of people will be benefited from your writing.
      Cheers!

    6. Jimmybub

      20 Aug 25 at 6:24 am

    7. Сначала администратор собирает ключевые данные: возраст и примерный вес, длительность употребления, описание симптомов, хронические заболевания, аллергии и принимаемые лекарства. По этой информации врач заранее продумывает схему инфузии и прогнозирует длительность процедуры.
      Изучить вопрос глубже – [url=https://narkolog-na-dom-serpuhov6.ru/]vyzvat-narkologa-na-dom[/url]

      HowardDiz

      20 Aug 25 at 6:31 am

    8. When I initially commented I clicked the “Notify me when new comments are added” checkbox and now each time
      a comment is added I get several e-mails with the same comment.
      Is there any way you can remove people from that service? Thank you!

    9. Этап процедуры
      Разобраться лучше – [url=https://vyvod-iz-zapoya-odincovo6.ru/]skoraya-pomoshch-vyvoda-iz-zapoya[/url]

      RicardoJar

      20 Aug 25 at 6:35 am

    10. плинко кз [url=https://plinko3001.ru]https://plinko3001.ru[/url]

      plinko_kz_iiEr

      20 Aug 25 at 6:36 am

    11. I’m gone to convey my little brother, that he should also pay a visit this webpage on regular basis to obtain updated from
      most recent reports.

      My webpage Future-focused career coaching services online

    12. Hi my family member! I wish to say that this post is amazing, nice written and come with almost all vital infos.
      I would like to peer extra posts like this .

    13. Hi there, You have done an incredible job. I will certainly digg
      it and personally recommend to my friends. I am confident they’ll be benefited from this
      website.

    14. купить аттестат за 11 класс калининграде [url=http://www.arus-diplom21.ru]купить аттестат за 11 класс калининграде[/url] .

      Diplomi_dpPr

      20 Aug 25 at 6:40 am

    15. как потратить бонусы казино 1win [url=https://1win22097.ru]https://1win22097.ru[/url]

      1win_zkpr

      20 Aug 25 at 6:41 am

    16. Thanks for sharing your thoughts on winter solar lights.
      Regards

    17. Jimmybub

      20 Aug 25 at 6:44 am

    18. It’s an awesome paragraph in favor of all the internet viewers; they will get benefit from it I am sure.

    19. купить подлинный аттестат за 11 класс [url=http://arus-diplom22.ru/]купить подлинный аттестат за 11 класс[/url] .

      Diplomi_miKt

      20 Aug 25 at 6:47 am

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

      Walterskips

      20 Aug 25 at 6:49 am

    21. This post will help the internet people for setting up new weblog or even a weblog from start to end.

    22. горшки для цветов с автополивом купить [url=http://www.kashpo-s-avtopolivom-spb.ru]горшки для цветов с автополивом купить[/url] .

      gorshok s avtopolivom_swsr

      20 Aug 25 at 6:50 am

    23. melbet promo code [url=https://melbet3006.com/]https://melbet3006.com/[/url]

      melbet_bkpa

      20 Aug 25 at 6:50 am

    24. viagra 50mg generic: SildenaPeak – SildenaPeak

      PeterTEEFS

      20 Aug 25 at 6:54 am

    25. Thank you a lot for sharing this with all folks you actually know what you are speaking about!
      Bookmarked. Please also talk over with my website =).
      We could have a hyperlink change contract between us

      my site … avซับไทย

    26. I was wondering if you ever considered changing the structure of your website?
      Its very well written; I love what youve got to say. But maybe you could a little more in the way of
      content so people could connect with it better. Youve got an awful lot of text for only
      having 1 or 2 images. Maybe you could space it
      out better?

    27. Капельницы от запоя в Красноярске: экстренная помощь на дому Проблема алкогольной зависимости требует квалифицированного подхода. При запойном состоянии наблюдаются тяжелые симптомы‚ такие как тремор‚ повышенная потливость‚ беспокойство и‚ порой‚ галлюцинации. В таких ситуациях необходима помощь нарколога для получения грамотной медицинской помощи. Преимущества домашней терапии заключаются в том‚ что пациент находится в знакомой среде‚ что помогает быстрее восстановиться после запоя. Не менее важно уделить внимание профилактике рецидивов‚ чтобы предотвратить повторные запои. Обращаясь за помощью к специалистам‚ вы получите не только капельницы для детоксикации‚ но и комплексное лечение алкоголизма‚ направленное на полное восстановление.

    28. Samuelloofe

      20 Aug 25 at 6:59 am

    29. В Санкт-Петербурге решение есть — наркологическая клиника. Здесь помогают людям выйти из запоя без страха и осуждения. Всё анонимно, грамотно и с заботой о каждом пациенте.
      Выяснить больше – [url=https://azithromycinum.ru/]помощь вывод из запоя[/url]

      Terryunock

      20 Aug 25 at 7:00 am

    30. Jimmybub

      20 Aug 25 at 7:05 am

    31. плинко кз [url=plinko3001.ru]плинко кз[/url]

      plinko_kz_cbEr

      20 Aug 25 at 7:09 am

    32. Hey There. I found your blog using msn. This is a very well written article.

      I’ll be sure to bookmark it and come back to read more of your useful info.
      Thanks for the post. I will certainly comeback.

      flm bokep xxx

      20 Aug 25 at 7:16 am

    33. Клиника «АнтиАлко» предлагает экстренную медицинскую помощь на дому в Новосибирске и Новосибирской области для тех, кто столкнулся с запоем. Если вы или ваш близкий оказались в состоянии длительной алкогольной интоксикации, наши специалисты готовы оперативно приехать к вам, провести комплексную детоксикацию и купировать симптомы абстинентного синдрома. Мы гарантируем высокий уровень безопасности, полную анонимность и индивидуальный подход к каждому пациенту.
      Подробнее – [url=https://vyvod-iz-zapoya-novosibirsk00.ru/]vyvod-iz-zapoya-na-domu novosibirsk[/url]

      DavidBrard

      20 Aug 25 at 7:17 am

    34. провайдеры интернета по адресу
      krasnoyarsk-domashnij-internet005.ru
      провайдеры по адресу

      inernetadreselini

      20 Aug 25 at 7:18 am

    35. Great web site. A lot of helpful information here.
      I’m sending it to several pals ans also sharing in delicious.
      And of course, thanks on your effort!

    36. Great article! This is the type of info that are supposed to be
      shared around the internet. Disgrace on the seek engines
      for now not positioning this put up higher! Come on over
      and discuss with my web site . Thank you =)

    37. software de gestión de multipropiedad

      PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog

    38. Jimmybub

      20 Aug 25 at 7:26 am

    39. купить аттестат за 11 классов в орле [url=http://arus-diplom21.ru]купить аттестат за 11 классов в орле[/url] .

      Diplomi_ujPr

      20 Aug 25 at 7:27 am

    40. Затем организуется выезд специалиста — нарколог приезжает на дом или, по желанию, принимает пациента в стационаре. После осмотра и измерения жизненно важных показателей врач разрабатывает индивидуальную схему терапии. Главная цель — мягкая и безопасная детоксикация, восстановление работы органов и снятие психических и физических симптомов.
      Получить дополнительные сведения – http://vyvod-iz-zapoya-shchelkovo6.ru/vyvod-iz-zapoya-nedorogo-v-shchelkovo/https://vyvod-iz-zapoya-shchelkovo6.ru

      BrucePal

      20 Aug 25 at 7:32 am

    41. viagra europe over the counter: cheap viagra 100mg canada – can you buy viagra

      RichardTit

      20 Aug 25 at 7:33 am

    42. RichardPep

      20 Aug 25 at 7:33 am

    43. купить аттестат 11 классов за 1996 год [url=www.arus-diplom22.ru/]купить аттестат 11 классов за 1996 год[/url] .

      Diplomi_rqKt

      20 Aug 25 at 7:33 am

    44. plinko slot [url=http://plinko-kz2.ru]plinko slot[/url]

      plinko_kz_wfer

      20 Aug 25 at 7:39 am

    45. Do you mind if I quote a couple of your articles as long as I
      provide credit and sources back to your blog? My blog
      is in the exact same area of interest as yours and
      my users would genuinely benefit from a lot of the information you present here.
      Please let me know if this ok with you. Regards!

    46. Terrific work! That is the type of info that are meant
      to be shared around the web. Shame on the search engines for no longer positioning this submit upper!
      Come on over and visit my website . Thank you =)

      https://poolstoday.net/

      Bookmakers News

      20 Aug 25 at 7:39 am

    47. Samuelloofe

      20 Aug 25 at 7:43 am

    48. Jimmybub

      20 Aug 25 at 7:46 am

    49. We are a group of volunteers and opening a new
      scheme in our community. Your site offered us with valuable
      information to work on. You have done an impressive task and our entire neighborhood will probably be
      thankful to you.

    Leave a Reply