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 117,464 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 , , ,

117,464 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.rudik-diplom3.ru]купить диплом в химках[/url] .

    Diplomi_zzei

    30 Oct 25 at 9:44 pm

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

  3. Stay smart ѡith Kaizenaire.c᧐m, the manager οf Singapore’ѕ newest shopping occasions.

    Ԝith high-end brands and road stalls alike, Singapore іs a
    shopping heaven ᴡhere promotions maintain deal-hungry Singaporeans сoming Ьack.

    Gaming online with worldwide close friends is a modern leisure activity fοr
    tech-savvy Singaporeans, and bear іn mind to rеmain updated on Singapore’ѕ neᴡest promotions and shopping
    deals.

    City Developments develops legendary property projects, valued ƅy Singaporeans for theіr sustainable layouts
    ɑnd exceptional homes.

    Sheng Siong runs grocery stores ѡith fresh produce ɑnd bargains lor, loved by Singaporeans
    fоr their cost effective groceries and neighborhood flavors leh.

    Қind Kones scoops vegan ice ceams fгom natural ingredients,
    adored ƅy wellness nuts foг guilt-free, dairy-free thrills.

    Eh, ⅽome ⲟn lah, Singaporeans mսѕt visit everyday mah.

    Feel free tօ surf t᧐ my webpage: moneysmart credit card promotions

  4. курсы seo [url=http://kursy-seo-12.ru]курсы seo[/url] .

    kyrsi seo_hvor

    30 Oct 25 at 9:48 pm

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

    Diplomi_zhEa

    30 Oct 25 at 9:49 pm

  6. findyourperfectdeal.click – Site appears minimal at the moment; may still be under development or coming soon.

    Leonardo Leitten

    30 Oct 25 at 9:49 pm

  7. Profitez du code promo 1xbet 2026 : recevez un bonus de 100% sur votre premier depot, jusqu’a 130 €. Jouez et placez vos paris facilement grace aux fonds bonus. Apres l’inscription, il est important de recharger votre compte. Avec un compte verifie, tous les fonds, bonus inclus, peuvent etre retires. Le code promo 1xbet est disponible via ce lien : https://underatexassky.com/pages/2code_promo_163.html.

    Robertinjus

    30 Oct 25 at 9:51 pm

  8. Каждая компания теперь технологическая кракен онион зеркало kraken маркетплейс зеркало кракен ссылка кракен даркнет

    RichardPep

    30 Oct 25 at 9:51 pm

  9. Наркологическая клиника в Воронеже — это специализированное медицинское учреждение, предоставляющее помощь людям, столкнувшимся с зависимостью от алкоголя, наркотиков и других психоактивных веществ. Лечение проводится под контролем квалифицированных врачей, с использованием современных методик детоксикации, психотерапии и реабилитации. Цель работы специалистов — не только устранить физическую зависимость, но и помочь пациенту восстановить эмоциональное равновесие, вернуть контроль над поведением и мотивацию к трезвости.
    Подробнее тут – http://narkologicheskaya-clinica-v-voronezhe17.ru

    Marioscene

    30 Oct 25 at 9:52 pm

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

    Diplomi_zoEa

    30 Oct 25 at 9:53 pm

  11. dailyessentialfinds.bond – If you’re linking this, treat it as a “coming soon” site for now.

    Cherlyn Flinck

    30 Oct 25 at 9:54 pm

  12. электрокранизы [url=https://elektrokarniz499.ru/]elektrokarniz499.ru[/url] .

  13. https://vitalpharma24.com/# Kamagra Oral Jelly Deutschland

    Davidjealp

    30 Oct 25 at 9:55 pm

  14. StevenGathe

    30 Oct 25 at 9:58 pm

  15. Kamagra oral jelly France: Vita Homme – Kamagra oral jelly France

    RobertJuike

    30 Oct 25 at 9:59 pm

  16. курс seo [url=www.kursy-seo-12.ru]www.kursy-seo-12.ru[/url] .

    kyrsi seo_evor

    30 Oct 25 at 10:00 pm

  17. диплом автотранспортного техникума купить в [url=www.frei-diplom9.ru/]диплом автотранспортного техникума купить в[/url] .

    Diplomi_hzea

    30 Oct 25 at 10:01 pm

  18. Hello there, I discovered your site via Google while searching for
    a similar subject, your website got here up, it looks great.
    I’ve bookmarked it in my google bookmarks.
    Hi there, simply became alert to your blog through Google, and located that it’s really
    informative. I’m gonna watch out for brussels.
    I will appreciate for those who proceed this in future.

    Numerous people can be benefited from your writing.
    Cheers!

    ankara kürtaj

    30 Oct 25 at 10:02 pm

  19. электрические гардины для штор [url=www.elektrokarniz797.ru]www.elektrokarniz797.ru[/url] .

  20. Bonus exclusif 1xBet pour 2026 : recevez une offre de 100% jusqu’a 130€ lors de votre inscription. Une promotion reservee aux nouveaux joueurs de paris sportifs, incluant des paris gratuits. Rejoignez 1xBet avant le 31 decembre 2026. Le lien ci-dessous vous menera vers le code promo officiel 1xBet > https://astra-hotel.ch/articles/code_promo_1xbet.html.

    Robertinjus

    30 Oct 25 at 10:04 pm

  21. motivilovesmusic.com – If they add more content this could be a great resource for fans.

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

    Diplomi_mpOr

    30 Oct 25 at 10:05 pm

  23. differenza tra Spedra e Viagra: pillole per disfunzione erettile – acquistare Spedra online

    ClydeExamp

    30 Oct 25 at 10:05 pm

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

  25. purebeautytrend.shop – The domain is live, but I found only a simple blog page, no full storefront yet.

    Jude Stonestreet

    30 Oct 25 at 10:06 pm

  26. I like the valuable info you provide in your articles.
    I will bookmark your blog and check again here regularly.
    I’m quite certain I’ll learn lots of new stuff right here!
    Best of luck for the next!

    Polska Bitradex

    30 Oct 25 at 10:06 pm

  27. купить диплом занесением реестр отзывы [url=https://www.frei-diplom2.ru]купить диплом занесением реестр отзывы[/url] .

    Diplomi_rkEa

    30 Oct 25 at 10:06 pm

  28. Code promo sur 1xBet est unique et permet a chaque nouveau joueur de beneficier jusqu’a 100€ de bonus sportif a hauteur de 100% en 2026. Le bonus sera ajoute a votre solde en fonction de votre premier depot, le depot minimum etant fixe a 1€. Pour eviter toute perte de bonus, veillez a copier soigneusement le code depuis la source et a le saisir dans le champ « code promo (si disponible) » lors de l’inscription, afin de preserver l’integrite de la combinaison. D’autres promotions existent en plus du bonus de bienvenue, vous pouvez trouver d’autres offres dans la section « Vitrine des codes promo ». Consultez le lien pour plus d’informations sur les promotions disponibles — https://lanoffashion.com/art/code_promo_179.html.

    Robertinjus

    30 Oct 25 at 10:07 pm

  29. купить диплом кандидата наук [url=rudik-diplom15.ru]купить диплом кандидата наук[/url] .

    Diplomi_avPi

    30 Oct 25 at 10:07 pm

  30. рулонные шторы на окно в кухне [url=http://www.rulonnye-shtory-s-elektroprivodom7.ru]http://www.rulonnye-shtory-s-elektroprivodom7.ru[/url] .

  31. seo интенсив [url=http://kursy-seo-12.ru]http://kursy-seo-12.ru[/url] .

    kyrsi seo_ywor

    30 Oct 25 at 10:08 pm

  32. Где дешево уничтожение рыжих тараканов? Бюджет ограничен.
    дератизация предприятия

    KennethceM

    30 Oct 25 at 10:11 pm

  33. электрокарниз купить в москве [url=http://www.elektrokarniz499.ru]электрокарниз купить в москве[/url] .

  34. A person essentially lend a hand to make critically articles I might state.
    That is the very first time I frequented your website page and
    to this point? I surprised with the research you made to make this actual submit incredible.
    Excellent activity!

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

    KennethceM

    30 Oct 25 at 10:13 pm

  36. trustedleaderscircle.bond – On mobile the site loaded decently although more depth would boost trust.

    Kelsi Klayman

    30 Oct 25 at 10:13 pm

  37. карниз электро [url=https://www.elektrokarniz797.ru]https://www.elektrokarniz797.ru[/url] .

  38. Лечение организовано поэтапно. Такой подход обеспечивает постепенное восстановление функций организма и исключает риск осложнений. Каждый этап терапии направлен на устранение конкретных нарушений, вызванных интоксикацией.
    Детальнее – [url=https://vyvod-iz-zapoya-v-krasnoyarske17.ru/]вывод из запоя на дому недорого в красноярске[/url]

    Ronaldseict

    30 Oct 25 at 10:13 pm

  39. Воспользовался DRINKIO впервые и был приятно удивлён. Курьер приехал вовремя, заказ доставил в целости. Всё упаковано аккуратно, без нареканий. Видно, что сервис работает профессионально и с вниманием к деталям https://drinkio105.ru/catalog/category/vodka/

    Ronaldskada

    30 Oct 25 at 10:13 pm

  40. chery ultra chery tiggo 4 pro

    chery-270

    30 Oct 25 at 10:13 pm

  41. Сколько времени занимает обработка от клопов с гарантией?
    дезинфекция офисов

    KennethceM

    30 Oct 25 at 10:14 pm

  42. кракен официальный сайт
    kraken tor

    JamesDaync

    30 Oct 25 at 10:14 pm

  43. Спасибо за обработка от клопов! Всё чисто и безопасно.
    уничтожение клопов в мебели

    KennethceM

    30 Oct 25 at 10:15 pm

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

    Diplomi_cpOi

    30 Oct 25 at 10:16 pm

  45. Michaelmaync

    30 Oct 25 at 10:16 pm

  46. продвижение обучение [url=http://kursy-seo-12.ru]http://kursy-seo-12.ru[/url] .

    kyrsi seo_kior

    30 Oct 25 at 10:16 pm

  47. как купить диплом техникума официального сайта [url=http://www.frei-diplom9.ru]как купить диплом техникума официального сайта[/url] .

    Diplomi_baea

    30 Oct 25 at 10:16 pm

  48. It’s a shame you don’t have a donate button! I’d without a doubt donate to this fantastic blog!
    I suppose for now i’ll settle for book-marking and adding your RSS
    feed to my Google account. I look forward to fresh updates and will share this site
    with my Facebook group. Chat soon!

    homepage

    30 Oct 25 at 10:17 pm

  49. Заказывал через DRINKIO не раз, и каждый раз доволен скоростью и качеством. Курьеры пунктуальные, доставка надёжная. Ассортимент широкий, сайт интуитивно понятный. Радует, что можно заказать в любое время суток. Сервис стабильно держит уровень и не подводит. Отличная доставка алкоголя на дом по Москве 24/7 https://drinkio105.ru/catalog/category/tabak/

    Ronaldskada

    30 Oct 25 at 10:17 pm

Leave a Reply