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 111,455 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 , , ,

111,455 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. Keep on working, great job!

    boobs

    27 Oct 25 at 3:24 pm

  2. There is certainly a lot to find out about this topic.

    I like all of the points you’ve made.

    Yupoo Burberry

    27 Oct 25 at 3:24 pm

  3. Реабилитация проходит в комфортных условиях, с постоянным наблюдением специалистов. Важным элементом является формирование новых привычек и социальных навыков, что способствует возвращению пациента к полноценной жизни.
    Углубиться в тему – [url=https://narkologicheskaya-clinika-v-nizhnem-novgorode16.ru/]наркологическая клиника стационар нижний новгород[/url]

    Nicolascruby

    27 Oct 25 at 3:25 pm

  4. Нарколог на дом в Челябинске — это услуга, которая позволяет получить профессиональную медицинскую помощь при алкогольной или наркотической интоксикации без необходимости посещения клиники. Такой формат особенно востребован в случаях, когда пациент не может самостоятельно прибыть в медицинское учреждение или нуждается в конфиденциальной помощи. Врач-нарколог выезжает по указанному адресу, проводит осмотр, оценивает состояние и подбирает оптимальную терапию. Квалифицированное вмешательство помогает избежать осложнений и стабилизировать состояние уже в течение первых часов после прибытия специалиста.
    Ознакомиться с деталями – [url=https://narkolog-na-dom-v-chelyabinske16.ru/]частный нарколог на дом[/url]

    JosephMep

    27 Oct 25 at 3:25 pm

  5. Где купить Фенибут в Краснокаменске?Обратите внимание – сайт https://best-kicks.ru
    . Цены нормальные, доставку обещают. Кто-то покупал у них? Как у них с надежностью?

    Stevenref

    27 Oct 25 at 3:26 pm

  6. Awesome post.

    Live Draw Sydney

    27 Oct 25 at 3:27 pm

  7. kraken обмен
    кракен сайт

    Henryamerb

    27 Oct 25 at 3:28 pm

  8. Hey there! Someone in my Myspace group shared this website with
    us so I came to take a look. I’m definitely
    loving the information. I’m book-marking and will be tweeting this to my followers!

    Outstanding blog and superb design.

    pg slot99

    27 Oct 25 at 3:29 pm

  9. https://mannvital.com/# billig Viagra Norge

    Davidjealp

    27 Oct 25 at 3:29 pm

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

    Diplomi_cePi

    27 Oct 25 at 3:30 pm

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

    Diplomi_bmkt

    27 Oct 25 at 3:32 pm

  12. Лечение в клинике в Челябинске строится на принципах конфиденциальности, добровольности и медицинской этики. Врачи применяют доказательные методы терапии, а программы лечения адаптируются под особенности каждого пациента. Работа ведётся комплексно, включая медикаментозную помощь, психотерапию и социальную реабилитацию. Такой подход позволяет эффективно восстановить здоровье и вернуть пациента к нормальной жизни в обществе.
    Углубиться в тему – https://narcologicheskaya-klinika-v-chelyabinske16.ru/chastnaya-narkologicheskaya-klinika-chelyabinsk/

    Jamestug

    27 Oct 25 at 3:33 pm

  13. you can find out more

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

  14. наркологические услуги в москве [url=https://narkologicheskaya-klinika-28.ru/]narkologicheskaya-klinika-28.ru[/url] .

  15. наркологическая служба [url=narkologicheskaya-klinika-25.ru]narkologicheskaya-klinika-25.ru[/url] .

  16. Доставка пиццы в Туле https://pizzacuba.ru горячо и быстро. Классические и авторские рецепты, несколько размеров и бортики с сыром, добавки по вкусу. Онлайн-меню, акции «2 по цене 1», промокоды. Оплата картой/онлайн, бесконтактная доставка, трекинг заказа.

    pizzacuba-939

    27 Oct 25 at 3:36 pm

  17. кракен qr код
    кракен vk4

    Henryamerb

    27 Oct 25 at 3:37 pm

  18. кракен тор
    kraken онлайн

    Henryamerb

    27 Oct 25 at 3:37 pm

  19. rankwebdevelopers.com – Bookmarked this immediately, planning to revisit for updates and inspiration.

    Meta Faries

    27 Oct 25 at 3:38 pm

  20. learnandtrade – Every article feels written with real experience, not just copied theory.

    Dayna Perrot

    27 Oct 25 at 3:38 pm

  21. кракен онион
    kraken

    Henryamerb

    27 Oct 25 at 3:42 pm

  22. Hello would you mind sharing which blog platform you’re using?
    I’m looking to start my own blog soon but I’m having a difficult time deciding between BlogEngine/Wordpress/B2evolution and Drupal.

    The reason I ask is because your design and style seems different then most blogs
    and I’m looking for something completely unique.
    P.S My apologies for getting off-topic but I had to
    ask!

  23. анонимная наркологическая клиника [url=https://narkologicheskaya-klinika-25.ru/]анонимная наркологическая клиника[/url] .

  24. Your means of telling the whole thing in this article is in fact pleasant, every one
    be able to easily know it, Thanks a lot.

    situs bokep

    27 Oct 25 at 3:44 pm

  25. http://vitalpharma24.com/# Erfahrungen mit Kamagra 100mg

    Davidjealp

    27 Oct 25 at 3:45 pm

  26. Доставка пиццы в Туле https://pizzacuba.ru горячо и быстро. Классические и авторские рецепты, несколько размеров и бортики с сыром, добавки по вкусу. Онлайн-меню, акции «2 по цене 1», промокоды. Оплата картой/онлайн, бесконтактная доставка, трекинг заказа.

    pizzacuba-440

    27 Oct 25 at 3:45 pm

  27. Bʏ celebrating tiiny victories underway monitoring, OMT nurtures ɑ
    favorable relationship with mathematics, motivating students fⲟr exam quality.

    Transform math difficulties іnto accomplishments with OMT Math Tuition’ѕ blend of online
    and օn-site choices, ƅacked Ьy a track record ߋf student quality.

    In a ѕystem whеre mathematics education һas aсtually
    evolved tо cultivate innovation and worldwide competitiveness, registering
    in math tuition mаkes ѕure trainees stay ahead by deepening their understanding
    and application of crucial principles.

    Tuition emphasizes heuristic рroblem-solving аpproaches, essential fߋr
    tаking on PSLE’s tough w᧐rd pгoblems that require multiple steps.

    Comprehensive insurance coverage օf the
    entirе O Level curriculum іn tuition mɑkes cеrtain no topics, fгom sets tο vectors,
    ɑre neglected іn a trainee’ѕ alteration.

    Math tuition аt the junior college degree highlights conceptual clarity оvеr rote memorization, іmportant for tackling application-based
    А Level questions.

    OMT’ѕ proprietary curriculum enhances MOE standards tһrough ɑn aⅼl natural approach that nurtures ƅoth scholastic
    skills and an interest fоr mathematics.

    OMT’s online ɑrea offers assistance leh, where yօu ϲan aѕk
    concerns and enhance your understanding for much better grades.

    Math tuitiion builds resilience іn facing difficult
    concerns, ɑ requirement for growing in Singapore’ѕ hіgh-pressure test atmosphere.

    mү web ρage :: secondary 4 math tuition singapore

  28. Nice replies in return of this matter with real arguments and explaining everything on the topic of that.

  29. Доставка пиццы в Туле https://pizzacuba.ru горячо и быстро. Классические и авторские рецепты, несколько размеров и бортики с сыром, добавки по вкусу. Онлайн-меню, акции «2 по цене 1», промокоды. Оплата картой/онлайн, бесконтактная доставка, трекинг заказа.

    pizzacuba-811

    27 Oct 25 at 3:47 pm

  30. Greetings! I know this is kinda off topic but I was wondering which blog platform are you using for this website?
    I’m getting fed up of WordPress because I’ve had problems with hackers
    and I’m looking at options for another platform. I would
    be fantastic if you could point me in the direction of a good platform.

    boyarka

    27 Oct 25 at 3:48 pm

  31. кракен 2025
    kraken онлайн

    Henryamerb

    27 Oct 25 at 3:49 pm

  32. гидроизоляция подвала цена [url=https://gidroizolyaciya-cena-7.ru/]гидроизоляция подвала цена[/url] .

  33. реабилитация зависимых [url=https://narkologicheskaya-klinika-28.ru/]реабилитация зависимых[/url] .

  34. I’ve learn a few good stuff here. Definitely price bookmarking for
    revisiting. I surprise how so much attempt you put to make one
    of these wonderful informative website.

    slot pulsa

    27 Oct 25 at 3:51 pm

  35. наркологическая клиника в москве [url=http://narkologicheskaya-klinika-25.ru]наркологическая клиника в москве[/url] .

  36. Energy Storage Systems https://e7repower.com from E7REPOWER: modular BESS for grid, commercial, and renewable energy applications. LFP batteries, bidirectional inverters, EMS, BMS, fire suppression. 10/20/40 ft containers, scalable to hundreds of MWh. Peak-saving, balancing, and backup. Engineering and service.

    LarryHeP

    27 Oct 25 at 3:53 pm

  37. Доставка пиццы в Туле https://pizzacuba.ru горячо и быстро. Классические и авторские рецепты, несколько размеров и бортики с сыром, добавки по вкусу. Онлайн-меню, акции «2 по цене 1», промокоды. Оплата картой/онлайн, бесконтактная доставка, трекинг заказа.

    pizzacuba-253

    27 Oct 25 at 3:54 pm

  38. купить диплом в миассе [url=www.rudik-diplom12.ru/]купить диплом в миассе[/url] .

    Diplomi_cgPi

    27 Oct 25 at 3:55 pm

  39. где можно купить диплом медицинского колледжа [url=http://frei-diplom10.ru/]http://frei-diplom10.ru/[/url] .

    Diplomi_euEa

    27 Oct 25 at 3:57 pm

  40. кракен вход
    kraken vk3

    Henryamerb

    27 Oct 25 at 3:57 pm

  41. кракен сайт
    kraken онлайн

    Henryamerb

    27 Oct 25 at 3:58 pm

  42. Energy Storage Systems https://e7repower.com from E7REPOWER: modular BESS for grid, commercial, and renewable energy applications. LFP batteries, bidirectional inverters, EMS, BMS, fire suppression. 10/20/40 ft containers, scalable to hundreds of MWh. Peak-saving, balancing, and backup. Engineering and service.

    LarryHeP

    27 Oct 25 at 4:01 pm

  43. Henryamerb

    27 Oct 25 at 4:03 pm

  44. Energy Storage Systems https://e7repower.com from E7REPOWER: modular BESS for grid, commercial, and renewable energy applications. LFP batteries, bidirectional inverters, EMS, BMS, fire suppression. 10/20/40 ft containers, scalable to hundreds of MWh. Peak-saving, balancing, and backup. Engineering and service.

    LarryHeP

    27 Oct 25 at 4:04 pm

  45. клиника вывод из запоя москва [url=https://www.narkologicheskaya-klinika-25.ru]клиника вывод из запоя москва[/url] .

  46. Thanks for finally talking about > PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog < Liked it!

    爹地

    27 Oct 25 at 4:08 pm

  47. подвал дома ремонт [url=https://gidroizolyaciya-podvala-cena.ru]https://gidroizolyaciya-podvala-cena.ru[/url] .

  48. вывод из запоя москва клиника [url=https://www.narkologicheskaya-klinika-28.ru]вывод из запоя москва клиника[/url] .

  49. кракен qr код
    kraken сайт

    Henryamerb

    27 Oct 25 at 4:10 pm

Leave a Reply