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 98,101 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 , , ,

98,101 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=https://alloopt.ru]https://alloopt.ru[/url]

    Спасибо за внимание! Надеюсь, вам было интересно.

    fixRow

    20 Oct 25 at 2:35 am

  2. купить диплом в рубцовске [url=https://rudik-diplom15.ru/]https://rudik-diplom15.ru/[/url] .

    Diplomi_tuPi

    20 Oct 25 at 2:36 am

  3. Bullish on $MTAUR coin for its referral and vesting perks. ICO phase’s low entry beats later prices. Whimsical gameplay hooks you instantly.
    minotaurus ico

    WilliamPargy

    20 Oct 25 at 2:36 am

  4. уколы от алкоголя на дому [url=https://narkolog-na-dom-1.ru/]https://narkolog-na-dom-1.ru/[/url] .

  5. Капельница от похмелья в Нижнем Новгороде — доступная и эффективная процедура для снятия симптомов интоксикации. Стоимость услуги начинается от 2?100??.
    Разобраться лучше – [url=https://vyvod-iz-zapoya-nizhnij-novgorod12.ru/]наркологический вывод из запоя в нижний новгороде[/url]

    Miltondiolo

    20 Oct 25 at 2:38 am

  6. 1win uz kazino [url=https://1win5510.ru]https://1win5510.ru[/url]

    1win_uz_yksi

    20 Oct 25 at 2:40 am

  7. диплом колледжа купить в екатеринбурге [url=http://frei-diplom11.ru]http://frei-diplom11.ru[/url] .

    Diplomi_jhsa

    20 Oct 25 at 2:41 am

  8. платный наркологический стационар [url=http://www.narkologicheskaya-klinika-20.ru]http://www.narkologicheskaya-klinika-20.ru[/url] .

  9. купить диплом техникума до 1996 года [url=https://frei-diplom9.ru]купить диплом техникума до 1996 года[/url] .

    Diplomi_rbea

    20 Oct 25 at 2:42 am

  10. kraken официальный
    кракен Москва

    JamesDaync

    20 Oct 25 at 2:43 am

  11. купить диплом электрика [url=www.rudik-diplom6.ru]купить диплом электрика[/url] .

    Diplomi_gfKr

    20 Oct 25 at 2:43 am

  12. купить диплом в ельце [url=https://rudik-diplom7.ru/]https://rudik-diplom7.ru/[/url] .

    Diplomi_arPl

    20 Oct 25 at 2:44 am

  13. Celebrate your achievements: finishing a winning bet on our website [url=https://praqrado.com/download-the-1xbet-app-for-an-unmatched-betting/]https://praqrado.com/download-the-1xbet-app-for-an-unmatched-betting/[/url] money will be automatically transferred to balance.

    Allisonken

    20 Oct 25 at 2:45 am

  14. нарколог психолог [url=http://narkologicheskaya-klinika-20.ru/]http://narkologicheskaya-klinika-20.ru/[/url] .

  15. 1вин ios приложение [url=https://www.1win5510.ru]https://www.1win5510.ru[/url]

    1win_uz_yesi

    20 Oct 25 at 2:48 am

  16. В Сочи стационар клиники «Детокс» предлагает комплексный вывод из запоя. Пациентам обеспечивают комфорт, безопасность и круглосуточный контроль.
    Углубиться в тему – [url=https://vyvod-iz-zapoya-sochi23.ru/]вывод из запоя на дому круглосуточно в сочи[/url]

    Gordontrive

    20 Oct 25 at 2:48 am

  17. диплом колледжа купить диплом юриста [url=http://frei-diplom9.ru/]http://frei-diplom9.ru/[/url] .

    Diplomi_nkea

    20 Oct 25 at 2:48 am

  18. купить диплом техникума в самаре [url=https://frei-diplom8.ru/]купить диплом техникума в самаре[/url] .

    Diplomi_ebsr

    20 Oct 25 at 2:49 am

  19. В «Частном Медике 24» в Самаре выход из запоя организуют поэтапно: диагностика, лечение, реабилитация.
    Разобраться лучше – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]нарколог вывод из запоя в стационаре[/url]

    GilbertCoeby

    20 Oct 25 at 2:51 am

  20. куплю диплом высшего образования [url=www.rudik-diplom7.ru/]куплю диплом высшего образования[/url] .

    Diplomi_whPl

    20 Oct 25 at 2:53 am

  21. right here on 9signal

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

  22. прогнозы на спорт с аналитикой [url=http://prognozy-ot-professionalov4.ru/]http://prognozy-ot-professionalov4.ru/[/url] .

  23. купить диплом в саранске [url=rudik-diplom6.ru]купить диплом в саранске[/url] .

    Diplomi_rwKr

    20 Oct 25 at 2:54 am

  24. 1win [url=http://1win5510.ru]http://1win5510.ru[/url]

    1win_uz_jjsi

    20 Oct 25 at 2:56 am

  25. Scale your operations safely! An antidetect browser is engineered specifically for multi-account management, allowing you to run separate profiles for social media, ads, or e-commerce without any cross-linking risk.

    DouglasJasse

    20 Oct 25 at 2:57 am

  26. купить диплом фармацевта [url=http://rudik-diplom3.ru/]купить диплом фармацевта[/url] .

    Diplomi_raei

    20 Oct 25 at 2:57 am

  27. диплом жд техникума купить в [url=http://frei-diplom8.ru/]диплом жд техникума купить в[/url] .

    Diplomi_nhsr

    20 Oct 25 at 2:57 am

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

    Diplomi_owOl

    20 Oct 25 at 2:59 am

  29. купить диплом вуза [url=https://rudik-diplom7.ru/]купить диплом вуза[/url] .

    Diplomi_fzPl

    20 Oct 25 at 2:59 am

  30. купить украинский диплом техникума [url=https://frei-diplom11.ru]купить украинский диплом техникума[/url] .

    Diplomi_iasa

    20 Oct 25 at 2:59 am

  31. кракен vk5
    кракен vk6

    JamesDaync

    20 Oct 25 at 3:00 am

  32. Scale your operations safely! An antidetect browser is engineered specifically for multi-account management, allowing you to run separate profiles for social media, ads, or e-commerce without any cross-linking risk.

    DouglasJasse

    20 Oct 25 at 3:00 am

  33. Anthonycam

    20 Oct 25 at 3:01 am

  34. potenzmittel cialis: PotenzVital – cialis generika

    RaymondNit

    20 Oct 25 at 3:02 am

  35. проект перепланировки стоимость москва [url=https://proekt-pereplanirovki-kvartiry11.ru/]https://proekt-pereplanirovki-kvartiry11.ru/[/url] .

  36. cialis 20 mg achat en ligne: livraison rapide et confidentielle – cialis sans ordonnance

    JosephPseus

    20 Oct 25 at 3:02 am

  37. новости хоккея [url=http://sportivnye-novosti-2.ru]новости хоккея[/url] .

  38. Kaizenaire.ⅽom leads tһе pack іn curating deals f᧐r Singapore’s smart shoppers.

    In Singapore’ѕ heart, shopping paradise ɡrows оn deals that thrill its people.

    Scuba diving journeys tо nearby islands excitement underwater travelers
    from Singapore, and bear іn mind to remɑin updated on Singapore’ѕ neѡest promotions and shopping deals.

    Rye mɑkes easy females’ѕ clothing, valued by casual style enthusiasts in Singapore
    fߋr tһeir relaxed үеt stylish designs.

    Fraser and Neave creates drinks ⅼike 100PᒪUЅ аnd F&N cordials lor, cherished Ƅy Singaporeans fоr thеіr refreshing drinks Ԁuring heat leh.

    SaladStop! assembles fresh salads ɑnd wraps, treasured ƅy fitness enthusiasts fօr personalized, nutritious meals ᧐n the fly.

    Ꭰon’t Ƅe obsoleted leh, Kaizenaire.ϲom updates with nwwest discounts оne.

    Feel free tօ visit my һomepage – Kaizenaire Promotions

  39. Refresh Renovation Southwest Charlotte
    1251 Arrow Piine Ɗr c121,
    Charlotte, NC 28273, United Ѕtates
    +19803517882
    Project renovation management

  40. В Краснодаре клиника «Детокс» предлагает услугу выезда нарколога на дом. Быстро, безопасно, анонимно.
    Получить дополнительную информацию – [url=https://narkolog-na-dom-krasnodar27.ru/]врач нарколог на дом[/url]

    DanielNus

    20 Oct 25 at 3:05 am

  41. Стационарное лечение запоя в Воронеже помогает быстрее восстановить силы и вернуть ясность мышления.
    Узнать больше – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh22.ru/]вывод из запоя в стационаре в воронеже[/url]

    RichardJuids

    20 Oct 25 at 3:06 am

  42. Halo teman-teman! Artikel ini informatif dan mudah diikuti.

    Buat yang mencari platform gaming dengan desain elegan dan fitur lengkap, saya rekomendasikan King7.

    Selain punya reputasi bagus dan banyak dipakai, mereka juga
    rutin kasih promo berjalan dengan proteksi kuat sehingga main terasa aman.

    Aksesnya ringkas, navigasi intuitif, dan performa stabil.

    Yang ingin cek bisa ke king7.

    Terima kasih untuk kontennya; sukses selalu untuk blog ini!

    king7

    20 Oct 25 at 3:06 am

  43. 1вин лайв ставки [url=https://1win5510.ru/]https://1win5510.ru/[/url]

    1win_uz_zfsi

    20 Oct 25 at 3:06 am

  44. Thanks very interesting blog!

  45. I visited various web pages however the audio feature for audio songs present at this web page is actually wonderful.

  46. Great delivery. Sound arguments. Keep up the amazing work.

    man with a van

    20 Oct 25 at 3:08 am

  47. [url=https://jili-bet.hashnode.dev/]jili casino[/url] or betting?

    Joshuahic

    20 Oct 25 at 3:09 am

  48. диплом с внесением в реестр купить [url=https://www.frei-diplom3.ru]диплом с внесением в реестр купить[/url] .

    Diplomi_vuKt

    20 Oct 25 at 3:09 am

  49. частные наркологические клиники в москве [url=www.narkologicheskaya-klinika-20.ru]www.narkologicheskaya-klinika-20.ru[/url] .

Leave a Reply