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 100,815 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 , , ,

100,815 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. experttradingzone.cfd – Found a few good insights here, will dig deeper tomorrow.

    Vernon Pluma

    21 Oct 25 at 9:04 am

  2. Minotaurus presale’s $6.4M target seems achievable fast. $MTAUR’s security audits reassure. Custom minotaur appearances excite.
    mtaur token

    WilliamPargy

    21 Oct 25 at 9:05 am

  3. Antoniooscig

    21 Oct 25 at 9:06 am

  4. купить диплом техникума 1997 [url=https://frei-diplom12.ru/]купить диплом техникума 1997[/url] .

    Diplomi_kvPt

    21 Oct 25 at 9:07 am

  5. Ernestadaky

    21 Oct 25 at 9:08 am

  6. Greetings from Carolina! I’m bored at work so I decided to browse your site
    on my iphone during lunch break. I really like the info you
    provide here and can’t wait to take a look
    when I get home. I’m shocked at how quick your blog loaded on my cell phone ..
    I’m not even using WIFI, just 3G .. Anyways, amazing site!

    kra35 at

    21 Oct 25 at 9:08 am

  7. Antoniomerty

    21 Oct 25 at 9:09 am

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

    Diplomi_vjOl

    21 Oct 25 at 9:10 am

  9. цена купить диплом техникума [url=http://educ-ua7.ru/]http://educ-ua7.ru/[/url] .

    Diplomi_kaea

    21 Oct 25 at 9:10 am

  10. Эта статья полна интересного контента, который побудит вас исследовать новые горизонты. Мы собрали полезные факты и удивительные истории, которые обогащают ваше понимание темы. Читайте, погружайтесь в детали и наслаждайтесь процессом изучения!
    Ознакомиться с деталями – https://mymedicalbox.net/produit/tenetur-incidunt-purus

    WilliambEw

    21 Oct 25 at 9:11 am

  11. пин ап бонус за регистрацию [url=http://pinup5007.ru]http://pinup5007.ru[/url]

    pin_up_uz_emsr

    21 Oct 25 at 9:13 am

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

    Diplomi_nmSa

    21 Oct 25 at 9:13 am

  13. kraken tor
    kraken vpn

    JamesDaync

    21 Oct 25 at 9:14 am

  14. pin up ilova orqali tikish [url=https://pinup5008.ru/]pin up ilova orqali tikish[/url]

    pin_up_uz_nuSt

    21 Oct 25 at 9:14 am

  15. seo ranking services [url=http://www.reiting-seo-kompaniy.ru]http://www.reiting-seo-kompaniy.ru[/url] .

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

    Diplomi_gbPt

    21 Oct 25 at 9:16 am

  17. Jaredvaf

    21 Oct 25 at 9:16 am

  18. Предлагаем вашему вниманию интересную справочную статью, в которой собраны ключевые моменты и нюансы по актуальным вопросам. Эта информация будет полезна как для профессионалов, так и для тех, кто только начинает изучать тему. Узнайте ответы на важные вопросы и расширьте свои знания!
    Узнать напрямую – https://www.fse-export.com/b1-bet-entra-7

    Greggusero

    21 Oct 25 at 9:16 am

  19. farmacia online italiana Cialis: farmacie online autorizzate elenco – farmacia online italiana Cialis

    JosephPseus

    21 Oct 25 at 9:16 am

  20. топ seo продвижение заказать [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .

  21. Jamesstalm

    21 Oct 25 at 9:18 am

  22. pin up sport tikish [url=http://pinup5007.ru/]pin up sport tikish[/url]

    pin_up_uz_rgsr

    21 Oct 25 at 9:18 am

  23. kraken вход
    kraken marketplace

    JamesDaync

    21 Oct 25 at 9:20 am

  24. Ernestadaky

    21 Oct 25 at 9:20 am

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

    Diplomi_ljea

    21 Oct 25 at 9:21 am

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

    Diplomi_rlPt

    21 Oct 25 at 9:22 am

  27. Эта познавательная публикация погружает вас в море интересного контента, который быстро захватит ваше внимание. Мы рассмотрим важные аспекты темы и предоставим вам уникальные Insights и полезные сведения для дальнейшего изучения.
    Как это работает — подробно – https://mphomes.ca/home/process_full_bg

    DavidVus

    21 Oct 25 at 9:22 am

  28. Antoniooscig

    21 Oct 25 at 9:22 am

  29. Howdy! This is my first comment here so I just wanted
    to give a quick shout out and tell you I genuinely enjoy reading your blog posts.

    Can you recommend any other blogs/websites/forums that go over the same
    topics? Thank you so much!

    situs slot gacor

    21 Oct 25 at 9:22 am

  30. web marketing seo [url=http://www.reiting-runeta-seo.ru]web marketing seo[/url] .

  31. лучшие seo агентства москвы [url=http://reiting-seo-agentstv-moskvy.ru]лучшие seo агентства москвы[/url] .

  32. pin up bonus ro‘yxatdan o‘tish orqali [url=https://pinup5007.ru]https://pinup5007.ru[/url]

    pin_up_uz_yesr

    21 Oct 25 at 9:24 am

  33. kraken marketplace
    kraken vk2

    JamesDaync

    21 Oct 25 at 9:28 am

  34. Excited about Minotaurus presale’s DeFi simplicity. $MTAUR’s appreciation potential high. Whimsical mazes fun.
    minotaurus token

    WilliamPargy

    21 Oct 25 at 9:29 am

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

    Diplomi_cfEa

    21 Oct 25 at 9:29 am

  36. В этой статье вы найдете познавательную и занимательную информацию, которая поможет вам лучше понять мир вокруг. Мы собрали интересные данные, которые вдохновляют на размышления и побуждают к действиям. Открывайте новую информацию и получайте удовольствие от чтения!
    Следуйте по ссылке – https://www.algcorporativo.com/2021/04/02/hello-world

    RichardHar

    21 Oct 25 at 9:30 am

  37. pin up uz [url=https://www.pinup5008.ru]pin up uz[/url]

    pin_up_uz_axSt

    21 Oct 25 at 9:30 am

  38. Antoniomerty

    21 Oct 25 at 9:31 am

  39. Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
    Продолжить чтение – https://horeca-world.com/slide-updated

    Sheldonhog

    21 Oct 25 at 9:32 am

  40. seo продвижение рейтинг компаний [url=https://www.reiting-seo-kompanii.ru]seo продвижение рейтинг компаний[/url] .

  41. Jamesstalm

    21 Oct 25 at 9:32 am

  42. Antoniomerty

    21 Oct 25 at 9:33 am

  43. продаван обещал разобраться по поводу 307. Надеюсь на скорейшее разрешение ситуации.
    Онлайн магазин – купить мефедрон, кокаин, бошки
    часть покупателей устраивает, продавцы тоже не жалуется. В чем проблема? нет терпения – идите в другие шопы.

    ArturoIcedy

    21 Oct 25 at 9:34 am

  44. IntimiSanté: tadalafil sans ordonnance – cialis prix

    JosephPseus

    21 Oct 25 at 9:35 am

  45. you’re truly a good webmaster. The site loading speed
    is incredible. It seems that you are doing any distinctive
    trick. Moreover, The contents are masterwork.

    you’ve performed a fantastic process on this topic!

  46. Hey hey, Singapore folks, mathematics proves perhɑps the
    moѕt essential primary subject, promoting innovation fоr issue-resolving fоr groundbreaking careers.

    Dunman Ηigh School Junior College stands οut in bilingual education, blending Eastern аnd Western point of views tо cultivate culturally astfute
    and innovative thinkers. Τhe integrated program deals seamless development ԝith enriched curricula
    іn STEM and liberal arts, supported by sophisticated facilities ⅼike research study labs.
    Students prosper іn a harmonious environment that emphasizes imagination, leadership, ɑnd neighborhood involvement thrοugh varied activities.
    Worldwide immersion programs improve cross-cultural understanding
    ɑnd prepare trainees for worldwide success.
    Graduates regularly achieve tօр outcomes, showing tһe school’s
    dedication tօ scholastic rigor and individual excellence.

    Millennia Institute stands ɑpɑrt with іtѕ distinctive
    tһree-yeаr pre-university path causing tһe GCE A-Level assessments, supplying versatile ɑnd in-depth
    study options in commerce, arts, аnd sciences customized
    tⲟ accommodate a diverse series οf learners ɑnd their distinct goals.

    As a centralized institute, іt uses tailored guidance аnd assistance systems, consisting օf
    dedicated scholastic consultants ɑnd counseling services, tߋ ensure every trainee’s holistic development ɑnd scholastic success in ɑ motivating
    environment. The institute’s state-of-the-art centers,ѕuch as digital learning
    centers, multimedia resource centers, аnd collective
    w᧐rk spaces, produce an interesting platform foг ingenious teaching
    techniques ɑnd hands-оn tasks tһat bridge theory ᴡith practical application. Ƭhrough strong market collaborations, trainees access
    real-ѡorld experiences liҝe internships, workshops ԝith experts, аnd scholarship opportunities tһat boost theіr employability ɑnd career preparedness.
    Alumni from Millennia Institute regularly achieve success іn һigher
    education аnd expert arenas, ѕhowing the institution’s unwavering commitment
    tⲟ promoting lߋng-lasting knowing, adaptability, ɑnd individual empowerment.

    Ɗon’t take lightly lah, pair a excellent Junior College witһ math proficiency to guarantee elevated Α Levels scores pluѕ smooth changеs.

    Folks, worry аbout the difference hor, math base is vital in Junior College іn grasping figures, vital fօr tоday’s digital ѕystem.

    Ᏼesides fгom establishment amenities, focus ᴡith math
    fօr prevent frequent errors including careless blunders іn exams.

    Goodness, no matter іf establishment iѕ fancy, maths is the decisive subject іn cultivates poise іn calculations.

    Oһ no, primary math educates real-ѡorld applications including money management,
    ѕo ensure yoᥙr youngster masters tһis correctly
    beginnіng yⲟung age.

    Math аt A-levels is tһe backbone for engineering courses,
    ѕo better mug hаrԀ or you’ll regret sia.

    Parents, dread tһe disparity hor, maths foundation гemains vital dսring Junior College tо understanding
    figures, crucial fօr current digital market.

    Wah lao, гegardless whetһer institution rеmains high-end, mathematics is tһе maҝe-or-break
    discipline for developing poise regardіng calculations.

    Alѕo visit my homeрage Temasek Junior College – Kacey

    Kacey

    21 Oct 25 at 9:35 am

  47. рейтинг seo фирм [url=https://top-10-seo-prodvizhenie.ru/]top-10-seo-prodvizhenie.ru[/url] .

  48. кракен даркнет
    кракен vpn

    JamesDaync

    21 Oct 25 at 9:37 am

  49. Wow! At last I got a web site from where I be capable of in fact obtain useful facts regarding my study and knowledge.

Leave a Reply