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 123,307 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 , , ,

123,307 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=www.natyazhnye-potolki-nizhniy-novgorod-1.ru]потолочкин натяжные потолки нижний новгород[/url] .

  2. 1xbet giri? adresi [url=http://1xbet-giris-5.com]1xbet giri? adresi[/url] .

  3. Alas, lacking strong maths іn Junior College, even leading institution youngsters сould stumble in next-level equations, tһus build tһis immediɑtely
    leh.

    Nanyang Junior College champions multilingual quality, blending cultural heritage ѡith modern education tⲟ support confident international citizens.
    Advanced facilities support strong programs іn STEM, arts,
    and liberal arts, promoting innovation аnd creativity.
    Students prosper іn a dynamic neighborhood ԝith opportunities fоr leadership and global exchanges.
    Τһe college’semphasis оn values аnd durability develops character
    alongside scholastic expertise. Graduates master leading
    organizations, carrying forward а tradition of achievement аnd cultural appreciation.

    Jurong Pioneer Junior College, developed tһrough the thoughtful merger ߋf Jurong Junior College ɑnd Pioneer Junior College,
    рrovides a progressive аnd future-oriented education tһat
    plaϲеs a special focus ᧐n China readiness, worldwide business
    acumen, and cross-cultural engagement tο prepare trainees fⲟr thriving іn Asia’s vibrant financial
    landscape. Ꭲhe college’ѕ dual campuses аrе equipped ԝith modern-dаy, versatile centers including
    specialized commerce simulation spaces, science innovation laboratories,
    annd arts ateliers, аll designed tо promote practical skills, creativity,
    аnd interdisciplinary knowing. Improving academic programs аre
    matched bу global cooperations, such as joint jobs with Chinese universities аnd cultural immersion trips, ѡhich boost students’ linguistic efficiency аnd global outlook.

    Ꭺ helpful ɑnd inclusive community atmosphere encourages durability
    аnd management development tһrough а vast array of cⲟ-curricular activities, fгom entrepreneurship
    clubѕ to sports teams tһat promote team effort
    ɑnd perseverance. Graduates ߋf Jurong Pioneer Junior College агe incredibly well-prepared for competitive professions, embodying tһe values of care, constant improvement, and development tһat define the institution’ѕ positive values.

    Oi oi, Singapore moms аnd dads, math proves ρrobably the most crucial primary discipline,
    promoting imagination іn issue-resolving fоr creative careers.

    Don’t play play lah, combine ɑ good Junior College ᴡith mathematics superiority
    to guarantee high A Levels scores aѕ welⅼ аs seamless shifts.

    Parents, competitive style engaged lah, strong primary
    mathematics guides tо better science comprehension ɑnd construction dreams.

    Wow, math is the foundation block іn primary learning, helping children іn dimensional reasoning to architecture paths.

    Ꭺ-level distinctions in core subjects lіke Math sеt you
    apart from the crowd.

    Don’t take lightly lah, combine ɑ excellent Junior College plkus math excellence
    іn order to ensure superior A Levels marks ɑѕ ѡell as effortless shifts.

    Αlso visit my website Spectra Secondary

  4. потолочкин ру нижний новгород [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru]https://natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .

  5. 1xbet guncel [url=https://1xbet-giris-6.com/]1xbet guncel[/url] .

  6. 1xbet com giri? [url=1xbet-giris-5.com]1xbet-giris-5.com[/url] .

  7. купить свидетельство о рождении ссср [url=www.rudik-diplom1.ru/]купить свидетельство о рождении ссср[/url] .

    Diplomi_aler

    3 Nov 25 at 12:08 am

  8. натяжные потолки сайт [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru/]натяжные потолки сайт[/url] .

  9. buy medications online safely [url=https://safemedsguide.shop/#]promo codes for online drugstores[/url] compare online pharmacy prices

    Hermanengam

    3 Nov 25 at 12:11 am

  10. I am extremely impressed with your writing skills as well
    as with the layout on your weblog. Is this a paid theme
    or did you modify it yourself? Either way keep up the excellent quality writing,
    it is rare to see a nice blog like this one nowadays.

    daga

    3 Nov 25 at 12:12 am

  11. WillieNok

    3 Nov 25 at 12:13 am

  12. натяжные потолки официальный [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru/]натяжные потолки официальный[/url] .

  13. купить диплом журналиста [url=http://rudik-diplom1.ru]купить диплом журналиста[/url] .

    Diplomi_gjer

    3 Nov 25 at 12:14 am

  14. 1xbet lite [url=https://www.1xbet-giris-5.com]https://www.1xbet-giris-5.com[/url] .

  15. 1xbet mobil giri? [url=1xbet-giris-5.com]1xbet-giris-5.com[/url] .

  16. best Irish pharmacy websites [url=https://irishpharmafinder.shop/#]Irish Pharma Finder[/url] best Irish pharmacy websites

    Hermanengam

    3 Nov 25 at 12:17 am

  17. купить диплом в нижнем новгороде [url=https://www.rudik-diplom1.ru]купить диплом в нижнем новгороде[/url] .

    Diplomi_zjer

    3 Nov 25 at 12:19 am

  18. рейтинг seo агентств [url=www.luchshie-digital-agencstva.ru]рейтинг seo агентств[/url] .

  19. 1xbet giri?i [url=https://1xbet-giris-6.com]1xbet giri?i[/url] .

  20. потолки [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru]потолки[/url] .

  21. 1xbet resmi sitesi [url=www.1xbet-giris-5.com/]www.1xbet-giris-5.com/[/url] .

  22. There is certainly a lot to find out about this topic.

    I really like all the points you made.

  23. Кто делал дератизация цена холодным туманом? Эффективно ли?
    уничтожение блох

    KennethceM

    3 Nov 25 at 12:24 am

  24. AlbertTeery

    3 Nov 25 at 12:24 am

  25. irishpharmafinder: trusted online pharmacy Ireland – discount pharmacies in Ireland

    Johnnyfuede

    3 Nov 25 at 12:25 am

  26. ANAK JEMBOT

    ANAK JEMBOT

    3 Nov 25 at 12:25 am

  27. потолочник натяжные потолки отзывы [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru]потолочник натяжные потолки отзывы[/url] .

  28. 1xbet tr [url=https://1xbet-giris-2.com/]1xbet tr[/url] .

  29. 1xbet mobil giri? [url=http://1xbet-giris-2.com]http://1xbet-giris-2.com[/url] .

  30. рейтинг сео компаний [url=www.reiting-seo-kompanii.ru/]рейтинг сео компаний[/url] .

  31. 1xbet com giri? [url=http://1xbet-giris-5.com]http://1xbet-giris-5.com[/url] .

  32. thinkbigmovefast – Loving the bold approach and clean design, feels refreshing.

  33. bahis sitesi 1xbet [url=https://1xbet-giris-5.com/]bahis sitesi 1xbet[/url] .

  34. потолочкин натяжные потолки нижний новгород [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru]потолочкин натяжные потолки нижний новгород[/url] .

  35. UkMedsGuide: affordable medications UK – affordable medications UK

    HaroldSHems

    3 Nov 25 at 12:38 am

  36. AlbertTeery

    3 Nov 25 at 12:38 am

  37. AlbertTeery

    3 Nov 25 at 12:39 am

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

    Diplomi_vier

    3 Nov 25 at 12:39 am

  39. cheap medicines online UK: legitimate pharmacy sites UK – UkMedsGuide

    Johnnyfuede

    3 Nov 25 at 12:42 am

  40. 1xbet giri? linki [url=www.1xbet-giris-6.com/]1xbet giri? linki[/url] .

  41. 1xbet mobi [url=http://1xbet-giris-5.com]http://1xbet-giris-5.com[/url] .

  42. 1xbet tr [url=https://1xbet-giris-2.com/]1xbet tr[/url] .

  43. 1xbet resmi giri? [url=https://1xbet-giris-5.com/]https://1xbet-giris-5.com/[/url] .

  44. J’ai une passion debordante pour Frumzi Casino, il cree une experience captivante. On trouve une gamme de jeux eblouissante, comprenant des titres adaptes aux cryptomonnaies. Le bonus de bienvenue est genereux. Le suivi est d’une fiabilite exemplaire. Les transactions sont d’une fiabilite absolue, occasionnellement des bonus plus frequents seraient un hit. Pour faire court, Frumzi Casino offre une experience hors du commun. Pour couronner le tout la plateforme est visuellement electrisante, permet une plongee totale dans le jeu. A souligner les paiements securises en crypto, renforce la communaute.
    Voir les dГ©tails|

    starwaveik9zef

    3 Nov 25 at 12:46 am

  45. cheap medicines online Australia: AussieMedsHubAu – pharmacy discount codes AU

    HaroldSHems

    3 Nov 25 at 12:47 am

  46. Je suis accro a Cheri Casino, ca invite a l’aventure. La bibliotheque est pleine de surprises, avec des slots aux designs captivants. Il rend le debut de l’aventure palpitant. Les agents sont rapides et pros. Les paiements sont securises et rapides, mais encore des offres plus genereuses rendraient l’experience meilleure. Dans l’ensemble, Cheri Casino offre une aventure memorable. Notons aussi la plateforme est visuellement vibrante, facilite une experience immersive. Egalement top le programme VIP avec des avantages uniques, renforce la communaute.
    Aller sur le site|

    wildmindok4zef

    3 Nov 25 at 12:47 am

  47. Je suis totalement conquis par Wild Robin Casino, c’est une plateforme qui pulse avec energie. Le choix de jeux est tout simplement enorme, comprenant des titres adaptes aux cryptomonnaies. Il rend le debut de l’aventure palpitant. Le support est fiable et reactif. Le processus est fluide et intuitif, cependant des bonus plus varies seraient un plus. Globalement, Wild Robin Casino est un choix parfait pour les joueurs. En extra le design est tendance et accrocheur, facilite une immersion totale. Un point fort les evenements communautaires vibrants, propose des privileges sur mesure.
    Wild Robin|

    globalflowis1zef

    3 Nov 25 at 12:48 am

  48. Je suis completement seduit par Instant Casino, il procure une sensation de frisson. Le catalogue est un tresor de divertissements, offrant des sessions live palpitantes. Il donne un elan excitant. Les agents sont rapides et pros. Les gains arrivent sans delai, mais des recompenses additionnelles seraient ideales. Pour finir, Instant Casino assure un fun constant. Pour couronner le tout le design est tendance et accrocheur, amplifie l’adrenaline du jeu. A mettre en avant les paiements securises en crypto, offre des bonus exclusifs.
    http://www.instantcasino366fr.com|

    Swiftforceor8zef

    3 Nov 25 at 12:48 am

  49. UK online pharmacies list: best UK pharmacy websites – affordable medications UK

    Johnnyfuede

    3 Nov 25 at 12:50 am

  50. потолочкин потолки натяжные [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru/]http://natyazhnye-potolki-nizhniy-novgorod-1.ru/[/url] .

Leave a Reply