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,976 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,976 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. На сторінці zebraschool.com.ua замовляв ремонт автомагнітоли у Вінниці — зробили якісно

    zebraschool-454

    26 Oct 25 at 8:18 am

  2. What a information of un-ambiguity and preserveness
    of valuable familiarity on the topic of unpredicted feelings.

    sugar daddy

    26 Oct 25 at 8:18 am

  3. 1xbet yeni giri? adresi [url=https://1xbet-14.com]1xbet yeni giri? adresi[/url] .

    1xbet_jiet

    26 Oct 25 at 8:19 am

  4. J-center Studio — школа, где учат профессии парикмахера на практике с четвёртого дня: работа с клиентами, колористика, мужские и женские стрижки, укладки, стажировка в салонах. Прозрачные цены, маленькие группы, инструменты и материалы — за счёт школы. Записаться и узнать ближайший старт можно на https://j-center.ru/ — расписание, форматы (группы, индивидуально, экстерн) и контакты на странице. Диплом и реальный опыт дают выпускникам быстрый вход в индустрию красоты.

    cipymeRed

    26 Oct 25 at 8:24 am

  5. На сайті zebraschool.com.ua лагодили генератор у Сумах — сервіс на висоті

    zebraschool-651

    26 Oct 25 at 8:25 am

  6. 1x bet giri? [url=www.1xbet-12.com]www.1xbet-12.com[/url] .

    1xbet_dtSr

    26 Oct 25 at 8:26 am

  7. На сторінці zebraschool.com.ua замовив ремонт електросамоката в Полтаві — результат чудовий

    zebraschool-596

    26 Oct 25 at 8:28 am

  8. 1xbet yeni giri? [url=http://1xbet-12.com]1xbet yeni giri?[/url] .

    1xbet_hySr

    26 Oct 25 at 8:28 am

  9. farmacia con entrega rápida: farmacia online para hombres – pastillas de potencia masculinas

    Jesuskax

    26 Oct 25 at 8:28 am

  10. Piece of writing writing is also a excitement, if you be
    familiar with after that you can write or else it is complex to write.

    toto slot

    26 Oct 25 at 8:29 am

  11. 1 x bet giri? [url=www.1xbet-16.com]1 x bet giri?[/url] .

    1xbet_xzOn

    26 Oct 25 at 8:29 am

  12. 1xbet tr giri? [url=https://1xbet-10.com]https://1xbet-10.com[/url] .

    1xbet_thea

    26 Oct 25 at 8:29 am

  13. kraken vk5
    kraken онлайн

    JamesDaync

    26 Oct 25 at 8:30 am

  14. Если вы ищете информацию о бонусах при регистрации, прочитайте наши рекомендации о видах вознаграждений; в одном из разделов статьи естественно упомянут https://bergkompressor.ru/news/artcles/?1xbet_promokod_pri_registracii_bonus_5.html для получения приветственного бонуса. Редакция объясняем, как вводить данные при регистрации и какие правила нужно выполнить для отыгрыша.

    PatrickDrymn

    26 Oct 25 at 8:30 am

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

    1xbet_aoKa

    26 Oct 25 at 8:31 am

  16. Отзывы о обработка от клопов с гарантией реальные? Делитесь.
    дезинфекция после потопа

    KennethceM

    26 Oct 25 at 8:32 am

  17. Hurrah! At last I got a blog from where I can really obtain useful facts concerning my
    study and knowledge.

    유흥알바

    26 Oct 25 at 8:32 am

  18. На сайті zebraschool.com.ua побачив послугу ремонту дитячих колясок — дійсно зручно

    zebraschool-454

    26 Oct 25 at 8:34 am

  19. оборудование для больниц [url=medicinskoe–oborudovanie.ru]medicinskoe–oborudovanie.ru[/url] .

  20. Everything in One Place: https://www.home-truths.co.uk

    BryanAlarl

    26 Oct 25 at 8:35 am

  21. частная наркологическая клиника в москве анонимное [url=https://narkologicheskaya-klinika-23.ru/]https://narkologicheskaya-klinika-23.ru/[/url] .

  22. букмекерская контора теннесси скачать [url=mostbet12032.ru]mostbet12032.ru[/url]

    mostbet_kg_xfmt

    26 Oct 25 at 8:36 am

  23. mostbet kg [url=https://mostbet12031.ru/]mostbet kg[/url]

    mostbet_kg_igMa

    26 Oct 25 at 8:37 am

  24. 1 x bet [url=www.1xbet-14.com]1 x bet[/url] .

    1xbet_oset

    26 Oct 25 at 8:39 am

  25. 1 xbet giri? [url=https://1xbet-12.com]https://1xbet-12.com[/url] .

    1xbet_ehSr

    26 Oct 25 at 8:39 am

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

    1xbet_djea

    26 Oct 25 at 8:42 am

  27. mostbets [url=https://mostbet12031.ru/]https://mostbet12031.ru/[/url]

    mostbet_kg_kxMa

    26 Oct 25 at 8:42 am

  28. Hi there, just became alert to your blog through Google,
    and found that it’s really informative. I am going to watch out for brussels.
    I’ll appreciate if you continue this in future. A lot of people will be benefited from your writing.

    Cheers!

  29. 1 x bet [url=http://1xbet-16.com/]1 x bet[/url] .

    1xbet_vlOn

    26 Oct 25 at 8:44 am

  30. 1xbet lite [url=http://1xbet-16.com]1xbet lite[/url] .

    1xbet_hgOn

    26 Oct 25 at 8:47 am

  31. букмекерская контора теннесси скачать [url=http://mostbet12031.ru]http://mostbet12031.ru[/url]

    mostbet_kg_kzMa

    26 Oct 25 at 8:47 am

  32. köpa Viagra online Sverige: Sildenafil-tabletter pris – MannensApotek

    Jesuskax

    26 Oct 25 at 8:47 am

  33. kraken онлайн
    kraken vk3

    JamesDaync

    26 Oct 25 at 8:48 am

  34. 1xbet resmi sitesi [url=https://1xbet-13.com/]https://1xbet-13.com/[/url] .

    1xbet_lqKa

    26 Oct 25 at 8:50 am

  35. Ресторан чистый после профессиональная дератизация.
    уничтожение муравьев

    KennethceM

    26 Oct 25 at 8:51 am

  36. go source

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

    go source

    26 Oct 25 at 8:51 am

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

    KennethceM

    26 Oct 25 at 8:52 am

  38. Alas, primary math instructs real-worⅼd uѕеs suсh ɑs financial planning, sօ guarantee үour
    kid grasps tһis rіght starting eɑrly.
    Listen ᥙp, composed pom pi pі, math remаins among fгom the leading
    disciplines ɗuring Junior College, building foundation іn A-Level calculus.

    St. Andrew’ѕ Junior College fosters Anglican worths ɑnd holistic development, developing
    principled individuals ᴡith strong character.

    Modern amenities support excellence іn academics, sports,
    аnd arts.Community service and leadership programs impart compassion аnd duty.
    Diverse ϲo-curricular activities promote teamwork ɑnd sеlf-discovery.
    Alumni emerge аs ethical leaders, contributing meaningfully t᧐ society.

    Ⴝt. Joseph’ѕ Institution Junior College promotes cherished Lasallian traditions оf faith, service, and intellectual curiosity,
    producing ɑn empowering environment ᴡhere trainees
    pursue knowledge ԝith passion and devote
    tһemselves to uplifting οthers tһrough caring actions.
    Τhe incorporated program makеs ѕure a fluid
    development fгom secondary to pre-university levels, ԝith a concentrate
    οn multilingual proficiency ɑnd innovative curricula supported ƅy centers
    ⅼike stɑte-of-the-art performing arts centers аnd science гesearch labs that influence imaginative ɑnd analytical quality.
    Worldwide immersion experiences, including
    international service trips аnd cultural exchange programs,
    expand students’ horizons, enhance linguistic skills, аnd cultivate а deep appreciation fοr varied
    worldviews. Opportunities fߋr advanced гesearch study,
    management functions іn trainee companies, аnd mentorship fгom accomplished professors develop confidence,
    vital thinking, ɑnd a dedication tо ⅼong-lasting
    knowing. Graduates ɑre understood for theіr compassion and
    hіgh accomplishments, protecting plaϲes іn prominent universities аnd mastering careers that align wifh tһe college’ѕ ethos օf service
    and intellectual rigor.

    Wah, math acts ⅼike thе foundation block in primary learning, aiding
    kids іn spatial analysis fօr design routes.
    Alas, lacking robust mathematics аt Junior College, еven prestigious
    institution kids сould falter ԝith secondary equations, tһus cultivate thіs now leh.

    Dοn’t take lightly lah, pair ɑ reputable
    Junior College alongside mathematics excellence fοr guarantee superior А Levels гesults and smooth transitions.

    Oһ dear, lacking solid math аt Junior College, eѵеn leading institution children mаү falter іn neхt-level algebra, so cultivate it noѡ leh.

    Good grades іn A-levels mеan less debt from loans if ʏou get merit-based
    aid.

    Oһ, maths is the base block for primary learning, assisting kids ѡith spatial reasoning tο architecture paths.

    Ⲟh dear, without solid maths іn Junior College,
    no matter leading establishment kids ϲould struggle wіtһ next-level equations,
    tһus cultivate іt now leh.

    Here is my blog :: Math tuition for ip students at east

  39. платная наркологическая клиника [url=http://www.narkologicheskaya-klinika-23.ru]http://www.narkologicheskaya-klinika-23.ru[/url] .

  40. 1xbet yeni adresi [url=1xbet-14.com]1xbet yeni adresi[/url] .

    1xbet_adet

    26 Oct 25 at 8:54 am

  41. Appreciate this post. Let me try it out.

    98WIN

    26 Oct 25 at 8:56 am

  42. vrltdhu

    26 Oct 25 at 8:56 am

  43. Hello, i think that i saw you visited my site so i came to “return the favor”.I’m attempting to find things to improve my website!I suppose its ok to use a few of your
    ideas!!

    website

    26 Oct 25 at 8:58 am

  44. JamesDaync

    26 Oct 25 at 9:01 am

  45. xbet [url=www.1xbet-16.com/]xbet[/url] .

    1xbet_eiOn

    26 Oct 25 at 9:01 am

  46. мелбет kg [url=https://www.mostbet12032.ru]https://www.mostbet12032.ru[/url]

    mostbet_kg_nrmt

    26 Oct 25 at 9:01 am

  47. 1xbet giri? [url=1xbet-12.com]1xbet giri?[/url] .

    1xbet_pdSr

    26 Oct 25 at 9:03 am

  48. После санэпидемстанция цены дом безопасный для детей.
    уничтожение клопов холодным туманом

    KennethceM

    26 Oct 25 at 9:04 am

  49. mostbet сайт [url=mostbet12032.ru]mostbet12032.ru[/url]

    mostbet_kg_fvmt

    26 Oct 25 at 9:04 am

  50. мостбет официальный сайт вход [url=https://mostbet12032.ru]https://mostbet12032.ru[/url]

    mostbet_kg_ijmt

    26 Oct 25 at 9:04 am

Leave a Reply