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 120,954 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 , , ,

120,954 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. MichaelPione

    1 Nov 25 at 3:40 am

  2. discovernewhorizons – Really enjoying the topics here, they push me to explore different possibilities.

    Amelia Kimble

    1 Nov 25 at 3:40 am

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

    Diplomi_cmei

    1 Nov 25 at 3:41 am

  4. promo codes for online drugstores: SafeMedsGuide – promo codes for online drugstores

    Johnnyfuede

    1 Nov 25 at 3:41 am

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

  6. заказать онлайн трансляцию [url=www.zakazat-onlayn-translyaciyu4.ru/]заказать онлайн трансляцию[/url] .

  7. Immune Boosting Syrup

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

  8. J’ai une affection particuliere pour Sugar Casino, ca offre une experience immersive. Les titres proposes sont d’une richesse folle, avec des slots aux designs captivants. Il donne un elan excitant. Le suivi est d’une fiabilite exemplaire. Les paiements sont surs et efficaces, occasionnellement des recompenses additionnelles seraient ideales. En somme, Sugar Casino assure un fun constant. A signaler l’interface est intuitive et fluide, ce qui rend chaque session plus excitante. A noter les options variees pour les paris sportifs, cree une communaute soudee.
    DГ©couvrir|

    vibeknightan1zef

    1 Nov 25 at 3:42 am

  9. Ich bin ganz hin und weg von Cat Spins Casino, es ist ein Ort voller Energie. Die Auswahl ist so gro? wie ein Casino-Floor, mit Spielautomaten in kreativen Designs. Der Bonus fur Neukunden ist attraktiv. Der Kundensupport ist erstklassig. Gewinne kommen ohne Verzogerung, dennoch gro?ere Boni waren ein Highlight. Im Gro?en und Ganzen, Cat Spins Casino ist ein Top-Ziel fur Casino-Fans. Au?erdem die Benutzeroberflache ist flussig und intuitiv, zum Weiterspielen animiert. Ein besonders cooles Feature die dynamischen Community-Events, die Gemeinschaft starken.
    Details lernen|

    brightbyteex4zef

    1 Nov 25 at 3:42 am

  10. Hi! I could have sworn I’ve visited this web site before but after going through some of the
    posts I realized it’s new to me. Regardless, I’m certainly delighted I discovered it and I’ll be bookmarking it and checking
    back frequently!

    Dash Avita Ai

    1 Nov 25 at 3:42 am

  11. организация онлайн трансляций москва [url=zakazat-onlayn-translyaciyu4.ru]zakazat-onlayn-translyaciyu4.ru[/url] .

  12. жалюзи автоматические цена [url=elektricheskie-zhalyuzi97.ru]жалюзи автоматические цена[/url] .

  13. May I just say what a relief to uncover an individual who actually knows
    what they’re discussing over the internet. You actually realize how to bring an issue to light and make it important.
    More and more people have to check this out and understand this
    side of the story. I was surprised that you aren’t more popular because you definitely possess the gift.

  14. Наши специалисты в Ростове-на-Дону имеют многолетний опыт работы в области наркологии и готовы помочь вам на каждом этапе лечения.
    Углубиться в тему – [url=https://vyvod-iz-zapoya-rostov117.ru/]вывод из запоя на дому круглосуточно ростов-на-дону[/url]

    AngelNut

    1 Nov 25 at 3:45 am

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

  16. buy medicine online legally Ireland [url=http://irishpharmafinder.com/#]top-rated pharmacies in Ireland[/url] online pharmacy

    Hermanengam

    1 Nov 25 at 3:47 am

  17. братишки и сёстры всем мир и харе ругаться!жизнь прекрасна купить Кокаин, Мефедрон, Экстази Из 6 операторов именно оператор этого магазина отвечал быстрее и понятнее всех остальных. Я увидел здесь хорошее,грамотное отношение к клиентам, сразу видно человек знает свою работу.

    StephenZew

    1 Nov 25 at 3:49 am

  18. жалюзи для пластиковых окон с электроприводом [url=https://elektricheskie-zhalyuzi97.ru/]elektricheskie-zhalyuzi97.ru[/url] .

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

  20. https://safemedsguide.shop/# online pharmacy reviews and ratings

    Haroldovaph

    1 Nov 25 at 3:51 am

  21. автоматический карниз для штор [url=http://elektrokarniz777.ru]http://elektrokarniz777.ru[/url] .

  22. shapeyourdreams – A gentle reminder that dreams matter and we can shape them one step at a time.

    Delmy Brucz

    1 Nov 25 at 3:51 am

  23. findyourowngrowth – Such a refreshing site, always encouraging people to be their best self.

    Ted Mcgowin

    1 Nov 25 at 3:52 am

  24. Каждое направление терапии в клинике подбирается персонально. Пациент проходит пошаговую программу, начиная с диагностики и детоксикации и заканчивая психологическим сопровождением и адаптацией к жизни без зависимости.
    Получить больше информации – [url=https://narkologicheskaya-klinika-v-novokuzneczke17.ru/]запой наркологическая клиника[/url]

    SamuelQuode

    1 Nov 25 at 3:52 am

  25. купить диплом техникума в омске [url=http://frei-diplom11.ru/]купить диплом техникума в омске[/url] .

    Diplomi_jnsa

    1 Nov 25 at 3:54 am

  26. globalfashionfinds – Stylish layout and great designs, feels like a premium fashion hub.

    Myra Limbach

    1 Nov 25 at 3:54 am

  27. What we’re covering
    • Zelensky in Washington: European leaders will join Ukrainian President Volodymyr Zelensky at the White House, as he meets with US President Donald Trump this afternoon. Trump said Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
    [url=https://kra-37cc.com]kraken36[/url]
    • Potential security guarantees: At last week’s summit with Trump, Russian President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
    [url=https://at-kra34.cc]kra34 СЃСЃ[/url]
    • On the ground: Zelensky condemned Russia’s latest strikes across Ukraine, which killed at least 10 people, saying the Kremlin intends to “humiliate diplomatic efforts” and underscores “why reliable security guarantees are required.”
    kra32 at
    https://at-kra36.cc

    RichardJek

    1 Nov 25 at 3:55 am

  28. Galera, resolvi contar como foi no 4PlayBet Casino porque superou minhas expectativas. A variedade de jogos e de cair o queixo: roletas animadas, todos rodando lisos. O suporte foi bem prestativo, responderam em minutos pelo chat, algo que passa seguranca. Fiz saque em Ethereum e o dinheiro entrou em minutos, ponto fortissimo. Se tivesse que criticar, diria que mais brindes fariam falta, mas isso nao estraga a experiencia. No geral, o 4PlayBet Casino vale demais a pena. Com certeza vou continuar jogando.
    mg 4play|

    neonfalcon88zef

    1 Nov 25 at 3:55 am

  29. If some one desires expert view about blogging and site-building after that i suggest him/her to visit this weblog, Keep up the good job.

    Netto Tradeline

    1 Nov 25 at 3:55 am

  30. trendylifestylehub – Encouraging mindset pieces that feel genuine—not overly salesy or pushy.

    Evelina Johnico

    1 Nov 25 at 3:55 am

  31. Hello, I enjoy reading all of your article. I like to write a little comment to support you.

    check out

    1 Nov 25 at 3:56 am

  32. организация видеотрансляций [url=www.zakazat-onlayn-translyaciyu4.ru/]организация видеотрансляций[/url] .

  33. MichaelPione

    1 Nov 25 at 3:56 am

  34. findyourinspiration – The message is clear and encouraging, perfect pick-me-up when I need one.

    Sindy Flemming

    1 Nov 25 at 3:57 am

  35. MichaelPione

    1 Nov 25 at 3:57 am

  36. Доброго!
    Постоянный виртуальный номер для смс решает проблему с регистрацией. Купите постоянный виртуальный номер для смс и используйте его без ограничений.
    Полная информация по ссылке – [url=https://webjens.ru/chto-takoe-virtualnyy-nomer-i-kak-on-rabotaet/]купить виртуальный номер навсегда[/url]
    виртуальный номер, купить виртуальный номер для смс навсегда, постоянный виртуальный номер для смс
    виртуальных номеров, купить виртуальный номер для смс навсегда, постоянный виртуальный номер для смс
    Удачи и комфорта в общении!!

    Nomerpl

    1 Nov 25 at 3:58 am

  37. автоматические гардины для штор [url=http://elektrokarniz777.ru/]http://elektrokarniz777.ru/[/url] .

  38. discount pharmacies in Ireland

    Edmundexpon

    1 Nov 25 at 3:58 am

  39. trusted online pharmacy Ireland

    Edmundexpon

    1 Nov 25 at 3:59 am

  40. организация трансляций [url=http://zakazat-onlayn-translyaciyu4.ru]организация трансляций[/url] .

  41. электрожалюзи на заказ [url=https://elektricheskie-zhalyuzi97.ru/]elektricheskie-zhalyuzi97.ru[/url] .

  42. Тысячи клиентов постоянно пытаются найти надежный и проверенный способ для входа на маркетплейс Kraken, сталкиваясь с множеством фейковых ресурсов и устаревшей информацией. Дабы минимизировать эти риски и сохранить свои нервы, существует надежное и централизованное решение. [url=https://bhr-q.com]как зайти на кракен с айфона[/url] Перейдя по этому адресу, вы обретаете гарантированный доступ к всем возможностям платформы, в том числе систему безопасных сделок и круглосуточную техническую помощь. Этот способ дает возможность целиком исключить вероятность попадания на мошеннический сайт и гарантирует максимальную уровень конфиденциальности при совершении всех сделок.

    Othex

    1 Nov 25 at 4:04 am

  43. карниз с приводом для штор [url=http://elektrokarniz777.ru/]http://elektrokarniz777.ru/[/url] .

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

    Diplomi_bjsa

    1 Nov 25 at 4:04 am

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

    GeorgeHiB

    1 Nov 25 at 4:04 am

  46. You’ve made some good points there. I looked on the internet to find out more about the issue
    and found most individuals will go along with your
    views on this web site.

  47. globalfashionfinds – Love the trendy pieces here, everything looks so stylish and modern.

    Dillon Dozois

    1 Nov 25 at 4:05 am

  48. онлайн трансляция заказать москва [url=http://zakazat-onlayn-translyaciyu4.ru]http://zakazat-onlayn-translyaciyu4.ru[/url] .

  49. findyourfocus – Great site for mental clarity tips, everything’s short, simple, and useful.

    Jarrett Jobin

    1 Nov 25 at 4:08 am

  50. Australian pharmacy reviews: best Australian pharmacies – pharmacy online

    HaroldSHems

    1 Nov 25 at 4:09 am

Leave a Reply