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 91,412 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 , , ,

91,412 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=kuhni-spb-2.ru]kuhni-spb-2.ru[/url] .

    kyhni spb_dlmn

    15 Oct 25 at 7:54 pm

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

  3. потолки натяжные в нижнем новгороде [url=www.stretch-ceilings-nizhniy-novgorod.ru]www.stretch-ceilings-nizhniy-novgorod.ru[/url] .

  4. Строительный портал https://v-stroit.ru всё о строительстве, ремонте и архитектуре. Полезные советы, технологии, материалы, новости отрасли и практические инструкции для мастеров и новичков.

    Rogerzok

    15 Oct 25 at 7:57 pm

  5. AndrewKam

    15 Oct 25 at 7:59 pm

  6. организация трансляций [url=zakazat-onlayn-translyaciyu.ru]организация трансляций[/url] .

  7. вывод из запоя круглосуточно краснодар
    narkolog-krasnodar016.ru
    вывод из запоя

  8. Modern Purair
    201, 1475 Ellis Street, Kelowna
    BC Ꮩ1Y 2A3, Canada
    1-800-996-3878
    Social programs

    Social programs

    15 Oct 25 at 8:06 pm

  9. mexico pharmacy [url=https://medicosur.shop/#]mexican pharmacy[/url] mexican pharmacy

    CareyMag

    15 Oct 25 at 8:07 pm

  10. организация трансляции [url=www.zakazat-onlayn-translyaciyu1.ru]организация трансляции[/url] .

  11. Heya i’m for the first time here. I found this board and I find It really
    useful & it helped me out a lot. I hope to give something back and help others like you helped me.

  12. потолочкин натяжные потолки нижний новгород официальный сайт [url=stretch-ceilings-nizhniy-novgorod.ru]stretch-ceilings-nizhniy-novgorod.ru[/url] .

  13. What’s up to all, the contents present at this site are in fact awesome for people experience,
    well, keep up the good work fellows.

  14. Выданные бесплатные вращения работают в конкретном автомате.

  15. buy amoxil [url=http://zencaremeds.com/#]ZenCare Meds com[/url] buy amoxil

    CareyMag

    15 Oct 25 at 8:17 pm

  16. netmatrix.click – I’m impressed with load times, images pop in very quickly.

    Tequila Janoski

    15 Oct 25 at 8:19 pm

  17. глория мебель [url=kuhni-spb-2.ru]kuhni-spb-2.ru[/url] .

    kyhni spb_mdmn

    15 Oct 25 at 8:20 pm

  18. организация онлайн трансляции конференции [url=http://zakazat-onlayn-translyaciyu.ru]http://zakazat-onlayn-translyaciyu.ru[/url] .

  19. кухни на заказ в спб [url=https://kuhni-spb-1.ru/]https://kuhni-spb-1.ru/[/url] .

    kyhni spb_cgmi

    15 Oct 25 at 8:22 pm

  20. Thanks for finally writing about > PHP hook, building hooks in your
    application – Sjoerd Maessen blog at Sjoerd Maessen blog < Loved it!

  21. Steventib

    15 Oct 25 at 8:24 pm

  22. купить кухню на заказ в спб [url=www.kuhni-spb-2.ru]www.kuhni-spb-2.ru[/url] .

    kyhni spb_zjmn

    15 Oct 25 at 8:25 pm

  23. Hi, yeah this post is truly fastidious and I have learned lot
    of things from it about blogging. thanks.

  24. rankflow.click – The typography is sharp and easy on the eyes throughout.

    Rayford Hammet

    15 Oct 25 at 8:25 pm

  25. 1win bonus kodu [url=http://1win5004.com/]http://1win5004.com/[/url]

    1win_ajoi

    15 Oct 25 at 8:26 pm

  26. webpulse.click – The visuals are crisp and the load speed is pretty solid.

    Marion Lagrant

    15 Oct 25 at 8:26 pm

  27. Так вот, прошло все как всегда отлично, дошло за три дня, маскировка надежная. Так же отдельное спасибо магазину за проявление немыслимой заботы о безопасности клиента. Что имел ввиду писать не буду, но факт есть факт.
    https://telegra.ph/Dji-osmo-action-kupit-v-moskve-10-13-2
    пацаны магаз ровный пишу это уже не раз всегда списываюсь с менеджером все делает ровно и качество и оперативность , всегда заказываю и буду заказывать тут т.к. не париться за качество продукта как в других магазах!!!

    MichaelViess

    15 Oct 25 at 8:27 pm

  28. Приобрести диплом университета поможем. Купить диплом в России, предлагает наша компания – [url=http://diplomybox.com//]diplomybox.com/[/url]

    Cazrvpp

    15 Oct 25 at 8:28 pm

  29. заказать трансляцию [url=zakazat-onlayn-translyaciyu1.ru]заказать трансляцию[/url] .

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

  31. потолочкин потолки [url=https://stretch-ceilings-nizhniy-novgorod.ru/]https://stretch-ceilings-nizhniy-novgorod.ru/[/url] .

  32. You’ve made some really good points there. I looked on the internet for additional
    information about the issue and found most people will go along with your views on this site.

    index

    15 Oct 25 at 8:30 pm

  33. Excited about $MTAUR’s potential in the $14.78B gaming sector. Presale perks like value appreciation are drawing me. Game’s minotaur hero is iconic.
    minotaurus coin

    WilliamPargy

    15 Oct 25 at 8:31 pm

  34. https://tadalifepharmacy.com/# TadaLife Pharmacy

    Hermandug

    15 Oct 25 at 8:33 pm

  35. Врач уточняет, как долго продолжается запой, какой алкоголь употребляется, а также наличие сопутствующих заболеваний. Этот тщательный анализ позволяет оперативно подобрать оптимальные методы детоксикации и снизить риск осложнений.
    Разобраться лучше – [url=https://vyvod-iz-zapoya-tula0.ru/]вывод из запоя на дому тула[/url]

    JeffreyBoync

    15 Oct 25 at 8:33 pm

  36. When some one searches for his necessary thing, thus he/she
    needs to be available that in detail, so that thing is maintained over here.

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

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

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

    Ключевые особенности дизайнерского ремонта:

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

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

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

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

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

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

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

    Пример дизайна: просторный холл с камином, стеклянная веранда с видом на сад, спальня в пастельных тонах.
    [url=https://designapartment.ru]дизайнерский ремонт под ключ[/url]
    #3 Дизайнерский ремонт виллы

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

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

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

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

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

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

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

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

    Заключение

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

    https://designapartment.ru
    дизайнерский ремонт комнатной квартиры москва

    WayneTut

    15 Oct 25 at 8:35 pm

  38. pixelpush.click – Really enjoying the visual style, it gives a fresh and clean impression.

    Guillermo Trenkle

    15 Oct 25 at 8:35 pm

  39. аренда студии для записи подкаста [url=https://studiya-podkastov-spb.ru]аренда студии для записи подкаста[/url] .

  40. sitefoundry.click – Just browsed this site, it’s clean and the layout feels intuitive.

    Antonia Paulshock

    15 Oct 25 at 8:39 pm

  41. sport bild wetten

    Also visit my website … neue wettanbieter (Deanna)

    Deanna

    15 Oct 25 at 8:40 pm

  42. discreet ED pills delivery in the US: discreet ED pills delivery in the US – tadalafil tablets without prescription

    AndrewPal

    15 Oct 25 at 8:41 pm

  43. потолочкин натяжные [url=http://www.stretch-ceilings-nizhniy-novgorod.ru]http://www.stretch-ceilings-nizhniy-novgorod.ru[/url] .

  44. May I simply say what a relief to discover somebody that truly understands what
    they are discussing over the internet. You certainly know how to bring an issue
    to light and make it important. More people must check
    this out and understand this side of the story. I was surprised that you
    are not more popular since you most certainly have the gift.

  45. Kennethhep

    15 Oct 25 at 8:44 pm

  46. кухни на заказ в спб от производителя [url=http://kuhni-spb-1.ru/]http://kuhni-spb-1.ru/[/url] .

    kyhni spb_yimi

    15 Oct 25 at 8:46 pm

  47. Link kln

    fgsifidld

    15 Oct 25 at 8:47 pm

  48. потолочник потолки [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru]https://natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .

  49. It’s remarkable to go to see this website and reading the views of all friends concerning this paragraph, while I am also keen of getting familiarity.

     slut 

    15 Oct 25 at 8:47 pm

Leave a Reply