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 31,822 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 , , ,

    31,822 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 am really pleased to glance at this web site posts which contains tons of
      valuable data, thanks for providing these statistics.

      derila pillow

      31 Aug 25 at 3:25 am

    2. Мы предлагаем документы университетов, расположенных в любом регионе РФ. Купить диплом о высшем образовании:
      [url=http://hot9jajob.com/employer/ukrdiplom/]аттестат 10 11 класс с реестром купить[/url]

      Diplomi_ybPn

      31 Aug 25 at 3:29 am

    3. купить диплом москва легально [url=http://octavia-club.ru/id/143121]купить диплом москва легально[/url] .

      Priobresti diplom o visshem obrazovanii!_jmkt

      31 Aug 25 at 3:34 am

    4. I am not sure where you’re getting your information, but great topic.
      I needs to spend some time learning more or understanding more.
      Thanks for excellent information I was looking for this information for my mission.

      Flow Trade AI

      31 Aug 25 at 3:35 am

    5. как купить диплом с занесением в реестр [url=www.arus-diplom31.ru]как купить диплом с занесением в реестр[/url] .

      Diplomi_lbpl

      31 Aug 25 at 3:36 am

    6. Alfredrew

      31 Aug 25 at 3:36 am

    7. It’s going to be end of mine day, but before finish I am reading this great piece of writing
      to increase my know-how.

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

      Diplomi_gsol

      31 Aug 25 at 3:41 am

    9. Заказать диплом можно используя сайт компании. [url=http://igrosoft.getbb.ru/viewtopic.php?f=11&t=4965/]igrosoft.getbb.ru/viewtopic.php?f=11&t=4965[/url]

      Sazrlen

      31 Aug 25 at 3:42 am

    10. Этап вывода из запоя
      Выяснить больше – [url=https://vyvod-iz-zapoya-shchelkovo6.ru/]vyvod-iz-zapoya-na-domu[/url]

      JarvisStove

      31 Aug 25 at 3:45 am

    11. Josephpef

      31 Aug 25 at 3:47 am

    12. [url=https://paks-tore.ru/]straightforward upkeep ideas[/url] that worked well with this guidance, making my home upkeep routine more consistent. i believe adding such suggestions to everyday routines can make upkeep far less stressful and much more rewarding. advice like this not only helps with current problems but also builds confidence for tackling new challenges in the future. This time I stayed and thought it adds value to the overall topic. — In longer discussions I usually skip, but thanks for the hands-on and plain guidance. many avoid residence fixes due to lack of confidence, but this post helps overcome that. i also found some

      Alvingek

      31 Aug 25 at 3:48 am

    13. I’ve been browsing online greater than three hours lately, but I by no means discovered any
      fascinating article like yours. It’s pretty value enough for me.
      In my opinion, if all site owners and bloggers made just right content as you did, the
      net will likely be a lot more useful than ever before.

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

      vivodzapojtulaNeT

      31 Aug 25 at 3:48 am

    15. Мы можем предложить документы ВУЗов, которые расположены в любом регионе РФ. Заказать диплом ВУЗа:
      [url=http://techfestcitp.com/read-blog/19172_kupit-attestat-11-klassov-cena.html/]купить аттестат 10 11 класс вечерней школы[/url]

      Diplomi_pjPn

      31 Aug 25 at 3:50 am

    16. где купить аттестат за 11 класс в новосибирске [url=http://arus-diplom24.ru]где купить аттестат за 11 класс в новосибирске[/url] .

      Diplomi_xmsa

      31 Aug 25 at 3:54 am

    17. RichardKap

      31 Aug 25 at 3:57 am

    18. bonaslot situs bonus terbesar Indonesia: bonaslot link resmi mudah diakses – bonaslot jackpot harian jutaan rupiah

      Ramonatowl

      31 Aug 25 at 3:58 am

    19. купить диплом ижевск с занесением в реестр [url=http://arus-diplom31.ru/]купить диплом ижевск с занесением в реестр[/url] .

      Diplomi_wvpl

      31 Aug 25 at 4:01 am

    20. 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?

      Thanks!

      login loket88

      31 Aug 25 at 4:06 am

    21. Hello, i read your blog occasionally and i own a
      similar one and i was just wondering if you get a lot of spam comments?

      If so how do you stop it, any plugin or anything you can advise?
      I get so much lately it’s driving me crazy so any
      assistance is very much appreciated.

      32WIN

      31 Aug 25 at 4:07 am

    22. Josephpef

      31 Aug 25 at 4:09 am

    23. Simply want to say your article is as astounding.

      The clarity in your post is simply great and i can assume you are an expert on this subject.
      Well with your permission let me to grab your feed to keep updated with forthcoming
      post. Thanks a million and please continue the
      enjoyable work.

      סוכן בטים

      31 Aug 25 at 4:11 am

    24. диплом купить харьков цена [url=http://www.educ-ua1.ru]диплом купить харьков цена[/url] .

      Diplomi_atei

      31 Aug 25 at 4:12 am

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

      Diplomi_pmsa

      31 Aug 25 at 4:16 am

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

      Justingof

      31 Aug 25 at 4:19 am

    27. My partner and I stumbled over here from a different web address and thought I should check things out.
      I like what I see so now i am following you. Look forward to looking into your web page for a second time.

      iridium recycling

      31 Aug 25 at 4:21 am

    28. Самостоятельно выйти из запоя — почти невозможно. В Самаре врачи клиники проводят медикаментозный вывод из запоя с круглосуточным выездом. Доверяйте профессионалам.
      Подробнее можно узнать тут – [url=https://vyvod-iz-zapoya-v-stacionare-samara16.ru/]срочный вывод из запоя[/url]

      Pablotug

      31 Aug 25 at 4:22 am

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

      Diplomi_zqpl

      31 Aug 25 at 4:23 am

    30. Your mode of explaining everything in this paragraph is actually fastidious,
      all be capable of easily know it, Thanks a lot.

      Feel free to visit my webpage dewispin

      dewispin

      31 Aug 25 at 4:27 am

    31. Amazing! Its truly amazing piece of writing, I have got much clear idea about from this article.

    32. Самостоятельно выйти из запоя — почти невозможно. В Самаре врачи клиники проводят медикаментозный вывод из запоя с круглосуточным выездом. Доверяйте профессионалам.
      Углубиться в тему – [url=https://vyvod-iz-zapoya-v-stacionare-samara15.ru/]вывод из запоя на дому недорого[/url]

      Michaelamoma

      31 Aug 25 at 4:28 am

    33. I do consider all of the ideas you have introduced for your post.
      They’re very convincing and can certainly work. Still, the
      posts are too quick for beginners. Could you please extend
      them a bit from next time? Thanks for the post.

      my homepage pink salt trick

      pink salt trick

      31 Aug 25 at 4:29 am

    34. диплом о среднем образовании купить легально [url=http://arus-diplom31.ru]http://arus-diplom31.ru[/url] .

      Diplomi_gapl

      31 Aug 25 at 4:31 am

    35. Josephpef

      31 Aug 25 at 4:31 am

    36. Детокс-капельница на дому в Подольске от клиники «Частный Медик 24» — это быстрый способ вернуть здоровье после длительных возлияний. Мы подбираем индивидуальные составы инфузий, восстанавливаем работу печени, сердца и нервной системы. Вызвать нарколога можно круглосуточно, без записи и лишних формальностей.
      Узнать больше – [url=https://kapelnica-ot-zapoya-podolsk13.ru/]капельница от запоя город. московская область[/url]

      ZacharyBep

      31 Aug 25 at 4:32 am

    37. Liv Pure seems to be getting a lot of attention for its unique approach to supporting liver health and natural fat-burning.

      I like that it focuses on cleansing and optimizing liver function, since
      that’s such a key organ for metabolism and overall wellness.
      It looks like a solid option for people who want a more natural way
      to boost energy, digestion, and weight management.

      Liv Pure

      31 Aug 25 at 4:34 am

    38. купить диплом ижевск с занесением в реестр [url=http://vidogs.forum24.ru/?1-15-0-00001609-000-0-0-1752571096]купить диплом ижевск с занесением в реестр[/url] .

      Kypit diplom o visshem obrazovanii!_mekt

      31 Aug 25 at 4:36 am

    39. История и праздники в июле История фотографии: от первых снимков до цифровых изображений Как фотография изменила представление о мире.

      Williammus

      31 Aug 25 at 4:39 am

    40. Мы готовы предложить документы институтов, расположенных на территории всей РФ. Купить диплом о высшем образовании:
      [url=http://t98223u0.beget.tech/2025/07/09/diplom-s-proverkoy-podlinnosti-cherez-fis-frdo.html/]купить аттестаты за 11 с егэ[/url]

      Diplomi_zlPn

      31 Aug 25 at 4:40 am

    41. купить аттестат за 11 класс 2000 года [url=www.arus-diplom24.ru]www.arus-diplom24.ru[/url] .

      Diplomi_hrsa

      31 Aug 25 at 4:40 am

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

      KennethGlolo

      31 Aug 25 at 4:46 am

    43. Мы можем предложить документы институтов, которые находятся на территории всей РФ. Заказать диплом любого ВУЗа:
      [url=http://blog.nataraj.ru/~/Interest/Купитьдипломсзанесениемвреестр/]как можно купить аттестат за 11 класс[/url]

      Diplomi_hzPn

      31 Aug 25 at 4:48 am

    44. Thanks for ones marvelous posting! I certainly enjoyed reading it,
      you can be a great author. I will make sure to bookmark your blog and definitely will come back
      sometime soon. I want to encourage that you continue your great posts, have a
      nice day!

      Also visit my web page :: تولیدی کاپشن

    45. Josephpef

      31 Aug 25 at 4:53 am

    46. высшее образование купить диплом с занесением в реестр [url=https://arus-diplom31.ru]высшее образование купить диплом с занесением в реестр[/url] .

      Diplomi_jcpl

      31 Aug 25 at 4:59 am

    47. Straight to the point — I appreciate that!

    48. купить аттестат 11 классов с занесением в реестр [url=www.arus-diplom24.ru]www.arus-diplom24.ru[/url] .

      Diplomi_wwsa

      31 Aug 25 at 5:02 am

    49. купить диплом с занесением в реестр украина [url=rosseia.forumex.ru/viewtopic.php?f=3&t=4261]купить диплом с занесением в реестр украина[/url] .

      Bistro zakazat diplom instityta!_lskt

      31 Aug 25 at 5:05 am

    50. купить аттестат 11 классов в тольятти [url=https://www.arus-diplom24.ru]купить аттестат 11 классов в тольятти[/url] .

      Diplomi_qqsa

      31 Aug 25 at 5:09 am

    Leave a Reply