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 114,355 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 , , ,

114,355 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. Драгон Мани – идеальный выбор для азарта! Захватывающие игры,
    бонусы и быстрые выплаты. Получи максимум эмоций и выигрывай с удовольствием!
    драгон мани вход

    Jordanpiony

    28 Oct 25 at 7:02 pm

  2. заказать продвижение сайта в москве [url=www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]заказать продвижение сайта в москве[/url] .

  3. Казино Mellstroy – это море азарта и удачи! Яркие игры,
    щедрые акции и быстрые выплаты. Погрузитесь в мир азартных
    эмоций и наслаждайтесь каждым моментом
    слоты мелстроя

    Sammyfag

    28 Oct 25 at 7:04 pm

  4. Драгон Мани казино – азарт и удача! Увлекательные игры,
    щедрые бонусы, мгновенные выплаты. Погрузись в мир эмоций и выигрывай!
    драгон мани вход

    Alvinlor

    28 Oct 25 at 7:07 pm

  5. If you are going for finest contents like me, only go to see this
    site daily for the reason that it offers feature contents, thanks

  6. кракен
    кракен vk5

    Henryamerb

    28 Oct 25 at 7:08 pm

  7. kraken РФ
    kraken сайт

    Henryamerb

    28 Oct 25 at 7:09 pm

  8. блог про продвижение сайтов [url=http://www.statyi-o-marketinge6.ru]блог про продвижение сайтов[/url] .

  9. Казино Mellstroy – это море азарта и удачи! Яркие игры,
    щедрые акции и быстрые выплаты. Погрузитесь в мир азартных
    эмоций и наслаждайтесь каждым моментом
    казино мелстрой

    Sammyfag

    28 Oct 25 at 7:10 pm

  10. I have been browsing on-line more than three hours as of late, yet I never found any interesting article like yours.
    It is beautiful worth enough for me. In my opinion, if all webmasters
    and bloggers made just right content material as you probably did,
    the net will likely be a lot more useful than ever before.

  11. urbanwearstudio – Customer contact or support info appears accessible, which builds trust.

    Joyce Harwood

    28 Oct 25 at 7:12 pm

  12. Драгон Мани – ваш надежный партнер в мире азарта!
    Увлекательные игры, щедрые бонусы и моментальные выплаты!
    промокоды и фриспины dragon money

    Aaronbrume

    28 Oct 25 at 7:13 pm

  13. блог про seo [url=statyi-o-marketinge7.ru]блог про seo[/url] .

  14. кракен 2025
    кракен 2025

    Henryamerb

    28 Oct 25 at 7:14 pm

  15. Промокод – небольшая цифробуквенная комбинация, которая дает право на получение каких-то привилегий и бонусов. Система промокодов позволяет букмекерским конторам привлекать новых пользователей, поощрять их регистрацию и пополнение счета, поэтому эта схема удобна как букмекерам, так и пользователям. Вводя промокод мелбет на сегодня 2026 и другие бонусы для первых ставок. Обычно ввод промокода не представляет особой сложности. На сайте букмекера при регистрации будет отведено специальное поле для ввода кодовой комбинации. При выполнении всех условий компании, предоставляющей бонус, код начинает действовать сразу после ввода. Дополнительная активация не требуется. В этом случае есть свои особенности, о которых будет рассказано далее.

    Georgeduh

    28 Oct 25 at 7:15 pm

  16. купить диплом штукатура [url=rudik-diplom7.ru]rudik-diplom7.ru[/url] .

    Diplomi_twPl

    28 Oct 25 at 7:16 pm

  17. AU88️Link Đăng Ký – Đăng Nhập AU88.com Uy Tín An Toàn +88K
    AU88 là sân chơi cá cược trực tuyến đẳng cấp.
    Được cấp phép hoạt động bởi PAGCOR – tổ chức quản lý uy tín tại Philippines.

    Sở hữu nền tảng công nghệ hiện đại, giao diện thân thiện, thao tác
    dễ dàng cùng kho trò chơi đa dạng như cá cược thể
    thao, casino online, xổ số, đá gà, nổ hũ… Và hàng nghìn game hấp dẫn khác.
    AU88 cam kết mang đến cho người chơi trải nghiệm an toàn tuyệt đối.
    https://sdwi.sa.com/

    au88

    28 Oct 25 at 7:16 pm

  18. Calvindreli

    28 Oct 25 at 7:17 pm

  19. imaginelearnexplore – Navigation seems smooth and product categories appear well organized.

    Denny Hawf

    28 Oct 25 at 7:18 pm

  20. Calvindreli

    28 Oct 25 at 7:18 pm

  21. Драгон Мани – ваш надежный партнер в мире азарта!
    Увлекательные игры, щедрые бонусы и моментальные выплаты!
    драгон мани зеркало рабочее

    Aaronbrume

    28 Oct 25 at 7:18 pm

  22. Hello my family member! I want to say that this post is amazing, great
    written and include approximately all vital infos. I would like to see extra posts like
    this .

  23. I don’t even know the way I stopped up right here,
    however I believed this post used to be good. I don’t realize who you might be but certainly you are going to
    a famous blogger for those who aren’t already. Cheers!

  24. kraken tor
    kraken сайт

    Henryamerb

    28 Oct 25 at 7:20 pm

  25. Оптические нивелиры – это геодезические инструменты, предназначенные для определения превышений между точками на земной поверхности и создания горизонтальных линий визирования. Они широко используются в строительстве, геодезии,
    землеустройстве и других областях, где требуется точное измерение высот. Подскажите каким должен быть качественный [url=https://crimeaguide.com/forum/viewtopic.php?f=5&t=16278]оптический нивелир[/url]

    Tanyalig

    28 Oct 25 at 7:23 pm

  26. блог seo агентства [url=https://www.statyi-o-marketinge6.ru]https://www.statyi-o-marketinge6.ru[/url] .

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

    Diplomi_kdPl

    28 Oct 25 at 7:25 pm

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

  29. мелбет букмекерская контора [url=http://melbetofficialsite.ru]мелбет букмекерская контора[/url] .

    bk melbet_qdEa

    28 Oct 25 at 7:27 pm

  30. Chơi tại BJ39 Việt Nam và trải nghiệm cờ bạc
    trực tuyến tốt nhất: slot, casino trực tiếp, sportsbook và
    tiền thưởng hấp dẫn hàng ngày.

  31. кракен маркет
    kraken vk3

    Henryamerb

    28 Oct 25 at 7:29 pm

  32. kraken marketplace
    кракен сайт

    Henryamerb

    28 Oct 25 at 7:30 pm

  33. продвижение в google [url=https://www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]https://www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru[/url] .

  34. Nice blog here! Also your web site loads up very fast! What web
    host are you using? Can I get your affiliate link to your host?
    I wish my web site loaded up as fast as yours lol

  35. официальный сайт бк мелбет [url=www.melbetofficialsite.ru/]официальный сайт бк мелбет[/url] .

    bk melbet_dsEa

    28 Oct 25 at 7:32 pm

  36. discoverandcreate – I’ll bookmark this store for when I’m looking for creative, unique finds.

    Rudy Solonar

    28 Oct 25 at 7:32 pm

  37. материалы по seo [url=https://statyi-o-marketinge6.ru/]материалы по seo[/url] .

  38. 1go casino

    28 Oct 25 at 7:32 pm

  39. ts ровный беру уже давно унего но 35ф реально слабый эфект трафы сделал 10к1 неочом в итоги из 50г сделал 300гр основ нармально вышло по качиству пока ещё ещё некто не рыгал( но вопщем неплохо цена соответствует качиству 400р за грам норм https://mediclever.ru Закупал я рег у Тс конечно качество пацаны просто бомба:good: Я токого не когда не пробывал!!!

    JasonBoomi

    28 Oct 25 at 7:33 pm

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

    Diplomi_tqPl

    28 Oct 25 at 7:33 pm

  41. куплю диплом цена [url=http://www.rudik-diplom13.ru]куплю диплом цена[/url] .

    Diplomi_rjon

    28 Oct 25 at 7:33 pm

  42. Lightening agents that lighten your teeth can frequently momentarily aggravate the
    periodontals.

    Hildred

    28 Oct 25 at 7:33 pm

  43. radio with cd player and alarm clock [url=https://alarm-radio-clocks.com/]https://alarm-radio-clocks.com/[/url] .

  44. блог seo агентства [url=http://www.statyi-o-marketinge6.ru]http://www.statyi-o-marketinge6.ru[/url] .

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

    Diplomi_bnKr

    28 Oct 25 at 7:37 pm

  46. кракен маркет
    кракен

    Henryamerb

    28 Oct 25 at 7:37 pm

  47. Обожаю сайт казино онлайн, он очень понятный
    в использовании!
    рейтинг онлайн казино

  48. web site menyediakan layanan link daftar
    akun slot gacor dengan sistem cepat dan aman. Situs ini
    sudah dikenal luas sebagai tempat terbaik untuk bermain slot online gampang maxwin, karena
    menghadirkan berbagai game dengan RTP tinggi dan tingkat kemenangan yang stabil.

    web site

    28 Oct 25 at 7:39 pm

  49. В процессе лечения используются проверенные методики, которые в комплексе обеспечивают положительный эффект и снижают риск рецидива.
    Исследовать вопрос подробнее – [url=https://lechenie-alkogolizma-omsk0.ru/]принудительное лечение от алкоголизма в омске[/url]

    BradleyGeali

    28 Oct 25 at 7:39 pm

  50. Такая структура делает лечение последовательным и предсказуемым, повышая шансы на положительный исход.
    Подробнее тут – https://narkologicheskaya-klinika-v-omske0.ru/chastnaya-narkologicheskaya-klinika-omsk

    FloydVop

    28 Oct 25 at 7:39 pm

Leave a Reply