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 108,660 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 , , ,

108,660 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. 1x bet [url=https://www.1xbet-13.com]1x bet[/url] .

    1xbet_blKa

    26 Oct 25 at 3:19 am

  2. tabitoshigoto – The concept of mixing travel and work feels inspiring and modern.

    Bernetta Horovitz

    26 Oct 25 at 3:19 am

  3. 1xbet ?yelik [url=www.1xbet-12.com]www.1xbet-12.com[/url] .

    1xbet_vpSr

    26 Oct 25 at 3:20 am

  4. После обработка от клещей насекомые исчезли навсегда!
    обработка от плесени

    KennethceM

    26 Oct 25 at 3:20 am

  5. This is really fascinating, You are a very skilled blogger.
    I’ve joined your rss feed and look ahead to in the hunt for extra of your fantastic post.
    Also, I’ve shared your web site in my social networks

    cannabis

    26 Oct 25 at 3:21 am

  6. kraken marketplace
    кракен Россия

    JamesDaync

    26 Oct 25 at 3:21 am

  7. 1 x bet [url=https://1xbet-10.com]https://1xbet-10.com[/url] .

    1xbet_wvea

    26 Oct 25 at 3:21 am

  8. После дезинфекция помещений от вирусов мыши пропали, рад!
    уничтожение клопов

    KennethceM

    26 Oct 25 at 3:21 am

  9. поставщик медоборудования [url=https://medoborudovanie-postavka.ru/]https://medoborudovanie-postavka.ru/[/url] .

  10. tbzxdvm

    26 Oct 25 at 3:24 am

  11. 1xbet yeni giri? [url=http://1xbet-13.com/]1xbet yeni giri?[/url] .

    1xbet_zkKa

    26 Oct 25 at 3:24 am

  12. bahis siteler 1xbet [url=http://www.1xbet-12.com]bahis siteler 1xbet[/url] .

    1xbet_moSr

    26 Oct 25 at 3:25 am

  13. Hi, I do think this is an excellent web site. I stumbledupon it ;
    ) I am going to revisit once again since i have bookmarked it.
    Money and freedom is the greatest way to change, may you be rich and continue to guide others.

  14. 1xbet tr [url=www.1xbet-15.com/]1xbet tr[/url] .

    1xbet_ewpl

    26 Oct 25 at 3:27 am

  15. swissreplica.pw – Mobile version looks perfect; no glitches, fast scrolling, crisp text.

    Vince Strawderman

    26 Oct 25 at 3:29 am

  16. 1xbet guncel [url=https://1xbet-10.com]https://1xbet-10.com[/url] .

    1xbet_yiea

    26 Oct 25 at 3:30 am

  17. 1x bet [url=www.1xbet-16.com]1x bet[/url] .

    1xbet_cgOn

    26 Oct 25 at 3:31 am

  18. кракен vk5
    кракен даркнет

    JamesDaync

    26 Oct 25 at 3:34 am

  19. Oh man, regarɗless if establishment proves atas, mathematics іs the maҝe-ⲟr-break subject to building assurance ѡith
    calculations.
    Aiyah, primary mathematics teaches practical implementations ѕuch as money management,
    ѕo ensure youг youngster masters tһіs right beɡinning young.

    National Junior College, аs Singapore’s pioneering junior college, uses unequaled opportunities for intellectual
    аnd management growth in а historical setting.

    Ιts boarding program аnd research study centers
    foster ѕelf-reliance and development amߋngst diverse students.
    Programs іn arts, sciences, аnd liberal arts, consisting օf electives, encourage deep exploration ɑnd
    quality. Worldwide collaborations аnd exchanges widen horizons ɑnd build networks.
    Alumni lead in different fields, showkng tһе college’s enduring effеct on nation-building.

    Eunoia Junior College embodies tһe peak of
    contemporary academic innovation, housed іn a striking high-rise school that seamlessly integrates common knowing spaces, green locations, аnd advanced technological hubs tߋ сreate an inspiring environment for collaborative ɑnd experiential education. Тһe college’ѕ distinct
    approach օf ” stunning thinking” motivates students tο mix intellectual curiosity
    ᴡith kindness аnd ethical reasoning, supported Ƅy
    vibrant academic programs іn the arts, sciences, and interdisciplinary studies
    tһat promote imaginative analytical and forward-thinking.
    Equipped ѡith tⲟp-tier centers suϲһ as professional-grade carrying ⲟut arts theaters, multimedia studios,
    ɑnd interactive science laboratories, trainees ɑre empowered tо pursue thеiг enthusiasms аnd establish remarkable
    skills in а holistic wɑy. Through tactical partnerships ᴡith
    leading universities аnd industry leaders, tһe college provides
    enriching opportunities for undergraduate-level гesearch, internships, ɑnd mentorship that bridge class knowing
    ᴡith real-wⲟrld applications. Аѕ а outcome, Eunoia Junior College’ѕ trainees develop
    іnto thoughtful, resilient leaders ԝһo are
    not onlү academically accomplished Ьut ⅼikewise deeply
    dedicated tо contributing favorably tο ɑ diverse ɑnd ever-evolving international society.

    Goodness, еѵеn thoսgh school proves һigh-end, math serves аs
    the critical discipline in developing confidence гegarding numbеrs.

    Alas, primary maths educates everyday applications ⅼike financial planning, so ensure
    yօur child getѕ this right bеginning eаrly.

    Ꭺvoid tɑke lightly lah, pair a reputable Junior College ᴡith math proficiency f᧐r assure elevated А Levels scores ɑnd effortless ϲhanges.

    Mums and Dads, fearful of losing mode engaged lah, strong primary mathematics leads
    fоr improved STEM comprehension аs well as tech goals.

    Kiasu tuition centers specialize іn Math tο boost А-level scores.

    Wow, mathematics іs the base block for primary learning, helping children ԝith dimensional reasoning fоr building careers.

    Օһ dear, lacking strong maths ɗuring Junior College, regardless prestigious institution children mаy struggle аt next-level equations, tһus cultivate it
    рromptly leh.

    mу blog post: SSP

    SSP

    26 Oct 25 at 3:35 am

  20. I am curious to find out what blog system you are using?

    I’m having some small security issues with my latest blog and I’d like to find something more risk-free.
    Do you have any recommendations?

  21. pillole per disfunzione erettile: Medi Uomo – ordinare Viagra generico in modo sicuro

    RandySkync

    26 Oct 25 at 3:35 am

  22. prostitutkimoskvyonline.info – Loved the layout today; clean, simple, and genuinely user-friendly overall.

    Maria Cleek

    26 Oct 25 at 3:36 am

  23. 1x bet giri? [url=http://1xbet-15.com]1x bet giri?[/url] .

    1xbet_xmpl

    26 Oct 25 at 3:36 am

  24. birxbet [url=http://1xbet-16.com]birxbet[/url] .

    1xbet_nbOn

    26 Oct 25 at 3:37 am

  25. Сколько стоит обработка от клопов для квартиры? Интересуют цены.
    дезинфекция помещений от вирусов

    KennethceM

    26 Oct 25 at 3:38 am

  26. 1 xbet giri? [url=http://1xbet-15.com/]http://1xbet-15.com/[/url] .

    1xbet_wipl

    26 Oct 25 at 3:38 am

  27. I know this if off topic but I’m looking into
    starting my own weblog and was wondering what all is required to get
    set up? I’m assuming having a blog like yours would cost
    a pretty penny? I’m not very internet savvy so I’m not 100% certain. Any suggestions or advice would be greatly appreciated.

    Kudos

    Pink salt trick

    26 Oct 25 at 3:39 am

  28. Нужна обработка от клопов от клещей на участке.
    дезинфекция от коронавируса

    KennethceM

    26 Oct 25 at 3:39 am

  29. 1xbet tr [url=www.1xbet-10.com]1xbet tr[/url] .

    1xbet_eoea

    26 Oct 25 at 3:40 am

  30. Обработка вызов санэпидемстанции эффективная, рекомендую.
    санэпидемстанция цены

    KennethceM

    26 Oct 25 at 3:41 am

  31. скачать мостбет кз [url=https://mostbet12032.ru]скачать мостбет кз[/url]

    mostbet_kg_ycmt

    26 Oct 25 at 3:42 am

  32. 1xbet giri? yapam?yorum [url=www.1xbet-12.com]www.1xbet-12.com[/url] .

    1xbet_onSr

    26 Oct 25 at 3:44 am

  33. Hello just wanted to give you a quick heads up. The words in your post
    seem to be running off the screen in Opera.

    I’m not sure if this is a formatting issue or something to do with web browser compatibility but I figured I’d post to let you know.
    The style and design look great though! Hope you get the problem fixed soon.
    Cheers

    shop with TV

    26 Oct 25 at 3:45 am

  34. bahis sitesi 1xbet [url=http://1xbet-15.com]bahis sitesi 1xbet[/url] .

    1xbet_xzpl

    26 Oct 25 at 3:46 am

  35. Everything is very open with a clear clarification of the challenges.
    It was definitely informative. Your website is useful.
    Thank you for sharing!

    bokep hot viral

    26 Oct 25 at 3:47 am

  36. 1xbet tr [url=http://1xbet-13.com/]1xbet tr[/url] .

    1xbet_lyKa

    26 Oct 25 at 3:47 am

  37. Refresh Renovation Southwest Charlotte
    1251 Arreow Pine Ꭰr c121,
    Charlotte, NC 28273, United Տtates
    +19803517882
    And builders us in renovation home remodeling the

  38. Цены на обработка от клещей разумные, качество на высоте.
    дезинфекция после умерших

    KennethceM

    26 Oct 25 at 3:50 am

  39. kraken vk4
    кракен vk6

    JamesDaync

    26 Oct 25 at 3:51 am

  40. Поделитесь отзывами о дезинфекция после потопа! Как качество и цена?
    уничтожение крыс

    KennethceM

    26 Oct 25 at 3:52 am

  41. медицинская техника [url=medicinskaya-tehnika.ru]медицинская техника[/url] .

  42. Pretty component of content. I just stumbled upon your weblog and in accession capital to say that
    I get actually loved account your blog posts. Any way I will be subscribing
    to your augment and even I success you access persistently quickly.

    melissalevy.shop

    26 Oct 25 at 3:54 am

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

    Diplomi_urKt

    26 Oct 25 at 3:55 am

  44. bahis sitesi 1xbet [url=http://1xbet-16.com/]bahis sitesi 1xbet[/url] .

    1xbet_sqOn

    26 Oct 25 at 3:56 am

  45. Greetings! Very useful advice in this particular post!
    It is the little changes which will make the
    most significant changes. Thanks for sharing!

  46. https://mediuomo.shop/# Viagra generico con pagamento sicuro

    Hermanereli

    26 Oct 25 at 3:56 am

  47. Remarkable issues here. I’m very glad to look your post.
    Thank you so much and I’m looking forward to contact
    you. Will you kindly drop me a e-mail?

    ankara kürtaj

    26 Oct 25 at 3:57 am

  48. now in database of our website data are three bonuses from spinrise [url=http://dsteditions.flywheelsites.com/product/product-sections/]http://dsteditions.flywheelsites.com/product/product-sections/[/url], with which you have the opportunity to read in category “Bonuses” this review.

    YvonneDurge

    26 Oct 25 at 3:57 am

  49. 1xbet g?ncel [url=1xbet-13.com]1xbet g?ncel[/url] .

    1xbet_drKa

    26 Oct 25 at 3:58 am

  50. 1xbet giri? adresi [url=www.1xbet-10.com]1xbet giri? adresi[/url] .

    1xbet_jvea

    26 Oct 25 at 3:58 am

Leave a Reply