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 107,254 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 , , ,

107,254 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. 1x giri? [url=https://www.1xbet-7.com]https://www.1xbet-7.com[/url] .

    1xbet_gxol

    24 Oct 25 at 10:35 pm

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

    Diplomi_mukt

    24 Oct 25 at 10:35 pm

  3. диплом об окончании педагогического колледжа купить [url=https://frei-diplom11.ru]https://frei-diplom11.ru[/url] .

    Diplomi_absa

    24 Oct 25 at 10:36 pm

  4. где купить диплом техникума кого [url=www.frei-diplom12.ru/]где купить диплом техникума кого[/url] .

    Diplomi_soPt

    24 Oct 25 at 10:36 pm

  5. 555win – Sân Chơi Hoàn Hảo Cho Người Yêu Thích Đặt Cược
    555win – Cơn lốc mới trên bản đồ giải trí trực tuyến 2025, hứa hẹn khuấy đảo cộng đồng cược thủ yêu
    thích sự đẳng cấp và đổi mới. Đây,
    là điểm đến lý tưởng cho người chơi tìm kiếm cơ hội làm giàu, là biểu tượng cho xu hướng cá cược thời đại mới.

    555win

    24 Oct 25 at 10:37 pm

  6. Если в «окно оценки» прогресс ниже ожиданий, мы меняем ровно один параметр — дозировку, время приёма, приоритет модуля — и задаём новую дату проверки. Это защищает от «снежного кома» назначений и сохраняет ощущение контроля у пациента.
    Ознакомиться с деталями – http://narkologicheskaya-klinika-petrozavodsk0.ru/narkolog-petrozavodsk-otzyvy/

    ByronPaype

    24 Oct 25 at 10:38 pm

  7. Hi, I do believe this is a great blog. I stumbledupon it 😉 I may return yet again since I saved as a favorite it.
    Money and freedom is the greatest way to change, may you be rich and
    continue to help other people.

    join jihad

    24 Oct 25 at 10:38 pm

  8. Viagra generico con pagamento sicuro: Viagra generico online Italia – Medi Uomo

    Jesuskax

    24 Oct 25 at 10:38 pm

  9. Its not my first time to go to see this site, i am visiting this web page
    dailly and get fastidious facts from here every day.

  10. A motivating discussion is worth comment. I do think that you ought to publish more
    about this issue, it might not be a taboo subject but typically folks don’t talk about these issues.
    To the next! Many thanks!!

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

    Diplomi_alOi

    24 Oct 25 at 10:39 pm

  12. Howdy everyone… Wanted to show you a fun and exciting content from this site . Fun and engaging for fellow forum members . The quality is excellent and it covers trending content. I’ve been watching many of their videos lately, and it seems right up your alley. You won’t regret watching.

    Also visit my page https://thetranny.com/search/cum-swallow-compilation/

    homepage

    24 Oct 25 at 10:40 pm

  13. click through the up coming web page

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

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

    Diplomi_vsKr

    24 Oct 25 at 10:42 pm

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

    Diplomi_wzpi

    24 Oct 25 at 10:42 pm

  16. купить диплом колледжа отзывы [url=frei-diplom12.ru]frei-diplom12.ru[/url] .

    Diplomi_ihPt

    24 Oct 25 at 10:43 pm

  17. купить оригинальный диплом техникума [url=https://frei-diplom11.ru/]купить оригинальный диплом техникума[/url] .

    Diplomi_jzsa

    24 Oct 25 at 10:47 pm

  18. купить диплом в брянске [url=http://rudik-diplom2.ru]купить диплом в брянске[/url] .

    Diplomi_bqpi

    24 Oct 25 at 10:47 pm

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

    Diplomi_jtOi

    24 Oct 25 at 10:48 pm

  20. Такая структура лечения помогает пациентам пройти все этапы восстановления под контролем специалистов.
    Выяснить больше – https://narcologicheskaya-klinika-perm0.ru/

    StevenThalt

    24 Oct 25 at 10:48 pm

  21. 1 xbet giri? [url=https://www.1xbet-7.com]https://www.1xbet-7.com[/url] .

    1xbet_uwol

    24 Oct 25 at 10:49 pm

  22. 1x bet giri? [url=https://www.1xbet-9.com]https://www.1xbet-9.com[/url] .

    1xbet_gqSn

    24 Oct 25 at 10:49 pm

  23. Kinetic Staking lets crypto enthusiasts earn rewards by securely staking their digital
    assets. Kinetic staking crypto offers an easy, reliable way to grow your holdings while supporting blockchain networks safely
    and efficiently.

  24. 1xbwt giri? [url=https://1xbet-4.com]https://1xbet-4.com[/url] .

    1xbet_adol

    24 Oct 25 at 10:50 pm

  25. apotek online utan recept [url=https://mannensapotek.com/#]MannensApotek[/url] Sildenafil-tabletter pris

    Davidduese

    24 Oct 25 at 10:51 pm

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

    Diplomi_axon

    24 Oct 25 at 10:51 pm

  27. bahis siteler 1xbet [url=http://1xbet-giris-3.com]http://1xbet-giris-3.com[/url] .

    1xbet giris_nhMi

    24 Oct 25 at 10:52 pm

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

    Diplomi_qnPt

    24 Oct 25 at 10:53 pm

  29. купить диплом в благовещенске [url=https://www.rudik-diplom6.ru]купить диплом в благовещенске[/url] .

    Diplomi_noKr

    24 Oct 25 at 10:53 pm

  30. It’s really very difficult in this busy life to listen news on TV, thus I simply use world wide web for
    that reason, and get the most up-to-date news.

  31. Команда «КарелМед Центра» объединяет наркологов, психиатров, реаниматологов, клинических психологов, специалистов по реабилитации и социальному сопровождению. Мы работаем без очередей и навязчивых формальностей, а логистика визита, оформление в стационар и коммуникации с родственниками выстроены бережно: конфиденциальные записи, немаркированные выезды, отдельный вход и нейтральная терминология в документах. Вы получаете не только купирование абстиненции и детоксикацию, но и системную работу с триггерами, привычками и межличностными конфликтами — тем, что часто возвращает к употреблению даже после «идеальных капельниц».
    Получить дополнительные сведения – [url=https://narkologicheskaya-klinika-petrozavodsk0.ru/]наркологическая клиника нарколог[/url]

    Rodneynew

    24 Oct 25 at 10:55 pm

  32. It’s very straightforward to find out any topic on web
    as compared to books, as I found this article at this web page.

  33. Где купить Амфетамин в Самаре?Обратил внимание на сайт https://lordfilmsh24.ru
    – судя по отзывам ок. Цены адекватные, курьерская доставка. Кто-то пользовался? Насколько хороший товар?

    Stevenref

    24 Oct 25 at 10:58 pm

  34. moesboardwalk.com – The design is clean and the layout keeps things simple and uncluttered.

    Genny Krzyston

    24 Oct 25 at 11:00 pm

  35. WilliamJet

    24 Oct 25 at 11:02 pm

  36. диплом техникума старого образца до 1996 г купить [url=https://frei-diplom11.ru]диплом техникума старого образца до 1996 г купить[/url] .

    Diplomi_ursa

    24 Oct 25 at 11:02 pm

  37. купить проведенный диплом всеми [url=https://frei-diplom1.ru/]купить проведенный диплом всеми[/url] .

    Diplomi_ceOi

    24 Oct 25 at 11:06 pm

  38. 1xbet lite [url=http://www.1xbet-9.com]http://www.1xbet-9.com[/url] .

    1xbet_ziSn

    24 Oct 25 at 11:07 pm

  39. купить диплом в энгельсе [url=https://rudik-diplom6.ru/]https://rudik-diplom6.ru/[/url] .

    Diplomi_lpKr

    24 Oct 25 at 11:07 pm

  40. купить диплом в керчи [url=rudik-diplom15.ru]rudik-diplom15.ru[/url] .

    Diplomi_ptPi

    24 Oct 25 at 11:08 pm

  41. Great post. I was checking continuously this blog
    and I’m impressed! Extremely helpful information specially the last part :
    ) I care for such info much. I was seeking this particular information for a long time.
    Thank you and good luck.

  42. 1xbet g?ncel adres [url=1xbet-4.com]1xbet-4.com[/url] .

    1xbet_yuol

    24 Oct 25 at 11:09 pm

  43. 16 числа заказала товарчика)ну пока еще ничего не получила!!! продаван отправил только половинку(объяснил что не хватило реактивчика) но все остальное вышлет как привезут 100ый ))ждем и надеемся)) заказывала и раньше в этом магазе все было ОГОНЬ)) https://e-med-academy.ru Есть, но пока что временно не работает.

    LeonardHOX

    24 Oct 25 at 11:10 pm

  44. Каждый план лечения строится вокруг понятных целей и измеримых результатов. Вместо шаблонных «сильных» схем мы применяем минимально достаточную фармакотерапию, корректируем среду (свет, тишина, режим сна), учим пациента простым и повторяемым навыкам саморегуляции. Такое сочетание медицинских и психологических инструментов помогает быстрее снять острые симптомы и поддерживать стабильность в последующие недели. Кодирование мы рассматриваем не как «волшебную кнопку», а как часть маршрута, который всегда включает детокс, психообразование и профилактику срывов.
    Выяснить больше – http://narkologicheskaya-klinika-nizhnij-tagil0.ru

    Bryanler

    24 Oct 25 at 11:10 pm

  45. Pretty nice post. I simply stumbled upon your blog and wanted to
    say that I’ve truly loved surfing around your weblog posts.
    In any case I’ll be subscribing for your feed and I’m hoping you write once more very soon!

  46. Right now it sounds like Expression Engine is the best
    blogging platform out there right now. (from what I’ve read) Is that what you are
    using on your blog?

    seo course

    24 Oct 25 at 11:11 pm

Leave a Reply