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 102,245 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 , , ,

102,245 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=http://top-10-seo-prodvizhenie.ru/]сайтов продвижение в топ[/url] .

  2. топ digital агентств москвы [url=https://luchshie-digital-agencstva.ru]https://luchshie-digital-agencstva.ru[/url] .

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

    Diplomi_ngea

    22 Oct 25 at 2:15 am

  4. продвижение сайтов поисковых системах москва [url=https://reiting-seo-agentstv-moskvy.ru/]reiting-seo-agentstv-moskvy.ru[/url] .

  5. Excited for Minotaurus presale’s 80% off deal. $MTAUR’s in-game boosts edge-giving. Community vibrant.
    minotaurus token

    WilliamPargy

    22 Oct 25 at 2:17 am

  6. Пользуюсь DRINKIO регулярно и всегда остаюсь доволен. Всё работает стабильно: сайт удобный, курьеры пунктуальные, доставка быстрая. Очень удобно, что можно заказать в любое время суток. Радует внимательность сотрудников и аккуратность упаковки. Настоящий сервис премиум-класса – https://drinkio105.ru/

    Arthurtok

    22 Oct 25 at 2:17 am

  7. I am genuinely pleased to glance at this website posts which includes
    lots of helpful facts, thanks for providing such statistics.

  8. Hello there, I discovered your website by means of Google while looking for a
    related topic, your website came up, it looks good.
    I’ve bookmarked it in my google bookmarks.

    Hello there, simply changed into alert to your blog thru Google, and found that it is truly informative.
    I am gonna be careful for brussels. I will be grateful if you happen to continue this in future.
    Numerous other folks might be benefited out of your writing.
    Cheers!

    chumba casino

    22 Oct 25 at 2:18 am

  9. Wah lao, regardless whetһer school iѕ high-еnd, maths is the critical topic f᧐r building confidence іn figures.

    Οh no, primary math instructs practical ᥙseѕ like budgeting, so
    guarantee your kid masters tһat right from young.

    Hwa Chong Institution Junior College іs renowned for іts integrated program tһat perfectly combines scholastic rigor
    wіth character development, producing worldwide scholars
    ɑnd leaders. Woгld-class facilities ɑnd professional professors support quality іn rеsearch study, entrepreneurship,
    ɑnd bilingualism. Students tаke advantage of
    extensive international exchanges and competitions, broadening ⲣoint of
    views and sharpening skills. Ꭲhe institution’ѕ concentrate on innovation and service cultivates durability ɑnd ethical values.
    Alumni networks ⲟpen doors to top universities and prominent careers worldwide.

    Jurong Pioneer Junior College, developed
    tһrough thе thoughtful merger of Jurong Junior College ɑnd Pioneer
    Junior College, delivers ɑ progressive аnd future-oriented education that positions ɑ unique
    emphasis оn China readiness, international service acumen, ɑnd cross-cultural engagement tⲟ prepare
    trainees for prospering іn Asia’ѕ vibrant financial landscape.
    Tһe college’s dual schools аre outfitted ᴡith modern, versatile centers including specialized commerce simulation гooms,
    science innovation labs, and arts ateliers, ɑll developed tⲟ
    foster useful skills, creativity, ɑnd interdisciplinary knowing.

    Improving academic programs ɑre matched Ьy international partnerships,
    ѕuch as joint tasks witһ Chinese universities and cultural
    immersion journeys, whih boost trainees’ linguistic efficiency ɑnd international outlook.
    Α helpful and inclusive community atmosphere encourages durability аnd management
    advancement tһrough a large range of ϲo-curricular activities, fгom entrepreneurship ϲlubs to sports teams thɑt promote team effort аnd determination. Graduates
    ᧐f Jurong Pioneer Junior College ɑre remarkably ԝell-prepared
    fοr competitive professions, embodying tһe worths of care, constant
    enhancement, ɑnd development that specify tһe institution’s
    forward-ⅼooking values.

    Goodness, no matter tһough establishment proves fancy,
    math acts ⅼike the critical topic in developing assurance іn numbers.

    Alas, primary mathematics instructs practical սses suϲh aѕ money management,
    tһus ensure yօur youngster masters this properly fгom
    early.

    Aiyo, wіthout solid math ɑt Junior College,
    еven prestigious school children mаy stumble ԝith next-level calculations,
    tһerefore cultivate tһat promⲣtly leh.

    Folks, fearful ᧐f losing mode engaged lah, strong primary
    mathematics leads іn better STEM grasp plus engineering goals.

    Wow, math acts like the foundation block of primary
    schooling, aiding children foг dimensional thinking foг
    design paths.

    Kiasu mindset іn JC turns pressure into A-level motivation.

    Οһ no, primary math instructs real-ԝorld implementations including
    financial planning, ѕo guarantee уouг
    kid grasps tһis right from еarly.

    Here iѕ my blog post: River Valley High School

  10. сео продвижение компания [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]сео продвижение компания[/url] .

  11. рейтинг digital агентств москвы [url=http://luchshie-digital-agencstva.ru/]рейтинг digital агентств москвы[/url] .

  12. сео продвижение заказать москва [url=https://reiting-seo-agentstv-moskvy.ru]https://reiting-seo-agentstv-moskvy.ru[/url] .

  13. Minotaurus token’s ecosystem ties game, DAO, and rewards seamlessly. ICO phase is buzzing with partnerships forming. As a gamer, I’m all in on this maze adventure.
    minotaurus presale

    WilliamPargy

    22 Oct 25 at 2:25 am

  14. кракен онлайн
    кракен android

    JamesDaync

    22 Oct 25 at 2:26 am

  15. empresas seo [url=https://www.reiting-seo-agentstv.ru]empresas seo[/url] .

  16. услуги по продвижению сайта в поисковых системах [url=www.reiting-runeta-seo.ru/]услуги по продвижению сайта в поисковых системах[/url] .

  17. кракен актуальная ссылка
    кракен вход

    JamesDaync

    22 Oct 25 at 2:27 am

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

    Diplomi_czea

    22 Oct 25 at 2:27 am

  19. оптимизация и продвижение сайтов москва [url=www.seo-prodvizhenie-reiting-kompanij.ru]www.seo-prodvizhenie-reiting-kompanij.ru[/url] .

  20. рейтинг агентств digital услуг [url=http://luchshie-digital-agencstva.ru]http://luchshie-digital-agencstva.ru[/url] .

  21. продвижение сайтов в поисковых системах [url=www.reiting-runeta-seo.ru]продвижение сайтов в поисковых системах[/url] .

  22. Капельница от запоя в Нижнем Новгороде — процедура, направленная на детоксикацию организма и восстановление нормального самочувствия. Она включает в себя введение препаратов, способствующих выведению токсинов и восстановлению функций органов.
    Изучить вопрос глубже – [url=https://vyvod-iz-zapoya-nizhnij-novgorod11.ru/]вывод из запоя капельница в нижний новгороде[/url]

    Norbertavoig

    22 Oct 25 at 2:31 am

  23. В Сочи стационар клиники «Детокс» предлагает комплексный вывод из запоя. Пациентам обеспечивают комфорт, безопасность и круглосуточный контроль.
    Разобраться лучше – [url=https://vyvod-iz-zapoya-sochi24.ru/]вывод из запоя на дому круглосуточно[/url]

    DavidExarl

    22 Oct 25 at 2:33 am

  24. диплом жд техникума купить [url=https://frei-diplom10.ru/]диплом жд техникума купить[/url] .

    Diplomi_ikEa

    22 Oct 25 at 2:34 am

  25. obhruse

    22 Oct 25 at 2:34 am

  26. продвижение сайтов поисковых системах москва [url=https://reiting-seo-agentstv-moskvy.ru]https://reiting-seo-agentstv-moskvy.ru[/url] .

  27. kraken вход
    kraken сайт

    JamesDaync

    22 Oct 25 at 2:34 am

  28. Hello There. I discovered your weblog the use of msn. That is a very well written article.
    I will make sure to bookmark it and come back to read extra of your helpful information. Thanks for
    the post. I will certainly return.

    MDX document file

    22 Oct 25 at 2:35 am

  29. DRINKIO порадовал оперативностью и качеством. Курьеры приезжают вовремя, заказ всегда полный и аккуратно упакован. Ассортимент впечатляет, есть и популярные бренды, и редкие позиции. Очень удобно, что сервис работает круглосуточно. Заказываю уже не первый раз — всегда доволен. Надёжная доставка алкоголя на дом по Москве https://drinkio105.ru/

    Arthurtok

    22 Oct 25 at 2:36 am

  30. рейтинг seo агентств [url=http://www.luchshie-digital-agencstva.ru]рейтинг seo агентств[/url] .

  31. Несколько раз заказывал через DRINKIO, и всегда всё на высшем уровне. Ассортимент впечатляет, есть всё — от популярных напитков до редких позиций. Курьеры вежливые, всегда звонят заранее. Особенно радует, что доставка круглосуточная, выручает в любое время суток. Очень удобный и надёжный сервис: https://drinkio105.ru/

    Arthurtok

    22 Oct 25 at 2:37 am

  32. компании занимающиеся продвижением сайтов [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .

  33. сео москва [url=https://seo-prodvizhenie-reiting-kompanij.ru/]сео москва[/url] .

  34. seo services ranking [url=https://top-10-seo-prodvizhenie.ru]https://top-10-seo-prodvizhenie.ru[/url] .

  35. сео продвижение сайтов 10 [url=http://www.reiting-runeta-seo.ru]http://www.reiting-runeta-seo.ru[/url] .

  36. top seo company [url=http://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]http://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .

  37. В Екатеринбурге служба Stop-Alko круглосуточно помогает вывести из запоя на дому — быстро, анонимно и без постановки на учёт.
    Узнать больше – [url=https://vyvod-iz-zapoya-ekaterinburg27.ru/]наркология вывод из запоя[/url]

    DannyLox

    22 Oct 25 at 2:41 am

  38. best seo professional [url=top-10-seo-prodvizhenie.ru]best seo professional[/url] .

  39. продвижение сайтов по россии [url=www.reiting-seo-agentstv.ru/]www.reiting-seo-agentstv.ru/[/url] .

  40. купить диплом в новочебоксарске [url=https://www.rudik-diplom1.ru]https://www.rudik-diplom1.ru[/url] .

    Diplomi_cmer

    22 Oct 25 at 2:41 am

  41. Я считаю, что Вы допускаете ошибку. Могу отстоять свою позицию. Пишите мне в PM, поговорим.
    you will work on deep integration with payment providers, card processing operators and international systems to ensure serviceable functioning of [url=https://www.pocket-option.co.in]Pockett Option[/url] for corporate clients.

    Chrisfap

    22 Oct 25 at 2:42 am

  42. Здравствуйте!
    многомерное пространство и время
    Полная информация по ссылке – https://www.gada.su/2025/09/blog-post_20.html
    История человечеста, [url=https://www.gada.su/2025/09/blog-post_19.html]Атмосфера венеры[/url], История человечеста
    Удачи и успехов в жизни и саморазвитии!

    JamesTipsy

    22 Oct 25 at 2:42 am

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

    Diplomi_arMt

    22 Oct 25 at 2:42 am

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

    Diplomi_gqKt

    22 Oct 25 at 2:43 am

  45. Клиника «Похмельная служба» в Нижнем Новгороде предлагает комплексное лечение запоя с использованием капельницы. Наши специалисты проводят диагностику и назначают индивидуальный план лечения.
    Подробнее можно узнать тут – https://vyvod-iz-zapoya-nizhnij-novgorod13.ru

    StevenLat

    22 Oct 25 at 2:43 am

  46. рейтинг рекламных агентств россии [url=www.luchshie-digital-agencstva.ru]рейтинг рекламных агентств россии[/url] .

  47. Для восстановления после запоя выбирайте стационар клиники «Детокс» в Сочи. Здесь пациентам обеспечивают качественную помощь и поддержку на каждом этапе.
    Подробнее тут – [url=https://vyvod-iz-zapoya-sochi22.ru/]вывод из запоя недорого в сочи[/url]

    MichaelMak

    22 Oct 25 at 2:44 am

  48. кракен клиент
    kraken tor

    JamesDaync

    22 Oct 25 at 2:44 am

  49. seo продвижение корпоративных сайтов в москве [url=https://reiting-seo-agentstv-moskvy.ru]seo продвижение корпоративных сайтов в москве[/url] .

  50. казань купить диплом техникума [url=https://frei-diplom9.ru]казань купить диплом техникума[/url] .

    Diplomi_dlea

    22 Oct 25 at 2:47 am

Leave a Reply