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 118,110 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 , , ,

118,110 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. togetherwerise – The site looks clean and promising, but I couldn’t find detailed team bios or track record.

    Delpha Alier

    31 Oct 25 at 4:18 am

  2. billig Viagra Norge: billig Viagra Norge – generisk Viagra 50mg / 100mg

    RichardImmon

    31 Oct 25 at 4:19 am

  3. Без обновлений программ жить опасно кракен онион тор кракен onion сайт kra ссылка kraken сайт

    RichardPep

    31 Oct 25 at 4:19 am

  4. автоматические карнизы [url=https://elektrokarniz499.ru/]автоматические карнизы[/url] .

  5. купить диплом в муроме [url=www.rudik-diplom3.ru/]купить диплом в муроме[/url] .

    Diplomi_noei

    31 Oct 25 at 4:21 am

  6. Very nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed browsing your
    blog posts. In any case I’ll be subscribing to your
    feed and I hope you write again soon!

    Also visit my webpage led screen visuals

  7. электрокарнизы купить в москве [url=https://elektrokarniz797.ru]электрокарнизы купить в москве[/url] .

  8. Spot on with this write-up, I absolutely believe that this web site needs a lot more attention. I’ll
    probably be back again to see more, thanks for the information!

  9. купить диплом в калининграде [url=https://rudik-diplom8.ru/]купить диплом в калининграде[/url] .

    Diplomi_yiMt

    31 Oct 25 at 4:22 am

  10. рулонные жалюзи москва [url=www.rulonnye-shtory-s-elektroprivodom7.ru/]рулонные жалюзи москва[/url] .

  11. кракен маркетплейс
    kraken сайт

    JamesDaync

    31 Oct 25 at 4:22 am

  12. Heya i am for the primary time here. I found this board and I find It really helpful & it helped
    me out a lot. I am hoping to give something back and
    help others like you aided me.

    kra36 cc

    31 Oct 25 at 4:24 am

  13. рулонные шторы с электроприводом цена [url=www.rulonnye-shtory-s-elektroprivodom7.ru]рулонные шторы с электроприводом цена[/url] .

  14. карниз для штор электрический [url=https://elektrokarniz797.ru/]карниз для штор электрический[/url] .

  15. рулонные шторы жалюзи на окна [url=http://www.rulonnye-shtory-s-elektroprivodom7.ru]http://www.rulonnye-shtory-s-elektroprivodom7.ru[/url] .

  16. электронный карниз для штор [url=http://elektrokarniz499.ru]электронный карниз для штор[/url] .

  17. Вызвать уничтожение моли
    уничтожение блох

    Wernermog

    31 Oct 25 at 4:30 am

  18. kraken СПб
    kraken СПб

    JamesDaync

    31 Oct 25 at 4:32 am

  19. Вызывали уничтожение тараканов в мебели ночью, приехали быстро!
    санэпидемстанция цены

    KennethceM

    31 Oct 25 at 4:33 am

  20. We’re a bunch of volunteers and opening a brand new scheme in our
    community. Your web site provided us with helpful info to work on. You’ve done an impressive activity and our whole group might
    be grateful to you.

  21. Запой представляет собой состояние, при котором организм находится под постоянным воздействием этанола. Это вызывает интоксикацию, нарушение обменных процессов и дестабилизацию психики. При обращении за помощью врач-нарколог оценивает состояние пациента и подбирает индивидуальную схему терапии, чтобы безопасно вывести человека из запоя и предотвратить развитие синдрома отмены. Вмешательство проводится как в стационаре, так и на дому, в зависимости от состояния пациента.
    Разобраться лучше – https://vyvod-iz-zapoya-v-krasnoyarske17.ru/czentr-kodirovaniya-vyvod-iz-zapoya-krasnoyarsk/

    Ronaldseict

    31 Oct 25 at 4:34 am

  22. электро рулонные шторы [url=www.rulonnye-shtory-s-elektroprivodom7.ru/]www.rulonnye-shtory-s-elektroprivodom7.ru/[/url] .

  23. ИТ формирует мышление нового поколения kraken зеркало кракен онион тор кракен онион зеркало кракен даркнет маркет

    RichardPep

    31 Oct 25 at 4:35 am

  24. MichaelPione

    31 Oct 25 at 4:35 am

  25. диплом медсестры с аккредитацией купить [url=http://www.frei-diplom13.ru]диплом медсестры с аккредитацией купить[/url] .

    Diplomi_pykt

    31 Oct 25 at 4:36 am

  26. Результат после травля тараканов потрясающий!
    обработка участков от клещей

    KennethceM

    31 Oct 25 at 4:37 am

  27. Howdy! I know this is kinda off topic but I was wondering if you
    knew where I could find a captcha plugin for my comment form?

    I’m using the same blog platform as yours and I’m having trouble finding one?
    Thanks a lot!

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

  29. MichaelPione

    31 Oct 25 at 4:38 am

  30. Kamagra Wirkung und Nebenwirkungen: Potenzmittel ohne ärztliches Rezept – Kamagra Oral Jelly Deutschland

    ThomasCep

    31 Oct 25 at 4:40 am

  31. рулонные шторы на кухню купить [url=https://rulonnye-shtory-s-elektroprivodom7.ru/]рулонные шторы на кухню купить[/url] .

  32. куплю диплом младшей медсестры [url=www.frei-diplom13.ru/]www.frei-diplom13.ru/[/url] .

    Diplomi_vvkt

    31 Oct 25 at 4:43 am

  33. [url=https://umnye-shtory-s-elektroprivodom.ru/]управляемые шторы прокарниз[/url] – управляемые шторы, которые позволят вам легко контролировать свет и атмосферу в вашем доме.
    Раздел 3: Установка управляемых штор

  34. Борьба с профессиональная дезинфекция удалась, фирма молодцы.
    обработка квартиры от клопов

    KennethceM

    31 Oct 25 at 4:44 am

  35. ehe258.com – Color palette felt calming, nothing distracting, just focused, thoughtful design.

    Juliann Evelyn

    31 Oct 25 at 4:44 am

  36. кракен обмен
    kraken зеркало

    JamesDaync

    31 Oct 25 at 4:44 am

  37. Eh eh, steady pom pi pi, maths iѕ ߋne of the top subjects ɑt Junior College, building base fоr A-Level
    advanced math.
    In adԁition from school facilities, emphasize оn maths to st᧐p typical pitfalls ѕuch as inattentive blunders at
    assessments.

    Dunman Higһ School Junior College stands оut in multilingual
    education, blending Eastern аnd Western point ߋf views to cuultivate
    culturally astute аnd ingenious thinkers. Thе integrated
    program ߋffers seamless progression ԝith enriched curricula іn STEM and liberal arts, supported ƅy sophisticated centers
    like reseɑrch laboratories. Students flourish іn a harmonious environment tһat emphasizes creativity, leadership,
    ɑnd community involvement tһrough diverse activities.
    Global immersion programs boost cross-cultural understanding ɑnd prepare trainees fߋr international
    success. Graduates regularly accomplish leading outcomes,
    reflecting tһе school’s dedication tо scholastic rigor ɑnd personal quality.

    Victoria Junior College sparks imagination and fosters visionary management, empowering
    students tօ produce favorable change tһrough a curriculum tһat stimulates passions and
    encourages vibrant thinking іn a stunning coastal campus setting.
    The school’s detailed centers, including humanities discussion spaces, science гesearch study suites,
    aand arts efficiency locations, assistance enriched programs іn arts, liberal arts, ɑnd sciences that promote interdisciplinary insights ɑnd academic proficiency.
    Strategic alliances ѡith secondary schools thrⲟugh incorporated programs guarantee а smooth educational
    journey, uѕing accelerated learning paths аnd specialized electives tһat
    accommodate individual strengths аnd intеrests. Service-learning
    initiatives ɑnd international outreach tasks,
    ѕuch ɑs worldwide volunteer explorations аnd leadership forums, build caring personalities, strength, аnd a commitment to community welfare.

    Graduates lead ᴡith undeviating conviction ɑnd attain extraordinary success
    іn universities and careers, embodying Victoria
    Junior College’ѕ tradition оf nurturing imaginative,
    principled, ɑnd transformative people.

    Listen սp, composed pom рi рі, mathematics іѕ among
    of tһe top topics at Junior College, laying base fоr A-Level advanced math.

    Ιn adԁition to institution amenities, concentrate ᧐n maths in ordeг
    to stop frequent mistakes lіke inattentive errors ɗuring assessments.

    Οһ dear, lacking solid math ԁuring Junior College, еven prestigious institution kids mаү stumble ɑt hіgh school calculations, ѕо cultivate it noᴡ leh.

    Mums ɑnd Dads, competitive approach engaged lah,robust primary math leads
    іn superior scientific understanding аnd engineering aspirations.

    Wow, mathematics serves ɑs the base block іn primary schooling, helping children іn dimensional reasoning tⲟ building routes.

    Ɗⲟn’t underestimate Ꭺ-levels; tһey’re the foundation ᧐f youг academic journey in Singapore.

    Alas, primary mathematics educates everyday implementations ѕuch as budgeting, so guarantee your child ցets
    it properly starting young.

    my blog post: physics and maths tutor chemistry edexcel as level

  38. электрические рулонные шторы купить москва [url=https://rulonnye-shtory-s-elektroprivodom7.ru/]rulonnye-shtory-s-elektroprivodom7.ru[/url] .

  39. Thank you for some other informative web site.
    The place else could I am getting that kind of info written in such an ideal manner?
    I’ve a venture that I’m simply now working on, and I have been at the glance out for such info.

  40. kraken tor
    kraken darknet

    JamesDaync

    31 Oct 25 at 4:46 am

  41. Вызов обработка от клопов стоимость на выходные возможен?
    уничтожение тараканов в кафе

    KennethceM

    31 Oct 25 at 4:47 am

  42. электрокарниз москва [url=https://elektrokarniz797.ru/]https://elektrokarniz797.ru/[/url] .

  43. Kamagra online kaufen: Kamagra Wirkung und Nebenwirkungen – Kamagra online kaufen

    ThomasCep

    31 Oct 25 at 4:47 am

  44. карнизы для штор с электроприводом [url=www.elektrokarniz499.ru/]карнизы для штор с электроприводом[/url] .

  45. автоматические рулонные шторы [url=https://rulonnye-shtory-s-elektroprivodom7.ru/]автоматические рулонные шторы[/url] .

  46. Интернет изменил мышление человека kraken onion зеркала kraken онион kraken онион тор кракен онион

    RichardPep

    31 Oct 25 at 4:51 am

  47. MichaelPione

    31 Oct 25 at 4:52 am

  48. JamesDaync

    31 Oct 25 at 4:52 am

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

Leave a Reply