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 30,621 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 , , ,

    30,621 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. Plongez dans l’ambiance rétro et laissez-vous inspirer
      par notre sélection de robes de mariage des années 60, pour un style unique et inoubliable
      lors de votre jour J.

    2. Very great post. I just stumbled upon your blog and wanted to say that
      I have truly loved browsing your weblog posts.

      In any case I’ll be subscribing for your feed and
      I hope you write again soon!

    3. We are a group of volunteers and opening a new scheme
      in our community. Your web site offered us with valuable information to work
      on. You have done an impressive job and our entire community will be grateful to you.

      Shari

      30 Aug 25 at 4:37 am

    4. Мы готовы предложить документы институтов, расположенных в любом регионе России. Купить диплом любого университета:
      [url=http://inteam.maxbb.ru/viewtopic.php?f=1&t=2122/]купить аттестаты за 11 с егэ[/url]

      Diplomi_pwPn

      30 Aug 25 at 4:43 am

    5. DanielVeiff

      30 Aug 25 at 4:44 am

    6. Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!

      remontkomand-316

      30 Aug 25 at 4:46 am

    7. Описание
      Ознакомиться с деталями – http://vyvod-iz-zapoya-sochi7.ru/vyvod-iz-zapoya-anonimno-v-sochi/

      JimmyOmify

      30 Aug 25 at 4:47 am

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

      Diplomi_gnOt

      30 Aug 25 at 4:47 am

    9. The Memory Wave seems like a fascinating approach to supporting brain health and mental clarity.
      I like how it’s designed to help with focus, memory retention,
      and overall cognitive performance. It feels like a helpful option for anyone wanting a natural boost in mental sharpness and long-term brain support.

      The Memory Wave

      30 Aug 25 at 4:55 am

    10. Это мода с акцентом на женственность и повседневность.

      Трикотаж обеспечивает комфорт на протяжении всего дня.

      Полный образ легко собрать в одном месте.

      Сайт ориентирован на комфорт и простоту покупки.

      25 Union делает стиль доступным всегда.

    11. DanielVeiff

      30 Aug 25 at 5:06 am

    12. This paragraph will help the internet users for
      setting up new web site or even a weblog from start to end.

      Zorovixia

      30 Aug 25 at 5:09 am

    13. Hi friends, its wonderful post regarding educationand fully explained, keep it up all the
      time.

    14. Currently it looks like Expression Engine is the best blogging platform out there right now.

      (from what I’ve read) Is that what you are using on your blog?

    15. Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!

      remontkomand-393

      30 Aug 25 at 5:13 am

    16. SlimMe Detox Tea ist eine tolle Unterstützung für alle,
      die ihrem Körper etwas Gutes tun möchten. Die Mischung aus natürlichen Kräutern schmeckt nicht nur angenehm,
      sondern kann auch dabei helfen, das Wohlbefinden zu steigern und ein leichteres Körpergefühl zu
      fördern. Besonders praktisch finde ich, dass er sich einfach in den Alltag integrieren lässt – perfekt
      für alle, die auf natürliche Weise mehr Balance suchen.

      SlimMe Detox Tea

      30 Aug 25 at 5:14 am

    17. Phalo Boost Supplement sounds really promising for anyone looking to naturally increase
      energy and support overall vitality. I like that it focuses on enhancing stamina and daily performance without relying on harsh stimulants.

      Definitely looks like a solid option for long-term wellness support.

    18. Мы можем предложить документы институтов, которые находятся в любом регионе России. Приобрести диплом любого университета:
      [url=http://mbableu.com/employer/ukrdiplom/]купить аттестат в челябинске за 11 класс[/url]

      Diplomi_dbPn

      30 Aug 25 at 5:27 am

    19. DanielVeiff

      30 Aug 25 at 5:29 am

    20. Creative
      If some one needs to be updated with newest technologies afterward he
      must be pay a visit this web site and be up to date all the
      time.

      Emotions

      30 Aug 25 at 5:31 am

    21. Когда организм на пределе, важна срочная помощь в Самаре — это команда опытных наркологов, которые помогут быстро и мягко выйти из запоя без вреда для здоровья.
      Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara14.ru/]вывод из запоя капельница на дому[/url]

      Michaelplert

      30 Aug 25 at 5:33 am

    22. Cabinnet IQ
      8305 Statе Hwy 71 #110, Austin,
      TX 78735, United Stаtes
      254-275-5536
      Minimalist

      Minimalist

      30 Aug 25 at 5:33 am

    23. mostbet qeydiyyat aviator [url=http://mostbet4138.ru/]mostbet qeydiyyat aviator[/url]

      mostbet_blot

      30 Aug 25 at 5:34 am

    24. This post is actually a pleasant one it helps new net viewers, who are wishing for
      blogging.

      Hitomi Tanaka

      30 Aug 25 at 5:39 am

    25. Выбор банного комплекса влияет на комфорт и
      пользу процедуры.

      на сайте

      30 Aug 25 at 5:41 am

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

      Justingof

      30 Aug 25 at 5:42 am

    27. billiards ball

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

      billiards ball

      30 Aug 25 at 5:43 am

    28. Check for drug interactions when you bupropion pronunciation and save the money for other purchases. wellbutrin tinnitus

      ErcsFlulk

      30 Aug 25 at 5:45 am

    29. купить диплом с проводкой моих [url=www.arus-diplom31.ru]купить диплом с проводкой моих[/url] .

      Diplomi_gbpl

      30 Aug 25 at 5:45 am

    30. Igenics seems like a great option for supporting eye health and
      protecting vision as we age. I like that it’s
      made with natural ingredients aimed at reducing oxidative stress and keeping the eyes sharp.
      Definitely feels like something worth trying if
      you’re looking to maintain clear, healthy vision for the
      long run.

      iGenics

      30 Aug 25 at 5:48 am

    31. read this post from Calmlife

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

    32. I am actually delighted to read this webpage posts which consists of plenty of valuable information, thanks for providing such statistics.

      sandibet

      30 Aug 25 at 5:50 am

    33. WW88 chính thống 2025, thể thao phong phú, giấy
      phép hợp pháp, tỷ lệ thưởng cao.

      Trang chủ WW88

      30 Aug 25 at 5:50 am

    34. Hey! This post couldn’t be written any better! Reading through
      this post reminds me of my good old room mate! He always kept talking about this.
      I will forward this write-up to him. Pretty sure he will have a
      good read. Thanks for sharing!

    35. DanielVeiff

      30 Aug 25 at 5:51 am

    36. Instead of paying high prices locally for stromectol 3 mg price after comparing multiple offers stromectol ivermectin buy

      NtcqFlulk

      30 Aug 25 at 5:52 am

    37. Мы готовы предложить документы учебных заведений, расположенных в любом регионе РФ. Купить диплом университета:
      [url=http://skrivunder.net/492274/]аттестат за 11 классов купить в красноярске[/url]

      Diplomi_waPn

      30 Aug 25 at 5:52 am

    38. Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!

      remontkomand-747

      30 Aug 25 at 5:59 am

    39. Nice respond in return of this question with real arguments and describing
      the whole thing regarding that.

      eSEOspace

      30 Aug 25 at 6:03 am

    40. I have been surfing online more than 2 hours today, yet I never found any interesting article like yours.
      It is pretty worth enough for me. Personally, if all web owners and bloggers made good content as you did,
      the net will be a lot more useful than ever before.

      YOURmeds24

      30 Aug 25 at 6:05 am

    41. купить диплом внесенный в реестр [url=http://arus-diplom31.ru]купить диплом внесенный в реестр[/url] .

      Diplomi_cxpl

      30 Aug 25 at 6:08 am

    42. DanielVeiff

      30 Aug 25 at 6:13 am

    43. где можно купить аттестаты 11 класса в онеге [url=https://arus-diplom23.ru]где можно купить аттестаты 11 класса в онеге[/url] .

      Diplomi_bfol

      30 Aug 25 at 6:16 am

    44. аттестат 11 класса купить [url=https://arus-diplom24.ru/]аттестат 11 класса купить[/url] .

      Diplomi_tpsa

      30 Aug 25 at 6:20 am

    45. We’re a group of volunteers and opening a new scheme in our community.
      Your website offered us with valuable information to work on. You’ve done a
      formidable job and our whole community will be grateful to
      you.

    46. Мы готовы предложить документы университетов, расположенных на территории всей Российской Федерации. Заказать диплом о высшем образовании:
      [url=http://buch.christophgerber.ch/index.php?title=Benutzer:LenoreKeartland/]купить аттестаты за 11 класс 2021 год[/url]

      Diplomi_zkPn

      30 Aug 25 at 6:22 am

    47. Планируете ремонт https://remontkomand.kz в Алматы и боитесь скрытых платежей? Опубликовали полный и честный прайс-лист! Узнайте точные расценки на все виды работ — от демонтажа до чистовой отделки. Посчитайте стоимость своего ремонта заранее и убедитесь в нашей прозрачности. Никаких «сюрпризов» в итоговой смете!

      remontkomand-919

      30 Aug 25 at 6:25 am

    48. youtubeijb

      30 Aug 25 at 6:28 am

    49. Georgebon

      30 Aug 25 at 6:32 am

    Leave a Reply