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 20,561 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 , , ,

    20,561 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 exploring for a little bit for any high-quality articles or blog posts
      on this sort of house . Exploring in Yahoo I eventually stumbled upon this website.
      Reading this information So i am satisfied to convey that I have an incredibly excellent uncanny feeling I found out exactly what I needed.
      I so much surely will make certain to don?t forget
      this website and provides it a look on a continuing basis.

      Xổ số dt68

      17 Aug 25 at 9:27 pm

    2. Hello there, You have done an incredible job. I’ll certainly digg it and personally suggest
      to my friends. I am sure they’ll be benefited from this web
      site.

      займ

      17 Aug 25 at 9:28 pm

    3. Please let me know if you’re looking for a author for your site.

      You have some really good posts and I believe I would be a
      good asset. If you ever want to take some of the load off,
      I’d absolutely love to write some articles for your
      blog in exchange for a link back to mine. Please
      shoot me an e-mail if interested. Cheers!

    4. Онлайн женский https://ledis.top сайт о стиле, семье, моде и здоровье. Советы экспертов, обзоры новинок, рецепты и темы для вдохновения. Пространство для современных женщин.

      Stephenwak

      17 Aug 25 at 9:32 pm

    5. Excellent pieces. Keep writing such kind of information on your site.
      Im really impressed by your blog.
      Hi there, You’ve performed a great job. I’ll
      certainly digg it and individually suggest to
      my friends. I’m sure they will be benefited from this site.

      KL99

      17 Aug 25 at 9:35 pm

    6. Миссия клиники “Перезагрузка” заключается в предоставлении высококвалифицированной помощи людям, страдающим от зависимостей. Мы стремимся создать безопасное пространство для лечения, где каждый пациент сможет получить поддержку и понимание. Наша цель — не просто избавление от зависимости, а восстановление полной жизнедеятельности человека.
      Ознакомиться с деталями – [url=https://zavisim-alko.ru/]наркологический вывод из запоя[/url]

      PeterNable

      17 Aug 25 at 9:42 pm

    7. Онлайн женский https://ledis.top сайт о стиле, семье, моде и здоровье. Советы экспертов, обзоры новинок, рецепты и темы для вдохновения. Пространство для современных женщин.

      Stephenwak

      17 Aug 25 at 9:44 pm

    8. I do not even understand how I ended up right here, however I assumed this post was
      great. I don’t understand who you might be however certainly you’re
      going to a well-known blogger for those who are not already.
      Cheers!

    9. SildenaPeak: SildenaPeak – where to buy viagra in india

      PeterTEEFS

      17 Aug 25 at 9:46 pm

    10. mostbet aplikace [url=https://mostbet11068.ru/]mostbet aplikace[/url]

      mostbet_ohpn

      17 Aug 25 at 9:46 pm

    11. most bet [url=http://mostbet11075.ru/]http://mostbet11075.ru/[/url]

      mostbet_kg_esei

      17 Aug 25 at 9:46 pm

    12. кашпо для цветов с автополивом [url=https://www.kashpo-s-avtopolivom-kazan.ru]кашпо для цветов с автополивом[/url] .

      gorshok s avtopolivom_nymr

      17 Aug 25 at 9:47 pm

    13. Imitation timber is successfully emergate.net used in construction and finishing due to its unique properties and appearance, which resembles real timber.

      Chrisprabe

      17 Aug 25 at 9:48 pm

    14. Онлайн женский https://ledis.top сайт о стиле, семье, моде и здоровье. Советы экспертов, обзоры новинок, рецепты и темы для вдохновения. Пространство для современных женщин.

      Stephenwak

      17 Aug 25 at 9:50 pm

    15. Woah! I’m really loving the template/theme
      of this website. It’s simple, yet effective. A lot of times it’s very difficult to get that “perfect balance” between usability and appearance.

      I must say that you’ve done a very good job with this.
      In addition, the blog loads very fast for me on Opera.
      Outstanding Blog!

      four wheel barrow

      17 Aug 25 at 9:55 pm

    16. Hey just wanted to give you a quick heads up. The words in your post seem to
      be running off the screen in Ie. I’m not sure if this
      is a formatting issue or something to do with
      browser compatibility but I thought I’d post to let
      you know. The style and design look great though! Hope you get the problem resolved soon. Cheers

      togel

      17 Aug 25 at 10:01 pm

    17. Hello there! This is my first visit to your blog!
      We are a collection of volunteers and starting a new initiative in a community in the
      same niche. Your blog provided us useful information to work on. You have done a outstanding job!

      8kbetedu.com

      17 Aug 25 at 10:07 pm

    18. This piece of writing will assist the internet visitors for setting up new web site or even a
      blog from start to end.

      goaqjrj.shop

      17 Aug 25 at 10:08 pm

    19. Medicament prescribing information. Brand names.
      pioglitazone generics
      Everything information about medicine. Read information now.

    20. мосбет [url=https://mostbet11071.ru/]https://mostbet11071.ru/[/url]

      mostbet_srKr

      17 Aug 25 at 10:08 pm

    21. Каждый врач клиники обладает глубокими знаниями в области фармакологии, психофармакологии и психотерапии, посещает профессиональные конференции и семинары, следит за достижениями в области лечения зависимостей. Такой подход позволяет применять наиболее эффективные и современные методы.
      Ознакомиться с деталями – [url=https://tajno-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-v-kruglosutochno-v-rostove-na-donu.ru/]наркологический вывод из запоя в ростове-на-дону[/url]

      ParisCappy

      17 Aug 25 at 10:12 pm

    22. мостбет оригинал скачать [url=mostbet11073.ru]mostbet11073.ru[/url]

      mostbet_kg_jxSl

      17 Aug 25 at 10:13 pm

    23. mostbet скачать [url=www.mostbet11068.ru]www.mostbet11068.ru[/url]

      mostbet_vipn

      17 Aug 25 at 10:14 pm

    24. Наркологическая клиника “Маяк надежды” — специализированное медицинское учреждение, предназначенное для оказания помощи лицам, страдающим от алкогольной и наркотической зависимости. Наша цель — предоставить эффективные методы лечения и поддержку, чтобы помочь пациентам преодолеть пагубное пристрастие и вернуть их к здоровой и полноценной жизни.
      Подробнее можно узнать тут – https://алко-лечение24.рф/vivod-iz-zapoya-v-stacionare-v-Sankt-Peterburge

      JasonLoorm

      17 Aug 25 at 10:15 pm

    25. Образовательные программы: Мы уверены, что знания о зависимости и её последствиях играют важную роль в реабилитации. Мы информируем пациентов о механизмах действия наркотиков и алкоголя на организм, что способствует изменению их отношения к терапии и жизни без зависимостей.
      Углубиться в тему – [url=https://srochnyj-vyvod-iz-zapoya.ru/vyvod-iz-zapoya-v-stacionare-v-kazani.ru/]вывод из запоя на дому цена в казани[/url]

      Richardfowly

      17 Aug 25 at 10:16 pm

    26. Заказать диплом о высшем образовании!
      Мы изготавливаем дипломы любых профессий по приятным ценам— [url=http://diplomoz-197.com/]diplomoz-197.com[/url]

      Lazrwhl

      17 Aug 25 at 10:19 pm

    27. It’s truly very complicated in this active life to listen news on Television, therefore I only use internet for that reason, and obtain the most up-to-date news.

      kill

      17 Aug 25 at 10:19 pm

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

      MichaelMes

      17 Aug 25 at 10:21 pm

    29. Для максимальной эффективности и безопасности «Красмед» использует комбинированные подходы:
      Получить больше информации – [url=https://medicinskij-vyvod-iz-zapoya.ru/]вывод из запоя цена в красноярске[/url]

      RobertExevy

      17 Aug 25 at 10:27 pm

    30. Купить диплом ВУЗа!
      Мы изготавливаем дипломы любой профессии по выгодным тарифам— [url=http://study-lingvo.ru/]study-lingvo.ru[/url]

      Lazridp

      17 Aug 25 at 10:28 pm

    31. аттестат 10 11 класс с реестром купить [url=http://www.arus-diplom21.ru]аттестат 10 11 класс с реестром купить[/url] .

    32. Lucknow Game: Immerse yourself in the cultural heritage of Lucknow, solving puzzles and exploring iconic landmarks to uncover hidden treasures: best games based on Lucknow culture

      HenryBlump

      17 Aug 25 at 10:32 pm

    33. Greetings I am so excited I found your web site, I really found you by accident, while I was looking on Google for something else, Anyhow I am here now and would
      just like to say many thanks for a fantastic post and a all round enjoyable blog (I also love the theme/design),
      I don’t have time to read through it all at the minute but I have book-marked it
      and also included your RSS feeds, so when I have time I will
      be back to read more, Please do keep up the superb b.

      login alternatif

      17 Aug 25 at 10:36 pm

    34. Hi there! This is my first comment here so I just wanted to give a quick shout out and tell you I genuinely enjoy reading your blog posts.
      Can you suggest any other blogs/websites/forums that deal with the same topics?

      Thanks a lot!

    35. Если требуется экстренная помощь при алкогольном кризисе — Narcology Clinic Москва предоставляет срочную помощь на дому: выезд нарколога, купирование симптомов, мониторинг состояния, без очередей и задержек.
      Исследовать вопрос подробнее – [url=https://skoraya-narkologicheskaya-pomoshch-moskva.ru/]экстренная наркологическая помощь москва[/url]

      Robertkix

      17 Aug 25 at 10:42 pm

    36. Excellent post however I was wanting to know if you could write a litte more on this
      subject? I’d be very grateful if you could elaborate
      a little bit more. Appreciate it!

      plumbers

      17 Aug 25 at 10:43 pm

    37. Посетите сайт https://cs2case.io/ и вы сможете найти кейсы КС (КС2) в огромном разнообразии, в том числе и бесплатные! Самый большой выбор кейсов кс го у нас на сайте. Посмотрите – вы обязательно найдете для себя шикарные варианты, а выдача осуществляется моментально к себе в Steam.

      MociztCof

      17 Aug 25 at 10:45 pm

    38. официальный сайт мостбет скачать [url=mostbet11074.ru]mostbet11074.ru[/url]

      mostbet_kg_kvsn

      17 Aug 25 at 10:48 pm

    39. Marvelous, what a weblog it is! This blog provides helpful facts to us, keep it up.

      Also visit my web site; تلفن امداد کرمان موتور

    40. PECITOTO menawarkan berbagai bonus menarik sebagai langkah awal menuju kemenangan maxwin dalam permaian slot gacor hari ini,
      raih kemenangan mutlak surga game slot gacor hanya
      di sini!

      peci toto

      17 Aug 25 at 10:55 pm

    41. mostbet сайт регистрация [url=https://www.mostbet11069.ru]https://www.mostbet11069.ru[/url]

      mostbet_zdSa

      17 Aug 25 at 10:56 pm

    42. delivery in new york city shipping services new york

    43. I get pleasure from, lead to I found exactly what I was having a look for. You’ve ended my four day long hunt! God Bless you man. Have a nice day. Bye
      https://arlekin-dance.kiev.ua/sklo-far-ta-garantiya-virobnika-scho-potribno-zn-2.html

      EarnestAbent

      17 Aug 25 at 11:02 pm

    44. прогнозы на хоккей с высокой проходимостью [url=https://www.luchshie-prognozy-na-khokkej13.ru]https://www.luchshie-prognozy-na-khokkej13.ru[/url] .

    45. официальный сайт мостбет [url=https://mostbet11068.ru/]https://mostbet11068.ru/[/url]

      mostbet_ispn

      17 Aug 25 at 11:02 pm

    46. I don’t know if it’s just me or if perhaps everybody else encountering issues with your
      blog. It appears as if some of the written text on your content are running off the screen. Can somebody else please comment and let me know if this is happening to them as well?
      This could be a problem with my web browser because I’ve had this happen before.
      Appreciate it

    47. Nice blog here! Also your web site loads up very fast! What host are you
      using? Can I get your affiliate link to your host?
      I wish my web site loaded up as quickly as yours lol

    48. мостбет контакты [url=https://mostbet11074.ru]https://mostbet11074.ru[/url]

      mostbet_kg_ossn

      17 Aug 25 at 11:09 pm

    49. Greate post. Keep posting such kind of info on your site.
      Im really impressed by it.
      Hi there, You have done an excellent job. I will definitely digg it and for my part
      recommend to my friends. I’m confident they’ll be benefited from this web
      site.

    50. Howdy! I know this is kinda off topic but I was
      wondering if you knew where I could locate a captcha plugin for my
      comment form? I’m using the same blog platform as yours and I’m having difficulty finding one?
      Thanks a lot!

      bet

      17 Aug 25 at 11:12 pm

    Leave a Reply