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 94,848 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 , , ,

94,848 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=frei-diplom12.ru]frei-diplom12.ru[/url] .

    Diplomi_vtPt

    17 Oct 25 at 6:31 am

  2. В этой статье вы найдете уникальные исторические пересечения с научными открытиями. Каждый абзац — это шаг к пониманию того, как наука и события прошлого создают основу для технологического будущего.
    Как это работает — подробно – https://carolarodriguezdebauer.com/sobre-la-autora-2

    Robertbum

    17 Oct 25 at 6:31 am

  3. купить диплом пту в реестре [url=http://frei-diplom2.ru]купить диплом пту в реестре[/url] .

    Diplomi_qnEa

    17 Oct 25 at 6:31 am

  4. futuregoalsnetwork – I enjoy reading, content is inspiring without being overwhelming.

    Clement Stum

    17 Oct 25 at 6:35 am

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

    Diplomi_psPl

    17 Oct 25 at 6:36 am

  6. купить диплом в биробиджане [url=https://rudik-diplom10.ru/]купить диплом в биробиджане[/url] .

    Diplomi_neSa

    17 Oct 25 at 6:37 am

  7. Pretty! This has been a really wonderful article.
    Thank you for supplying this info.

  8. купить диплом в гуково [url=www.rudik-diplom2.ru]купить диплом в гуково[/url] .

    Diplomi_bjpi

    17 Oct 25 at 6:39 am

  9. AlbertEnark

    17 Oct 25 at 6:39 am

  10. AlbertEnark

    17 Oct 25 at 6:40 am

  11. CameronJaisp

    17 Oct 25 at 6:41 am

  12. купить диплом колледжа с занесением в реестр в [url=www.frei-diplom3.ru/]купить диплом колледжа с занесением в реестр в[/url] .

    Diplomi_rxKt

    17 Oct 25 at 6:42 am

  13. В этом информативном тексте представлены захватывающие события и факты, которые заставят вас задуматься. Мы обращаем внимание на важные моменты, которые часто остаются незамеченными, и предлагаем новые перспективы на привычные вещи. Подготовьтесь к тому, чтобы быть поглощенным увлекательными рассказами!
    Посмотреть всё – https://portalonbus.com.br/2023/10/11/coldplay-e-antigo-empresario-se-processam-por-valores-milionario

    RolandToinc

    17 Oct 25 at 6:42 am

  14. купить свидетельство о заключении брака [url=www.rudik-diplom7.ru]купить свидетельство о заключении брака[/url] .

    Diplomi_elPl

    17 Oct 25 at 6:42 am

  15. Register at glory casino online and receive bonuses on your first deposit on online casino games and slots right now!

    Miguelhen

    17 Oct 25 at 6:42 am

  16. mostbet hu

    17 Oct 25 at 6:43 am

  17. This website definitely has all of the information and facts I wanted concerning this subject and didn’t know who to ask.

  18. как купить диплом техникума в уфе [url=www.frei-diplom12.ru]как купить диплом техникума в уфе[/url] .

    Diplomi_rvPt

    17 Oct 25 at 6:45 am

  19. AlbertEnark

    17 Oct 25 at 6:46 am

  20. купить диплом с занесением в реестр цена [url=http://www.frei-diplom2.ru]купить диплом с занесением в реестр цена[/url] .

    Diplomi_xlEa

    17 Oct 25 at 6:46 am

  21. В этой статье представлен занимательный и актуальный контент, который заставит вас задуматься. Мы обсуждаем насущные вопросы и проблемы, а также освещаем истории, которые вдохновляют на действия и изменения. Узнайте, что стоит за событиями нашего времени!
    Детали по клику – https://indivinejourneys.com/holi-festival-in-india

    Donaldirofe

    17 Oct 25 at 6:46 am

  22. OMT’s interactive quizzes gamify learning, mɑking mathematics habit forming fоr Singapore trainees ɑnd
    inspiring them to promote exceptional test qualities.

    Experience versatile learning anytime, ɑnywhere tһrough OMT’s tһorough
    online e-learning platform, including endless access tο video lessons and
    interactive tests.

    Сonsidered that mathematics plays ɑ critical role іn Singapore’ѕ financial development аnd development,
    purchasing specialized math tuition gears ᥙp trainees ԝith thе analytical abilities required tߋ thrive іn a competitive landscape.

    Ꮤith PSLE mathematics contributing ѕubstantially t᧐
    total ratings, tuition supplies extra resources ⅼike model responses fօr
    pattern recognition аnd algebraic thinking.

    Linking mathematics ideas tο real-world circumstances
    tһrough tuition deepens understanding, making O Level application-based concerns а lot moгe friendly.

    Individualized junior college tuition helps bridge tһe space
    frߋm О Level to A Level math, guaranteeing students adjust tօ the increased roughness and depth needed.

    Distinctively, OMT enhances tһe MOE curriculum wіth a
    personalized program featuring diagnostic assessments tο tailor
    content tߋ every trainee’ѕ staminas.

    Aesthetic aids ⅼike representations assist imagine ρroblems lor,
    improving understanding ɑnd test performance.

    Tuition reveals trainees t᧐ varied concern types, broadening tһeir preparedness for uncertain Singapore math
    exams.

    Ⅿy webpage … math tuition singapore (Vernita)

    Vernita

    17 Oct 25 at 6:48 am

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

    Diplomi_iyei

    17 Oct 25 at 6:48 am

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

    Diplomi_jjea

    17 Oct 25 at 6:52 am

  25. Сначала администратор собирает ключевые данные: возраст и примерный вес, длительность употребления, описание симптомов, хронические заболевания, аллергии и принимаемые лекарства. По этой информации врач заранее продумывает схему инфузии и прогнозирует длительность процедуры.
    Подробнее – [url=https://narkolog-na-dom-serpuhov6.ru/]narkolog-na-dom-kruglosutochno[/url]

    BlakeKib

    17 Oct 25 at 6:52 am

  26. Хотите узнать больше о природе нашей страны? Присоединяйтесь к обсуждению.

    По теме “Изучение ООПТ России: парки, заповедники, водоемы”, там просто кладезь информации.

    Вот, делюсь ссылкой:

    [url=https://alloopt.ru]https://alloopt.ru[/url]

    Жду ваших отзывов и вопросов по теме.

    fixRow

    17 Oct 25 at 6:55 am

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

    Diplomi_ynKt

    17 Oct 25 at 6:56 am

  28. Brentsek

    17 Oct 25 at 6:57 am

  29. Register at glory casino and receive bonuses on your first deposit on online casino games and slots right now!

    Miguelhen

    17 Oct 25 at 6:57 am

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

    Diplomi_uipi

    17 Oct 25 at 6:58 am

  31. Bernardgef

    17 Oct 25 at 6:59 am

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

    Diplomi_fdOi

    17 Oct 25 at 7:00 am

  33. где купить диплом техникума одних [url=http://www.frei-diplom8.ru]где купить диплом техникума одних[/url] .

    Diplomi_fusr

    17 Oct 25 at 7:01 am

  34. https://medicosur.shop/# mexico pharmacy

    Hermandug

    17 Oct 25 at 7:02 am

  35. خرید سود سوز آور – قیمت تگزاپون – خرید بنزن

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

    Diplomi_fupi

    17 Oct 25 at 7:07 am

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

    Diplomi_wqOi

    17 Oct 25 at 7:08 am

  38. AlbertEnark

    17 Oct 25 at 7:08 am

  39. купить бланк диплома [url=rudik-diplom7.ru]купить бланк диплома[/url] .

    Diplomi_jjPl

    17 Oct 25 at 7:09 am

  40. AlbertEnark

    17 Oct 25 at 7:09 am

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

    Diplomi_ydEa

    17 Oct 25 at 7:11 am

  42. можно ли купить диплом колледжа [url=frei-diplom9.ru]frei-diplom9.ru[/url] .

    Diplomi_fbea

    17 Oct 25 at 7:11 am

  43. Amazing things here. I am very happy to look your post.
    Thank you a lot and I’m taking a look forward to touch you.
    Will you please drop me a e-mail?

  44. linebet bonus

    17 Oct 25 at 7:14 am

  45. AlbertEnark

    17 Oct 25 at 7:14 am

  46. купить речной диплом [url=http://www.rudik-diplom2.ru]купить речной диплом[/url] .

    Diplomi_ippi

    17 Oct 25 at 7:14 am

  47. Hi, for all time i used to check webpage posts here early in the dawn, as
    i enjoy to learn more and more.

    Zoderovexis

    17 Oct 25 at 7:14 am

  48. AlbertEnark

    17 Oct 25 at 7:14 am

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

    Diplomi_qaOi

    17 Oct 25 at 7:15 am

  50. I love what you guys are up too. This kind of clever work and exposure!
    Keep up the good works guys I’ve added you guys to our blogroll.

    Vumon Capital

    17 Oct 25 at 7:16 am

Leave a Reply