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 113,899 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 , , ,

113,899 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. HighRollerMage

    28 Oct 25 at 2:21 pm

  2. Calvindreli

    28 Oct 25 at 2:22 pm

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

    Henryamerb

    28 Oct 25 at 2:23 pm

  4. Calvindreli

    28 Oct 25 at 2:23 pm

  5. Благо им! Биза на высоту https://tuningclass.ru какой выход с 1г ?

    JasonBoomi

    28 Oct 25 at 2:23 pm

  6. Marvinreoky

    28 Oct 25 at 2:24 pm

  7. This is a topic which is near to my heart…
    Best wishes! Where are your contact details though?

    Leger Finvio

    28 Oct 25 at 2:25 pm

  8. LuckyBandit

    28 Oct 25 at 2:25 pm

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

    Diplomi_kjPl

    28 Oct 25 at 2:25 pm

  10. Bryanfloky

    28 Oct 25 at 2:26 pm

  11. Промокод позволяет улучшить предлагаемые условия и получить ещё большую выгоду. Вводить melbet промокод при регистрации 2026 аккаунта или непосредственно перед внесением депозита. При этом все данные в профиле игрока в личном кабинете должны быть заполнены достоверной информацией, иначе это может привести к трудностям при выводе средств. Компания оставляет за собой право проводить различные проверки с целью защититься от недобросовестных действий бетторов (мультиаккаунтинг, бонусхантинг, подложные документы и т.п.). Для получения бонуса в соответствующих полях регистрационной формы клиент сначала должен выбрать его вид (спортивный бонус 100% на первый депозит, казино-бонус, фрибет), а затем указать промокод (при наличии). Также следует подтвердить совершеннолетие и согласие с правилами БК. Если беттор не желает обременять себя отыгрышем бонусных денег, то в ходе регистрации в поле выбора бонуса можно выбрать отметку «Мне не нужен бонус».

    Georgeduh

    28 Oct 25 at 2:26 pm

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

    Henryamerb

    28 Oct 25 at 2:29 pm

  13. Bryanfloky

    28 Oct 25 at 2:30 pm

  14. This game looks amazing! The way it blends that old-school chicken crossing concept with actual consequences is brilliant.
    Count me in!
    Okay, this sounds incredibly fun! Taking that nostalgic
    chicken crossing gameplay and adding real risk?

    I’m totally down to try it.
    This is right up my alley! I’m loving the combo of classic
    chicken crossing mechanics with genuine stakes involved.
    Definitely want to check it out!
    Whoa, this game seems awesome! The mix of that timeless chicken crossing feel with real consequences
    has me hooked. I need to play this!
    This sounds like a blast! Combining that iconic chicken crossing gameplay with actual stakes?
    Sign me up!
    I’m so into this concept! The way it takes that classic chicken crossing vibe and adds legitimate risk
    is genius. Really want to give it a go!
    This game sounds ridiculously fun! That fusion of nostalgic chicken crossing action with real-world stakes has me interested.

    I’m ready to jump in!
    Holy cow, this looks great! Merging that beloved chicken crossing style with tangible consequences?
    I’ve gotta try this out!

  15. Marvinreoky

    28 Oct 25 at 2:32 pm

  16. Presque toutes les robes des femmes arrivaient au niveau du genou ou au-dessus.

    Georgia

    28 Oct 25 at 2:33 pm

  17. ЛідерUA – інформативний портал https://liderua.com новин та корисних порад: актуальні події України, аналітика, життєві лайфхаки та експертні рекомендації. Все — щоб бути в курсі й отримувати практичні рішення для щоденного життя та розвитку.

    IsmaelStics

    28 Oct 25 at 2:33 pm

  18. блог о маркетинге [url=http://statyi-o-marketinge6.ru]блог о маркетинге[/url] .

  19. Wah, in Singapore, a prestigious primary mеans admission to fօrmer students grⲟups, assisting yoսr kid land internships and jobs іn future.

    Goodness, t᧐p primaries honor inventiveness, encouraging neᴡ ventures inn Singapore’s business scene.

    Guardians, fear tһe disparity hor, math groundwork proves critical аt primary school tⲟ grasping figures,
    essential fοr modern online economy.

    Hey hey, Singapore folks, arithmetic гemains perһaps the extremely imⲣortant primary discipline, encouraging
    imagination іn challenge-tackling for groundbreaking careers.

    Ⅾο not mess around lah, combine a good primary school ρlus math excellence to
    assure elevated PSLE reѕults as ԝell ɑs seamless ϲhanges.

    Guardians, fearful ߋf losing style οn lah, solid
    primary mathematics leads t᧐ improved scientific grasp ɑnd tech goals.

    Guardians, dread tһе gap hor, math base гemains
    critical іn primary school in comprehending informаtion, vital foг current tech-driven market.

    Ѕi Ling Primary School оffers а positive setting for
    detailed development.
    Ꭲhe school motivates seⅼf-confidence througһ
    quality guideline.

    Methodist Girls’ School (Primary) empowers ladies ᴡith Methodist worths ɑnd rigor.

    Тhe school promotes leadership ɑnd quality.
    Іt’s a leading option for aⅼl-girls education.

    mү website … Serangoon Garden Secondary School

  20. купить диплом фельдшера [url=rudik-diplom9.ru]купить диплом фельдшера[/url] .

    Diplomi_giei

    28 Oct 25 at 2:37 pm

  21. душевые на заказ из стекла в спб перегородки [url=http://dzen.ru/a/aPaQV60E-3Bo4dfi/]http://dzen.ru/a/aPaQV60E-3Bo4dfi/[/url] .

  22. beste sportwetten Apps (educamosviajando.com) urteil

  23. kraken vpn
    kraken android

    Henryamerb

    28 Oct 25 at 2:37 pm

  24. купить диплом в ноябрьске [url=www.rudik-diplom7.ru]купить диплом в ноябрьске[/url] .

    Diplomi_oaPl

    28 Oct 25 at 2:38 pm

  25. Bryanfloky

    28 Oct 25 at 2:38 pm

  26. кракен vk6
    kraken market

    Henryamerb

    28 Oct 25 at 2:38 pm

  27. l2dkp.com – Found practical insights today; sharing this article with colleagues later.

  28. Наши выездные и стационарные бригады работают по принципу «одна корректировка за раз». Меняем не всё и сразу, а ровно один параметр — темп инфузии, очередность модулей или поведенческий якорь (свет/тишина/питьевой режим). Затем в заранее оговорённый момент проверяем эффект по фактам: переносимость воды малыми глотками, вариабельность ЧСС к сумеркам, латентность сна, число ночных пробуждений, субъективная ясность утром. Такая дисциплина устраняет хаос и снижает потребность «усиливать» терапию «на всякий случай».
    Выяснить больше – http://narkologicheskaya-klinika-saratov0.ru/klinika-narkologii-saratov/

    Williamweith

    28 Oct 25 at 2:40 pm

  29. vqscvasavtzqpsj.shop – Bookmarked this immediately, planning to revisit for updates and inspiration.

    Michale Mccraig

    28 Oct 25 at 2:40 pm

  30. Цифровая экономика формирует будущее сайт kraken darknet kraken онион kraken онион тор кракен онион

    RichardPep

    28 Oct 25 at 2:41 pm

  31. spartanwebsolution.com – Content reads clearly, helpful examples made concepts easy to grasp.

    Doug Dejarnette

    28 Oct 25 at 2:41 pm

  32. ЛідерUA – інформативний портал https://liderua.com новин та корисних порад: актуальні події України, аналітика, життєві лайфхаки та експертні рекомендації. Все — щоб бути в курсі й отримувати практичні рішення для щоденного життя та розвитку.

    IsmaelStics

    28 Oct 25 at 2:41 pm

  33. Эта статья предлагает захватывающий и полезный контент, который привлечет внимание широкого круга читателей. Мы постараемся представить тебе идеи, которые вдохновят вас на изменения в жизни и предоставят практические решения для повседневных вопросов. Читайте и вдохновляйтесь!
    Обратитесь за информацией – https://doodhghar.com/hello-world

    Martinkem

    28 Oct 25 at 2:42 pm

  34. душевое ограждение матовое стекло [url=www.dzen.ru/a/aPaQV60E-3Bo4dfi/]www.dzen.ru/a/aPaQV60E-3Bo4dfi/[/url] .

  35. кракен Россия
    кракен сайт

    Henryamerb

    28 Oct 25 at 2:43 pm

  36. [url=https://mydiv.net/arts/view-TOP-5-luchshih-servisov-virtualnyh-nomerov-dlya-SMS-aktivaciy-v-2026-godu.html]аренда номера[/url]

    Briantar

    28 Oct 25 at 2:43 pm

  37. Hey there, I think your site might be having browser compatibility issues.

    When I look at your blog in Firefox, it looks fine but when opening in Internet Explorer, it
    has some overlapping. I just wanted to give you a quick heads up!
    Other then that, superb blog!

    dewa scatter

    28 Oct 25 at 2:43 pm

  38. pok01.live – Bookmarked this immediately, planning to revisit for updates and inspiration.

    Jonah Presha

    28 Oct 25 at 2:44 pm

  39. ЛідерUA – інформативний портал https://liderua.com новин та корисних порад: актуальні події України, аналітика, життєві лайфхаки та експертні рекомендації. Все — щоб бути в курсі й отримувати практичні рішення для щоденного життя та розвитку.

    IsmaelStics

    28 Oct 25 at 2:44 pm

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

  41. купить диплом в ухте [url=www.rudik-diplom13.ru]купить диплом в ухте[/url] .

    Diplomi_khon

    28 Oct 25 at 2:45 pm

  42. продвижение сайтов интернет магазины в москве [url=https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru/]продвижение сайтов интернет магазины в москве[/url] .

  43. Marvinreoky

    28 Oct 25 at 2:46 pm

  44. [url=https://elektrokarnizy-dlya-shtor-moskva.ru/]электро карниз[/url] позволяют управлять шторами с помощью одного нажатия кнопки, обеспечивая удобство и комфорт в вашем доме.
    Автоматические карнизы с электроприводом становятся всё более популярными в современных интерьере.

  45. Thankfulness to my father who informed me regarding this web site, this web site is in fact remarkable.

    ankara kürtaj

    28 Oct 25 at 2:47 pm

  46. купить диплом для иностранцев [url=http://rudik-diplom7.ru/]купить диплом для иностранцев[/url] .

    Diplomi_bzPl

    28 Oct 25 at 2:49 pm

  47. kraken 2025
    кракен тор

    Henryamerb

    28 Oct 25 at 2:49 pm

  48. ЛідерUA – інформативний портал https://liderua.com новин та корисних порад: актуальні події України, аналітика, життєві лайфхаки та експертні рекомендації. Все — щоб бути в курсі й отримувати практичні рішення для щоденного життя та розвитку.

    IsmaelStics

    28 Oct 25 at 2:50 pm

  49. Bryanfloky

    28 Oct 25 at 2:52 pm

  50. Marvinreoky

    28 Oct 25 at 2:52 pm

Leave a Reply