Wanneer casino weer open South Holland

  1. Roulette Wiel: Wed liefde om u een mooie gemakkelijke manier om een overwinning te garanderen wanneer u klikt om te draaien.
  2. 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.
  3. 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 89,260 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 , , ,

89,260 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. купить диплом в новокузнецке [url=https://www.rudik-diplom8.ru]купить диплом в новокузнецке[/url] .

    Diplomi_lyMt

    14 Oct 25 at 9:36 am

  2. купить диплом с занесением в реестр в архангельске [url=https://frei-diplom5.ru/]купить диплом с занесением в реестр в архангельске[/url] .

    Diplomi_ygPa

    14 Oct 25 at 9:37 am

  3. переустройство и перепланировка нежилого помещения [url=https://pereplanirovka-nezhilogo-pomeshcheniya10.ru]https://pereplanirovka-nezhilogo-pomeshcheniya10.ru[/url] .

  4. Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
    Не упусти важное! – https://garagedoorsconcept.org/2020/10/29/garage-doors-concept-part-three

    Rogercot

    14 Oct 25 at 9:39 am

  5. аренда экскаватора в московской области [url=https://arenda-ekskavatora-pogruzchika-cena-2.ru]аренда экскаватора в московской области[/url] .

  6. мини экскаватор в аренду [url=www.arenda-mini-ekskavatora-v-moskve-2.ru]мини экскаватор в аренду[/url] .

  7. купить диплом с реестром спб [url=www.frei-diplom4.ru/]купить диплом с реестром спб[/url] .

    Diplomi_aaOl

    14 Oct 25 at 9:40 am

  8. купить диплом занесенный реестр [url=https://frei-diplom6.ru]купить диплом занесенный реестр[/url] .

    Diplomi_ysOl

    14 Oct 25 at 9:41 am

  9. I think that everything published made a great deal of
    sense. But, what about this? suppose you were to write a awesome title?
    I ain’t saying your content is not good., but suppose you added a post title to maybe grab people’s attention? I
    mean PHP hook, building hooks in your application –
    Sjoerd Maessen blog at Sjoerd Maessen blog is kinda vanilla.
    You might peek at Yahoo’s home page and see how they write article headlines to grab viewers to click.

    You might add a related video or a related picture or two to grab people excited about everything’ve got to say.
    In my opinion, it might make your posts a little livelier.

    discuss

    14 Oct 25 at 9:42 am

  10. жалюзи автоматические цена [url=https://www.zhalyuzi-s-elektroprivodom77.ru]жалюзи автоматические цена[/url] .

  11. рулонные шторы на окна недорого [url=http://rulonnaya-shtora-s-elektroprivodom.ru/]рулонные шторы на окна недорого[/url] .

  12. wettseiten einzahlungsbonus

    Feel free to surf to my blog post; lizenz sportwetten deutschland

  13. как купить проведенный диплом отзывы [url=www.frei-diplom5.ru/]www.frei-diplom5.ru/[/url] .

    Diplomi_htPa

    14 Oct 25 at 9:43 am

  14. купить диплом с занесением в реестр [url=rudik-diplom8.ru]купить диплом с занесением в реестр[/url] .

    Diplomi_exMt

    14 Oct 25 at 9:44 am

  15. В этой статье-обзоре мы соберем актуальную информацию и интересные факты, которые освещают важные темы. Читатели смогут ознакомиться с различными мнениями и подходами, что позволит им расширить кругозор и глубже понять обсуждаемые вопросы.
    Где можно узнать подробнее? – https://digi-coin-diary.com/bybit-office

    Josephsom

    14 Oct 25 at 9:44 am

  16. купить диплом в калуге [url=http://www.rudik-diplom11.ru]купить диплом в калуге[/url] .

    Diplomi_reMi

    14 Oct 25 at 9:45 am

  17. куплю диплом кандидата наук [url=www.rudik-diplom13.ru]куплю диплом кандидата наук[/url] .

    Diplomi_rhon

    14 Oct 25 at 9:46 am

  18. купить диплом с занесением в реестр в украине [url=https://frei-diplom4.ru/]https://frei-diplom4.ru/[/url] .

    Diplomi_ktOl

    14 Oct 25 at 9:47 am

  19. Этот информативный текст отличается привлекательным содержанием и актуальными данными. Мы предлагаем читателям взглянуть на привычные вещи под новым углом, предоставляя интересный и доступный материал. Получите удовольствие от чтения и расширьте кругозор!
    Подробная информация доступна по запросу – https://convoy200.info/1

    RobertDax

    14 Oct 25 at 9:47 am

  20. Definitely believe that which you said. Your favorite justification appeared to be on the net the easiest thing to be aware of.

    I say to you, I certainly get annoyed while people consider worries that they just
    don’t know about. You managed to hit the nail
    upon the top and defined out the whole thing without having
    side effect , people can take a signal. Will likely
    be back to get more. Thanks

  21. автоматические рулонные шторы на створку [url=http://rulonnaya-shtora-s-elektroprivodom.ru]http://rulonnaya-shtora-s-elektroprivodom.ru[/url] .

  22. купить диплом в междуреченске [url=https://rudik-diplom8.ru/]https://rudik-diplom8.ru/[/url] .

    Diplomi_ruMt

    14 Oct 25 at 9:50 am

  23. В этой публикации мы предлагаем подробные объяснения по актуальным вопросам, чтобы помочь читателям глубже понять их. Четкость и структурированность материала сделают его удобным для усвоения и применения в повседневной жизни.
    Узнайте всю правду – https://farmersmedia.org/2020/07/20/agra-releases-africa-covid-19-situation-reports

    Rickyslack

    14 Oct 25 at 9:50 am

  24. купить диплом педагога [url=https://rudik-diplom1.ru/]купить диплом педагога[/url] .

    Diplomi_kxer

    14 Oct 25 at 9:51 am

  25. whoah this blog is excellent i like studying your posts.
    Stay up the great work! You know, many individuals are
    looking around for this information, you can aid them greatly.

    point blank

    14 Oct 25 at 9:51 am

  26. какие бывают рулонные шторы [url=http://www.rulonnaya-shtora-s-elektroprivodom.ru]http://www.rulonnaya-shtora-s-elektroprivodom.ru[/url] .

  27. купить диплом с регистрацией [url=http://frei-diplom4.ru/]купить диплом с регистрацией[/url] .

    Diplomi_xiOl

    14 Oct 25 at 9:51 am

  28. Этот обзор дает возможность взглянуть на историю и науку под новым углом. Мы представляем редкие факты, неожиданные связи и значимые события, которые помогут вам глубже понять развитие цивилизации и роль человека в ней.
    Что скрывают от вас? – https://about.weatherplus.vn/nguoi-dan-vung-bao-tri-an-tong-dai-khuyen-nong-sau-bao-so-9-usagi

    PhilipOxync

    14 Oct 25 at 9:52 am

  29. Публикация предлагает читателю не просто информацию, а инструменты для анализа и саморазвития. Мы стимулируем критическое мышление, предлагая различные точки зрения и призывая к самостоятельному поиску решений.
    Детали по клику – https://strelatrade.com/getting-in-touch-with-ukrainian-women-online

    Davidaxord

    14 Oct 25 at 9:52 am

  30. купить диплом в ростове-на-дону [url=www.rudik-diplom11.ru]купить диплом в ростове-на-дону[/url] .

    Diplomi_qzMi

    14 Oct 25 at 9:53 am

  31. купить диплом в ноябрьске [url=https://www.rudik-diplom5.ru]купить диплом в ноябрьске[/url] .

    Diplomi_gema

    14 Oct 25 at 9:53 am

  32. электрокарниз двухрядный цена [url=http://elektrokarnizy797.ru]http://elektrokarnizy797.ru[/url] .

  33. I really like your blog.. very nice colors
    & theme. Did you create this website yourself or did you hire someone to do it
    for you? Plz reply as I’m looking to create my own blog and would like
    to find out where u got this from. kudos

  34. Hello there! I simply want to offer you a huge thumbs up for the excellent
    info you have got right here on this post. I will be returning to your blog for more soon.

  35. аренда экскаватора в московской области [url=http://www.arenda-ekskavatora-pogruzchika-cena-2.ru]аренда экскаватора в московской области[/url] .

  36. купить диплом в кемерово [url=http://www.rudik-diplom11.ru]купить диплом в кемерово[/url] .

    Diplomi_daMi

    14 Oct 25 at 9:58 am

  37. These are genuinely enormous ideas in regarding blogging.
    You have touched some nice factors here. Any way keep up wrinting.

    NethertoxAGENT

    14 Oct 25 at 9:58 am

  38. купить диплом в перми [url=https://www.rudik-diplom5.ru]купить диплом в перми[/url] .

    Diplomi_epma

    14 Oct 25 at 9:59 am

  39. Этот обзор предлагает структурированное изложение информации по актуальным вопросам. Материал подан так, чтобы даже новичок мог быстро освоиться в теме и начать использовать полученные знания в практике.
    Узнать из первых рук – https://kizuna1046.com/business/gallery12

    MatthewRig

    14 Oct 25 at 9:59 am

  40. жалюзи на окна с электроприводом [url=www.zhalyuzi-s-elektroprivodom77.ru]жалюзи на окна с электроприводом[/url] .

  41. It is not my first time to visit this web site,
    i am browsing this website dailly and take pleasant
    facts from here everyday.

    BET88

    14 Oct 25 at 10:00 am

  42. перепланировка офиса согласование [url=www.pereplanirovka-nezhilogo-pomeshcheniya10.ru]перепланировка офиса согласование[/url] .

  43. где купить диплом с реестром [url=www.frei-diplom6.ru]где купить диплом с реестром[/url] .

    Diplomi_aaOl

    14 Oct 25 at 10:01 am

  44. электрокарнизы для штор купить в москве [url=elektrokarnizy797.ru]elektrokarnizy797.ru[/url] .

  45. жалюзи автоматические цена [url=http://zhalyuzi-s-elektroprivodom77.ru]жалюзи автоматические цена[/url] .

  46. рулонная штора автоматическая [url=https://rulonnaya-shtora-s-elektroprivodom.ru/]https://rulonnaya-shtora-s-elektroprivodom.ru/[/url] .

  47. перевозка мини экскаваторов [url=arenda-mini-ekskavatora-v-moskve-2.ru]arenda-mini-ekskavatora-v-moskve-2.ru[/url] .

  48. купить диплом о высшем образовании с занесением в реестр в кемерово [url=http://frei-diplom5.ru/]купить диплом о высшем образовании с занесением в реестр в кемерово[/url] .

    Diplomi_ytPa

    14 Oct 25 at 10:05 am

  49. купить диплом косметолога [url=http://rudik-diplom13.ru/]купить диплом косметолога[/url] .

    Diplomi_ihon

    14 Oct 25 at 10:07 am

  50. где купить диплом о среднем образование [url=https://www.rudik-diplom4.ru]где купить диплом о среднем образование[/url] .

    Diplomi_jvOr

    14 Oct 25 at 10:07 am

Leave a Reply