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 86,854 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 , , ,

86,854 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. urbanshift – Great mix of visuals and text, doesn’t feel overwhelming.

    Joana Quander

    12 Oct 25 at 10:41 pm

  2. RandyEluse

    12 Oct 25 at 10:41 pm

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

    Diplomi_jbEa

    12 Oct 25 at 10:44 pm

  4. купить диплом техникума настоящий [url=https://www.frei-diplom8.ru]купить диплом техникума настоящий[/url] .

    Diplomi_pbsr

    12 Oct 25 at 10:44 pm

  5. Glucophage hilft bei der Kontrolle des Blutzuckerspiegels. Es ist besonders in Online-Apotheken aus Indien oft gunstiger erhaltlich.
    Paraplatin

    ThomasInvag

    12 Oct 25 at 10:46 pm

  6. powercore – Found a few tips I can implement immediately, thanks!

    Fatima Bartle

    12 Oct 25 at 10:47 pm

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

    Diplomi_rxOi

    12 Oct 25 at 10:47 pm

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

    Diplomi_eaPl

    12 Oct 25 at 10:48 pm

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

    Diplomi_zaea

    12 Oct 25 at 10:48 pm

  10. novaorbit – Navigation feels smooth, didn’t struggle exploring the sections.

    Wilda Brannon

    12 Oct 25 at 10:49 pm

  11. primeimpact – Clean design, smooth navigation, very easy to explore.

    Chery Santomauro

    12 Oct 25 at 10:50 pm

  12. куплю диплом медсестры в москве [url=http://frei-diplom13.ru]куплю диплом медсестры в москве[/url] .

    Diplomi_hokt

    12 Oct 25 at 10:52 pm

  13. Cabinet IQ Austin
    8305 Ѕtate Hwyy 71 #110, Austin,
    TX 78735, United Ꮪtates
    +12542755536
    Trends

    Trends

    12 Oct 25 at 10:56 pm

  14. 1win az bank transfer [url=http://1win5004.com/]http://1win5004.com/[/url]

    1win_bvoi

    12 Oct 25 at 10:56 pm

  15. перепланировка нежилого помещения [url=www.aktivnoe.forum24.ru/?1-9-0-00001303-000-0-0/]www.aktivnoe.forum24.ru/?1-9-0-00001303-000-0-0/[/url] .

    pereplanirovka v nejilom zdanii_qfKi

    12 Oct 25 at 10:57 pm

  16. диплом лесной колледж ухта купить [url=https://www.frei-diplom9.ru]https://www.frei-diplom9.ru[/url] .

    Diplomi_nuea

    12 Oct 25 at 10:58 pm

  17. купить диплом в чапаевске [url=https://rudik-diplom2.ru]купить диплом в чапаевске[/url] .

    Diplomi_qnpi

    12 Oct 25 at 11:00 pm

  18. Bullish on Minotaurus ICO’s community. $MTAUR’s boosts strategic. Market growth aligns.
    mtaur token

    WilliamPargy

    12 Oct 25 at 11:00 pm

  19. urbannexus – Found several new ideas I hadn’t thought of before.

    Ludivina Huckle

    12 Oct 25 at 11:01 pm

  20. купить диплом в камышине [url=http://www.rudik-diplom7.ru]купить диплом в камышине[/url] .

    Diplomi_zgPl

    12 Oct 25 at 11:02 pm

  21. Дизайнерский ремонт: искусство преображения пространства

    Дизайн интерьера играет важную роль в создании комфортной и уютной атмосферы в доме. Сегодня мы поговорим о таком понятии, как дизайнерский ремонт, который позволяет превратить обычное жилье в уникальное пространство, отражающее индивидуальность владельца.
    [url=https://designapartment.ru ]дизайнерский ремонт под ключ москва[/url]
    Что такое дизайнерский ремонт?

    Дизайнерский ремонт — это комплекс работ, направленных на создание оригинального дизайна помещения. Это не просто обновление отделки, а полноценный творческий процесс, включающий разработку концепции, подбор материалов и мебели, а также реализацию проекта.

    Ключевые особенности дизайнерского ремонта:
    [url=https://designapartment.ru ]дизайнерский ремонт комнатной квартиры москва[/url]
    – Индивидуальный подход к каждому проекту.
    – Использование качественных материалов и современных технологий.
    – Создание уникального стиля, соответствующего вкусам заказчика.
    – Оптимизация пространства для максимального комфорта и функциональности.

    Виды дизайнерских ремонтов
    [url=https://designapartment.ru]дизайнерский ремонт квартиры под ключ[/url]
    Существует несколько видов дизайнерских ремонтов, каждый из которых имеет свои особенности и преимущества.

    #1 Дизайнерский ремонт квартиры

    Это наиболее распространенный вид ремонта, подходящий для тех, кто хочет обновить интерьер своей городской квартиры. Специалисты разрабатывают проект, учитывая размеры помещений, пожелания клиента и бюджет. Такой ремонт включает перепланировку, замену коммуникаций, отделочные работы и декорирование.

    Пример дизайна: светлая гостиная с панорамными окнами, минималистичный дизайн кухни и спальни в стиле лофт.

    #2 Дизайнерский ремонт дома

    Такой ремонт предполагает полное преобразование жилого дома, начиная от фундамента и заканчивая крышей. Здесь важно учитывать архитектурные особенности здания, климатические условия региона и предпочтения владельцев. Часто используется экодизайн, натуральные материалы и энергосберегающие технологии.

    Пример дизайна: просторный холл с камином, стеклянная веранда с видом на сад, спальня в пастельных тонах.

    #3 Дизайнерский ремонт виллы

    Ремонт вилл требует особого подхода, поскольку такие объекты часто расположены в живописных местах и имеют большую площадь. Важно сохранить гармонию с окружающей средой, используя природные материалы и цвета. Особое внимание уделяется созданию зон отдыха, бассейнов и садов.

    Пример дизайна: роскошная вилла с бассейном, открытая терраса с видами на море, спальная зона в тропическом стиле.

    #4 Дизайнерский ремонт коттеджа

    Коттедж отличается от обычного дома наличием придомового участка и возможностью организации дополнительных функциональных зон. Ремонт коттеджей включает работу над фасадом, ландшафтом и внутренним пространством. Стили могут варьироваться от классики до хай-тека.

    Пример дизайна: двухэтажный коттедж с мансардой, гостиная-столовая в скандинавском стиле, детская комната с игровой зоной.

    #5 Дизайнерский ремонт пентхауса

    Пентхаус — это элитное жилье, расположенное на верхних этажах зданий с панорамными видами. Для такого типа недвижимости характерны высокие потолки, большие окна и эксклюзивные элементы декора. Проектирование пентхауса требует учета особенностей конструкции здания и пожеланий клиентов относительно приватности и удобства.

    Пример дизайна: современный пентхаус с открытой планировкой, кабинет с видом на город, зона отдыха с джакузи.

    Заключение

    Дизайнерский ремонт — это возможность создать идеальное пространство для жизни и отдыха. Независимо от того, хотите ли вы обновить квартиру, дом, виллу, коттедж или пентхаус, профессиональный подход гарантирует вам комфорт и эстетическое удовольствие на долгие годы.
    дизайнерский ремонт дома под ключ москва
    https://designapartment.ru

    GarrettPaync

    12 Oct 25 at 11:02 pm

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

    Diplomi_bbea

    12 Oct 25 at 11:03 pm

  23. перепланировка нежилого помещения [url=http://mymoscow.forum24.ru/?1-6-0-00034012-000-0-0-1759746919]http://mymoscow.forum24.ru/?1-6-0-00034012-000-0-0-1759746919[/url] .

    pereplanirovka v nejilom zdanii_frKi

    12 Oct 25 at 11:03 pm

  24. Just swapped BNB for $MTAUR—smooth on BSC. Referral rewards motivate sharing. Game’s power-ups via tokens strategic.
    minotaurus token

    WilliamPargy

    12 Oct 25 at 11:04 pm

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

    Diplomi_aaOi

    12 Oct 25 at 11:04 pm

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

    Diplomi_xdkt

    12 Oct 25 at 11:05 pm

  27. order ED pills online UK: British online pharmacy Viagra – buy viagra

    Brettesofe

    12 Oct 25 at 11:05 pm

  28. перепланировка в нежилом здании [url=http://www.aktivnoe.forum24.ru/?1-9-0-00001303-000-0-0]http://www.aktivnoe.forum24.ru/?1-9-0-00001303-000-0-0[/url] .

    pereplanirovka v nejilom zdanii_roKi

    12 Oct 25 at 11:06 pm

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

    Diplomi_yhEa

    12 Oct 25 at 11:07 pm

  30. RandyEluse

    12 Oct 25 at 11:08 pm

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

    Diplomi_xqsr

    12 Oct 25 at 11:09 pm

  32. Prednisolone tablets UK online [url=http://medreliefuk.com/#]Prednisolone tablets UK online[/url] UK chemist Prednisolone delivery

    Jameshoasy

    12 Oct 25 at 11:10 pm

  33. I go to see daily some sites and sites to read articles or reviews,
    however this web site presents feature based writing.

    Kasey

    12 Oct 25 at 11:10 pm

  34. Hi there, I do believe your blog could possibly be having browser compatibility issues.

    Whenever I take a look at your site in Safari, it looks fine however when opening in I.E., it has some overlapping issues.

    I just wanted to give you a quick heads up! Other than that, excellent
    site!

    Excellent

    12 Oct 25 at 11:11 pm

  35. купить диплом парикмахера [url=www.rudik-diplom2.ru/]купить диплом парикмахера[/url] .

    Diplomi_nmpi

    12 Oct 25 at 11:12 pm

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

    Diplomi_ghOi

    12 Oct 25 at 11:12 pm

  37. Good blog you’ve got here.. It’s hard to find quality writing like yours nowadays.
    I seriously appreciate individuals like you! Take care!!

    content creation

    12 Oct 25 at 11:13 pm

  38. можно купить диплом медсестры [url=www.frei-diplom13.ru]можно купить диплом медсестры[/url] .

    Diplomi_nekt

    12 Oct 25 at 11:15 pm

  39. Hi superb website! Does running a blog such as this take a great deal of work?

    I have absolutely no understanding of computer programming however I was
    hoping to start my own blog soon. Anyhow, if you have any recommendations or tips for new blog owners please share.
    I know this is off topic nevertheless I simply
    had to ask. Thank you!

  40. Click at pastelink.net

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

  41. купить диплом с реестром цена [url=https://frei-diplom2.ru]купить диплом с реестром цена[/url] .

    Diplomi_sxEa

    12 Oct 25 at 11:17 pm

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

    Diplomi_gbOi

    12 Oct 25 at 11:17 pm

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

    Diplomi_ousr

    12 Oct 25 at 11:18 pm

  44. 1win [url=http://1win5005.com/]http://1win5005.com/[/url]

    1win_yaml

    12 Oct 25 at 11:18 pm

  45. можно купить диплом медсестры [url=http://frei-diplom13.ru]можно купить диплом медсестры[/url] .

    Diplomi_uwkt

    12 Oct 25 at 11:26 pm

  46. [url=https://madcasino.ru]https://madcasino.ru[/url]

    ThomasPaf

    12 Oct 25 at 11:26 pm

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

    Diplomi_bcPl

    12 Oct 25 at 11:27 pm

  48. где купить диплом колледжа омск [url=frei-diplom9.ru]frei-diplom9.ru[/url] .

    Diplomi_qoea

    12 Oct 25 at 11:28 pm

Leave a Reply