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 45,577 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 , , ,

    45,577 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. First off I would like to say awesome blog! I had a quick question which I’d
      like to ask if you do not mind. I was interested to know
      how you center yourself and clear your mind before writing.
      I have had difficulty clearing my thoughts in getting
      my ideas out. I truly do enjoy writing but it just
      seems like the first 10 to 15 minutes tend to be lost just trying to figure out how to begin. Any recommendations or tips?
      Thanks!

      pinbahis

      17 Jul 25 at 3:13 pm

    2. Клиника “Обновление” также активно занимается просветительской деятельностью. Мы организуем семинары и лекции, которые помогают обществу лучше понять проблемы зависимостей, их последствия и пути решения. Повышение осведомленности является важным шагом на пути к улучшению ситуации в этой области.
      Узнать больше – [url=https://kapelnica-ot-zapoya-irkutsk.ru/]вызвать капельницу от запоя на дому[/url]

      AustinIdela

      17 Jul 25 at 3:14 pm

    3. ГҐpen apotek [url=http://tryggmed.com/#]TryggMed[/url] kondomer apotek

      ScottFup

      17 Jul 25 at 3:15 pm

    4. диплом купить в саратове [url=http://arus-diplom8.ru/]диплом купить в саратове[/url] .

    5. домашний интернет
      domashij-internet-nizhnij-novgorod006.ru
      провайдер по адресу

      internetelini

      17 Jul 25 at 3:17 pm

    6. Запой – это очень опасно, нужно срочно вызывать нарколога на дом в Волгограде! Помощь нарколога на дому – это оперативно, удобно и анонимно. Мы быстро очистим ваш организм от алкоголя и восстановим его работу. Наши специалисты готовы приехать к вам в любое время суток. Лечение комплексное: лекарства, индивидуальный подход и психологическая помощь. Первый шаг – детоксикация, мы поможем вам избавиться от алкогольной интоксикации.
      Подробнее тут – https://vyvod-iz-zapoya-volgograd00.ru/vyvod-iz-zapoya-na-domu-volgograd

      Mathewdub

      17 Jul 25 at 3:18 pm

    7. DavidFoogs

      17 Jul 25 at 3:18 pm

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

      ManuelLut

      17 Jul 25 at 3:30 pm

    9. Вызов врача-нарколога на дом актуален в ситуациях, когда пациенту требуется срочная медицинская помощь, но его состояние не позволяет самостоятельно обратиться в клинику. Основными причинами вызова нарколога на дом являются:
      Подробнее – [url=https://narcolog-na-dom-sankt-peterburg00.ru/]нарколог на дом недорого в санкт-петербурге[/url]

      DerickDen

      17 Jul 25 at 3:34 pm

    10. диплом бакалавра купить [url=www.arus-diplom8.ru]диплом бакалавра купить[/url] .

    11. Эти данные являются основой для составления индивидуального плана лечения, позволяющего оперативно скорректировать терапевтические меры.
      Выяснить больше – https://narcolog-na-dom-ryazan00.ru/vyzov-narkologa-na-dom-ryazan

      Kennethseavy

      17 Jul 25 at 3:40 pm

    12. Психолог онлайн даст совет в сложный момент. Детский психолог онлайн разберется с детской тревогой.
      яндекс психолог онлайн

      Ernestpoive

      17 Jul 25 at 3:41 pm

    13. What i don’t understood is actually how you are no longer really a lot more well-liked than you might be right now.

      You are very intelligent. You understand thus considerably in relation to this matter, produced me in my opinion consider it from a lot of numerous angles.
      Its like women and men aren’t interested until it is one thing
      to do with Woman gaga! Your own stuffs great. Always handle it
      up!

    14. Использование автоматизированных систем дозирования обеспечивает точное введение медикаментов, что минимизирует риск передозировки и побочных эффектов. Постоянный мониторинг жизненно важных показателей позволяет врачу в режиме реального времени корректировать схему лечения, обеспечивая максимальную эффективность и безопасность процедуры.
      Получить дополнительную информацию – https://narcolog-na-dom-ryazan0.ru/

      StephenRof

      17 Jul 25 at 3:58 pm

    15. It’s appropriate time to make a few plans
      for the long run and it’s time to be happy.
      I’ve learn this put up and if I may just I desire to suggest you some
      attention-grabbing issues or tips. Maybe you could write subsequent articles relating to this article.
      I desire to read even more things approximately it!

      free webcam girls

      17 Jul 25 at 4:03 pm

    16. доставка воды технической цена [url=https://www.dostavka-tehnicheskoi-vodi.ru]https://www.dostavka-tehnicheskoi-vodi.ru[/url] .

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

      Diplomi_erPr

      17 Jul 25 at 4:05 pm

    18. I think that is among the so much vital info for me.
      And i am glad studying your article. However should remark on some general issues, The website
      style is wonderful, the articles is actually
      nice : D. Excellent process, cheers

    19. оренбург купить аттестат [url=www.arus-diplom8.ru/]оренбург купить аттестат[/url] .

    20. Neat blog! Is your theme custom made or did you download
      it from somewhere? A design like yours with a few simple tweeks would
      really make my blog shine. Please let me know where you got your theme.
      Bless you

    21. Психолог онлайн поможет наладить жизнь. Детский психолог онлайн поддержит в переходных этапах.
      семейные психологи онлайн

      Ernestpoive

      17 Jul 25 at 4:16 pm

    22. Игроки часто ищут vavada com online, и не зря — именно такие платформы обеспечивают честную игру и качественный сервис. Если вас интересует vavada com online, рекомендуем заглянуть сюда: vavada com online. Вы узнаете о бонусах, мобильной версии, рабочих зеркалах и многом другом. Проверяйте сами — vavada com online может приятно удивить!

      Matthewrhica

      17 Jul 25 at 4:18 pm

    23. Первым этапом лечения является медицинская детоксикация, которая направлена на удаление токсинов из организма и стабилизацию физического состояния пациента. Мы используем современные методики, которые помогают минимизировать симптомы абстиненции, такие как головная боль, тошнота и слабость, обеспечивая комфортное пребывание в клинике.
      Получить больше информации – [url=https://kapelnica-ot-zapoya-irkutsk2.ru/]вызвать капельницу от запоя на дому в иркутске[/url]

      Richardincog

      17 Jul 25 at 4:19 pm

    24. купить аттестат за 11 классов спб [url=arus-diplom22.ru]купить аттестат за 11 классов спб[/url] .

      Diplomi_wwKt

      17 Jul 25 at 4:20 pm

    25. apotek faktura: tea tree oil apotek – apotek fГ¶rkylning

      Altonjah

      17 Jul 25 at 4:23 pm

    26. вывод из запоя круглосуточно челябинск
      [url=https://vivod-iz-zapoya-chelyabinsk001.ru]https://vivod-iz-zapoya-chelyabinsk001.ru[/url]
      экстренный вывод из запоя

    27. ставки и прогнозы на спорт [url=http://prognozy-na-sport-2.ru]http://prognozy-na-sport-2.ru[/url] .

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

    29. I have read some just right stuff here. Certainly worth bookmarking
      for revisiting. I surprise how much effort you set to make this type of fantastic informative web site.

    30. хоккей ставки [url=http://www.prognozy-na-khokkej-segodnya.ru]http://www.prognozy-na-khokkej-segodnya.ru[/url] .

    31. прогнозы ставки [url=http://www.stavki-na-sport-prognozy2.ru]прогнозы ставки[/url] .

    32. hormonspiral pris apotek: Snabb Apoteket – hiv test hemma apotek

      Altonjah

      17 Jul 25 at 4:31 pm

    33. промо мелбет [url=http://melbet3005.com/]http://melbet3005.com/[/url]

      melbet_xrPl

      17 Jul 25 at 4:32 pm

    34. koronatest apotek [url=https://tryggmed.shop/#]magnesium apotek[/url] jerntilskudd apotek

      ScottFup

      17 Jul 25 at 4:34 pm

    35. http://tryggmed.com/# koronavaksine på apotek

      MichaelDeeli

      17 Jul 25 at 4:36 pm

    36. дешевый интернет нижний новгород
      domashij-internet-nizhnij-novgorod006.ru
      провайдеры в нижнем новгороде по адресу проверить

      internetelini

      17 Jul 25 at 4:37 pm

    37. скачать melbet на телефон [url=www.melbet3005.com]www.melbet3005.com[/url]

      melbet_mqPl

      17 Jul 25 at 4:40 pm

    38. RichardPep

      17 Jul 25 at 4:42 pm

    39. Психолог онлайн решит ваши внутренние конфликты. Детский психолог онлайн разберется с детскими страхами.
      детский психолог калуга хороший отзывы

      Ernestpoive

      17 Jul 25 at 4:43 pm

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

      MariaGer

      17 Jul 25 at 4:44 pm

    41. Vodka Casino https://vodkasloty.com — русскоязычная платформа с множеством слотов от NetEnt, Pragmatic Play, Evolution Gaming. Лицензия Кюрасао гарантирует безопасность. Темный дизайн с красными акцентами, простое управление и мобильная версия.

      LewisGuatt

      17 Jul 25 at 4:47 pm

    42. Vodka Casino https://vodkasloty.com — российская платформа с множеством слотов от NetEnt, Pragmatic Play, Evolution Gaming. Сертификат Кюрасао гарантирует безопасность. Стильный интерфейс с красными акцентами, простое управление и мобильное приложение.

      ShaneDrync

      17 Jul 25 at 4:49 pm

    43. Заказать диплом под заказ вы можете используя официальный портал компании. [url=http://nationalcarerecruitment.com.au/employer/diploms-ukraine/]nationalcarerecruitment.com.au/employer/diploms-ukraine[/url]

      Sazrzia

      17 Jul 25 at 4:52 pm

    44. прогнозы на ставки на спорт [url=https://prognozy-na-sport-2.ru/]https://prognozy-na-sport-2.ru/[/url] .

    45. apote: TryggMed – virus apotek

      Altonjah

      17 Jul 25 at 5:01 pm

    46. прогноз на сегодня футбол [url=www.prognozy-na-futbol-1.ru/]www.prognozy-na-futbol-1.ru/[/url] .

    47. Thanks for any other informative blog. Where else may just I get that
      type of info written in such a perfect means?

      I’ve a venture that I’m just now running on, and I have
      been on the glance out for such info.

    48. Купить диплом на заказ в столице возможно используя официальный сайт компании. [url=http://sslive.org/read-blog/4684_magistr-kupit-diplom.html/]sslive.org/read-blog/4684_magistr-kupit-diplom.html[/url]

      Sazrchg

      17 Jul 25 at 5:17 pm

    49. «ВоронежДоктор» сочетает в себе профессионализм, современное оборудование и заботу о приватности пациента. Ключевые преимущества:
      Получить дополнительные сведения – [url=https://kapelnica-ot-zapoya-voronezh2.ru/]капельница от запоя цена воронеж.[/url]

      Jamesgains

      17 Jul 25 at 5:21 pm

    Leave a Reply