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 119,153 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 , , ,

119,153 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://rudik-diplom15.ru/]старые дипломы купить[/url] .

    Diplomi_ayPi

    31 Oct 25 at 1:15 pm

  2. автоматические карнизы [url=https://elektrokarniz777.ru/]автоматические карнизы[/url] .

  3. Ich liebe das Flair von Cat Spins Casino, es ist ein Ort, der begeistert. Die Auswahl ist einfach unschlagbar, mit packenden Live-Casino-Optionen. Er macht den Einstieg unvergesslich. Die Mitarbeiter antworten prazise. Auszahlungen sind einfach und schnell, jedoch zusatzliche Freispiele waren ein Bonus. In Summe, Cat Spins Casino ist ein Ort fur pure Unterhaltung. Au?erdem die Benutzeroberflache ist klar und flussig, einen Hauch von Eleganz hinzufugt. Besonders erwahnenswert die dynamischen Community-Events, kontinuierliche Belohnungen bieten.
    Informationen erhalten|

    nightfireus1zef

    31 Oct 25 at 1:16 pm

  4. карнизы для штор с электроприводом [url=http://elektrokarniz-kupit.ru]карнизы для штор с электроприводом[/url] .

  5. SafeMedsGuide: top rated online pharmacies – trusted online pharmacy USA

    HaroldSHems

    31 Oct 25 at 1:17 pm

  6. OMT’s emphasis on metacognition ѕhows students to delight
    іn thinking օf math, fostering love ɑnd drive for exceptional examination outcomes.

    Dive іnto seⅼf-paced math proficiency wіth OMT’ѕ 12-month e-learning courses, t᧐tal
    with practice worksheets ɑnd recorded sessions fоr extensive revision.

    Ꭺs mathematics underpins Singapore’ѕ track record fօr excellence
    in global criteria ⅼike PISA, math tuition is key to ߋpening a kid’s p᧐ssible and protecting
    scholastric advantages іn thіs core subject.

    Ϝоr PSLE achievers, tuition pгovides mock examinations and feedback, assisting
    refine answers fοr optimum marks іn both multiple-choice ɑnd open-endеd aгeas.

    Linking mathematics concepts to real-wоrld circumstances ᴡith tuition growѕ understanding,
    making Ⲟ Level application-based concerns mߋre approachable.

    Tuition іn junior college mathematics furnishes trainees ԝith statistical apρroaches ɑnd chance models impоrtant for interpreting
    data-driven inquiries іn Ꭺ Level papers.

    OMT’s customized math curriculum attracts attention Ьy bridging MOE ⅽontent with sophisticated theoretical ⅼinks, assisting pupils attach concepts аcross dіfferent math
    topics.

    Visual aids lіke layouts aid picture troubles lor, boosting understanding ɑnd examination efficiency.

    Singapore’ѕ affordable streaming аt үoung ages mаkes very earⅼy math tuition essential fⲟr safeguarding helpful
    paths t᧐ examination success.

    mу web site :: singapore primary 3 math tuition

  7. Мы стремимся к тому, чтобы каждый наш пациент в Ростове-на-Дону почувствовал заботу и внимание, получая качественную медицинскую помощь.
    Детальнее – [url=https://vyvod-iz-zapoya-rostov112.ru/]врач вывод из запоя в ростове-на-дону[/url]

    DarrenBrupe

    31 Oct 25 at 1:18 pm

  8. электрокарнизы для штор цена [url=https://elektrokarniz-kupit.ru/]электрокарнизы для штор цена[/url] .

  9. рулонные шторы с электроприводом [url=https://rulonnye-shtory-s-elektroprivodom7.ru]рулонные шторы с электроприводом[/url] .

  10. Fantastic beat ! I wish to apprentice even as you amend your web site,
    how can i subscribe for a weblog site? The account helped me a appropriate deal.
    I have been a little bit familiar of this your broadcast
    offered vibrant transparent idea

  11. электрические гардины [url=https://elektrokarniz797.ru/]электрические гардины[/url] .

  12. ролет штора [url=www.avtomaticheskie-rulonnye-shtory1.ru/]ролет штора[/url] .

  13. trusted online pharmacy Australia: cheap medicines online Australia – Aussie Meds Hub Australia

    Johnnyfuede

    31 Oct 25 at 1:21 pm

  14. compare online pharmacy prices [url=https://safemedsguide.com/#]compare online pharmacy prices[/url] trusted online pharmacy USA

    Hermanengam

    31 Oct 25 at 1:21 pm

  15. After looking at a number of the articles on your
    site, I seriously like your technique of blogging.
    I book-marked it to my bookmark webpage list and will be checking back in the near future.

    Please visit my website as well and tell me your opinion.

    dewascatter login

    31 Oct 25 at 1:21 pm

  16. потол [url=www.natyazhnye-potolki-nizhniy-novgorod-1.ru/]www.natyazhnye-potolki-nizhniy-novgorod-1.ru/[/url] .

  17. рулонные шторы на электроприводе [url=www.rulonnye-shtory-s-elektroprivodom7.ru]рулонные шторы на электроприводе[/url] .

  18. карнизы для штор купить в москве [url=http://elektrokarniz797.ru/]карнизы для штор купить в москве[/url] .

  19. рулонные шторки на окна [url=https://avtomaticheskie-rulonnye-shtory77.ru/]рулонные шторки на окна[/url] .

  20. РедМетСплав предлагает широкий ассортимент качественных изделий из ценных материалов. Не важно, какие объемы вам необходимы – от небольших закупок до обширных поставок, мы гарантируем быстрое выполнение вашего заказа.
    Каждая единица продукции подтверждена требуемыми документами, подтверждающими их соответствие стандартам. Превосходное обслуживание – наш стандарт – мы на связи, чтобы разрешать ваши вопросы по мере того как предоставлять решения под требования вашего бизнеса.
    Доверьте ваш запрос профессионалам РедМетСплав и убедитесь в широком спектре предлагаемых возможностей
    поставляемая продукция:

    Фольга магниевая 4635 Труба магниевая 4635 – это высококачественный металлический профиль, предназначенный для широкого спектра применения в строительстве и промышленности. Изготавливается из магниевых сплавов, что обеспечивает отличные механические свойства и легкость. Отличается высокой коррозийной стойкостью, что увеличивает срок службы. Идеально подходит для изготовления конструкций, требующих высокой прочности и надежности. Если вы хотите купить Труба магниевая 4635, обратите внимание на ее превосходные характеристики и конкурентоспособную цену. Этот продукт станет отличным решением для ваших проектов.

    SheilaAlemn

    31 Oct 25 at 1:24 pm

  21. электрокарнизы купить в москве [url=http://elektrokarniz-kupit.ru]электрокарнизы купить в москве[/url] .

  22. организация онлайн трансляций под ключ [url=www.zakazat-onlayn-translyaciyu5.ru]организация онлайн трансляций под ключ[/url] .

  23. Мы предлагаем гибкую систему оплаты и прозрачные цены в Ростове-на-Дону, без скрытых платежей и переплат. Обратившись в нашу клинику в Ростове-на-Дону, вы делаете первый шаг к здоровой и трезвой жизни.
    Детальнее – [url=https://vyvod-iz-zapoya-rostov111.ru/]вывод из запоя капельница на дому[/url]

    CharlesHox

    31 Oct 25 at 1:26 pm

  24. купить диплом зубного техника [url=http://rudik-diplom12.ru/]купить диплом зубного техника[/url] .

    Diplomi_wlPi

    31 Oct 25 at 1:27 pm

  25. производители рулонных штор [url=https://avtomaticheskie-rulonnye-shtory1.ru/]avtomaticheskie-rulonnye-shtory1.ru[/url] .

  26. электрокарниз двухрядный [url=elektrokarniz797.ru]elektrokarniz797.ru[/url] .

  27. online pharmacy reviews and ratings: SafeMedsGuide – cheapest pharmacies in the USA

    HaroldSHems

    31 Oct 25 at 1:29 pm

  28. электрокарниз двухрядный цена [url=elektrokarniz-kupit.ru]elektrokarniz-kupit.ru[/url] .

  29. Admiring the time and effort you put into your blog and
    detailed information you provide. It’s nice to come
    across a blog every once in a while that isn’t the same old rehashed material.
    Wonderful read! I’ve saved your site and I’m adding your RSS feeds
    to my Google account.

    dewascatter login

    31 Oct 25 at 1:31 pm

  30. электрические карнизы купить [url=https://elektrokarniz797.ru/]elektrokarniz797.ru[/url] .

  31. электрические рулонные шторы на окна [url=https://avtomaticheskie-rulonnye-shtory1.ru]электрические рулонные шторы на окна[/url] .

  32. электрокарниз купить в москве [url=elektrokarniz777.ru]электрокарниз купить в москве[/url] .

  33. top rated online pharmacies: Safe Meds Guide – promo codes for online drugstores

    Johnnyfuede

    31 Oct 25 at 1:34 pm

  34. MichaelPione

    31 Oct 25 at 1:34 pm

  35. автоматические рулонные шторы на створку [url=https://rulonnye-shtory-s-elektroprivodom7.ru]https://rulonnye-shtory-s-elektroprivodom7.ru[/url] .

  36. Hello friends, how is everything, and what you wish for to say regarding
    this piece of writing, in my view its in fact awesome designed for me.

    udintogel

    31 Oct 25 at 1:35 pm

  37. карниз электроприводом штор купить [url=https://www.elektrokarniz797.ru]https://www.elektrokarniz797.ru[/url] .

  38. электронный карниз для штор [url=www.elektrokarniz-kupit.ru]электронный карниз для штор[/url] .

  39. [url=https://www.xn—–clcbled0c6ce0b1dxce.xn--p1ai/]Шары на день рождения[/url] — это идеальный способ украсить любое торжество. Познакомьтесь с коллекцией праздничных украшений и идей, где каждая деталь имеет значение. Красочные латексные шары создают атмосферу праздника в любом месте. Мы предлагаем широкий выбор дизайнов, которые можно заказать с доставкой. Любая комбинация цветов создаются профессиональными декораторами, чтобы всё выглядело стильно и празднично. У нас можно заказать оформление для романтического сюрприза или корпоративного события. Цветы и подарки идеально сочетаются между собой. Каждый клиент для нас важен, поэтому вы получаете готовый к празднику результат. Позвоните нашему менеджеру, чтобы добавить праздник в каждый день. Гелиевые шары — это яркое дополнение к любому подарку. Украсьте свой праздник красиво, ведь каждый подарок у нас — это кусочек радости.
    https://www.xn—–clcbled0c6ce0b1dxce.xn--p1ai/

    Rolandnup

    31 Oct 25 at 1:37 pm

  40. MichaelPione

    31 Oct 25 at 1:38 pm

  41. рулонные шторы автоматические купить [url=http://www.avtomaticheskie-rulonnye-shtory1.ru]http://www.avtomaticheskie-rulonnye-shtory1.ru[/url] .

  42. Good day! I know this is kind of off topic but
    I was wondering which blog platform are you using for this site?

    I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at options for another platform.

    I would be great if you could point me in the direction of
    a good platform.

  43. электрокарниз [url=https://www.elektrokarniz-kupit.ru]электрокарниз[/url] .

  44. non-prescription medicines UK: online pharmacy – legitimate pharmacy sites UK

    Johnnyfuede

    31 Oct 25 at 1:40 pm

  45. пластиковые окна рулонные шторы с электроприводом [url=http://rulonnye-shtory-s-elektroprivodom7.ru/]http://rulonnye-shtory-s-elektroprivodom7.ru/[/url] .

  46. Whoa! This blog looks just like my old one! It’s on a entirely different
    topic but it has pretty much the same page layout and design. Superb choice of colors!

    Have a look at my blog качественный сход развал

  47. купить диплом в севастополе [url=https://rudik-diplom15.ru/]купить диплом в севастополе[/url] .

    Diplomi_soPi

    31 Oct 25 at 1:41 pm

  48. JerryChoky

    31 Oct 25 at 1:42 pm

  49. Great site, I recommend it to everyone.[url=https://rolete.md/]rolete[/url]

    RoleteMd1Nic

    31 Oct 25 at 1:43 pm

  50. электрокарниз купить в москве [url=elektrokarniz797.ru]электрокарниз купить в москве[/url] .

Leave a Reply