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 101,812 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 , , ,

101,812 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. Ich bin suchtig nach Lowen Play Casino, es verstromt eine Spielstimmung, die wie eine Savanne tobt. Die Casino-Optionen sind vielfaltig und kraftvoll, mit einzigartigen Casino-Slotmaschinen. Die Casino-Mitarbeiter sind schnell wie ein Gepard, ist per Chat oder E-Mail erreichbar. Auszahlungen im Casino sind schnell wie ein Raubkatzen-Sprint, trotzdem mehr regelma?ige Casino-Boni waren ein Volltreffer. Kurz gesagt ist Lowen Play Casino ein Casino, das man nicht verpassen darf fur Fans moderner Casino-Slots! Zusatzlich die Casino-Oberflache ist flussig und strahlt wie ein Sonnenaufgang, was jede Casino-Session noch wilder macht.
    lГ¶wen play meppen Г¶ffnungszeiten|

    zappysquirrel3zef

    21 Oct 25 at 9:13 pm

  2. Где купить Лирику в Жукове?Смотрите, что нашел – сайт https://myturtime.ru
    . Цены приличные, есть доставка. Может, кто-то тестил у них? Как с качеством?

    Stevenref

    21 Oct 25 at 9:15 pm

  3. агентство seo [url=https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]агентство seo[/url] .

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

  5. cloudfiles.tech – The site has a sleek, modern layout and the navigation is intuitive and smooth.

    Ali Brisbone

    21 Oct 25 at 9:17 pm

  6. сео продвижение москва [url=www.seo-prodvizhenie-reiting-kompanij.ru/]сео продвижение москва[/url] .

  7. как купить легальный диплом [url=https://www.frei-diplom2.ru]https://www.frei-diplom2.ru[/url] .

    Diplomi_uyEa

    21 Oct 25 at 9:17 pm

  8. shop-in.tech – Just visited the website, the layout is clean and browsing was quite smooth.

    Marge Hauswald

    21 Oct 25 at 9:18 pm

  9. buildyourdreambrand – Loved the examples of branding projects—they made things much more tangible.

    Robbin Rochell

    21 Oct 25 at 9:18 pm

  10. Клиника «Детокс» в Сочи предлагает услугу вывода из запоя в стационаре. Под наблюдением профессиональных врачей пациент получит необходимую медицинскую помощь и поддержку. Услуга доступна круглосуточно, анонимно и начинается от 2000 ?.
    Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-sochi22.ru/]наркология вывод из запоя сочи[/url]

    MichaelMak

    21 Oct 25 at 9:18 pm

  11. Мы обеспечиваем быстрое и безопасное восстановление после длительного употребления алкоголя.
    Получить дополнительную информацию – http://vyvod-iz-zapoya-nizhnij-novgorod13.ru

    StevenLat

    21 Oct 25 at 9:20 pm

  12. Hello my friend! I want to say that this post is awesome,
    nice written and come with approximately all vital infos.
    I would like to look extra posts like this .

    AYUTOGEL

    21 Oct 25 at 9:21 pm

  13. промокод 1xBet все актуальные акции и бонусы собраны на одной странице

    Aaronawads

    21 Oct 25 at 9:22 pm

  14. seo москва [url=http://www.reiting-seo-agentstv-moskvy.ru]seo москва[/url] .

  15. топ seo продвижение низкие цены [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/[/url] .

  16. Bullish on $MTAUR coin for its referral and vesting perks. ICO phase’s low entry beats later prices. Whimsical gameplay hooks you instantly.
    minotaurus token

    WilliamPargy

    21 Oct 25 at 9:25 pm

  17. диджитал агентства москвы [url=www.luchshie-digital-agencstva.ru]диджитал агентства москвы[/url] .

  18. сео оптимизация заказать [url=https://reiting-runeta-seo.ru/]сео оптимизация заказать[/url] .

  19. Sildenafil side effects and safe dosage: Blue Peak Meds – how generic Viagra works in the body

    AnthonySep

    21 Oct 25 at 9:27 pm

  20. seo agents [url=https://reiting-seo-kompanii.ru/]seo agents[/url] .

  21. рейтинг компаний по продвижению сайтов [url=www.luchshie-digital-agencstva.ru/]рейтинг компаний по продвижению сайтов[/url] .

  22. medtronik.ru подборка бонусов и акций для новых пользователей

    Aaronawads

    21 Oct 25 at 9:30 pm

  23. https://medivertraut.shop/# Viagra Generika online kaufen ohne Rezept

    LanceHek

    21 Oct 25 at 9:30 pm

  24. лучший seo продвижение [url=https://reiting-seo-agentstv.ru]https://reiting-seo-agentstv.ru[/url] .

  25. russian seo [url=https://reiting-seo-agentstv.ru]https://reiting-seo-agentstv.ru[/url] .

  26. Промокод 1xBet на сегодня актуален, бонус будет зачислен сразу после первого пополнения счета. Временные коды. Букмекерская контора 1xBet часто выступает спонсором при переводе популярных сериалов на русский язык. Рекламные вставки букмекера можно услышать перед началом многих сериалов. Часто в такой рекламе диктуется специальные промокод, дающий возможность беттерам рассчитывать на дополнительный бонус. Максимальный бонус при регистрации составляется 32500 рублей. Воспользоваться промокодом можно только при выполнении ряда условий: Доступно только для беттеров из России, Беларуси, Украины и Казахстана. Возврат игрока – от 18 лет. промокод для 1xbet на сегодня. Промокод 1xBet сегодня найти в интернете не так сложно, достаточно воспользоваться любой поисковой системой. Но обращайте внимание на профессиональность ресурса, откуда будет скопирован промокод. Многие сайты предлагают неактуальные бонусные коды, которые не дадут никакого повышенного депозита после регистрации. На нашем сайте представлен актуальный промокод 1xBet на 2026 год. Вводите промокод, чтобы получить 100% сверху после первого пополнения. Минимальная сумма депозита для использования промокода – 1000 рублей. Ограничивается бонус 1хБет суммой в 32500 рублей.

    Stanleyvonna

    21 Oct 25 at 9:34 pm

  27. Eugenioves

    21 Oct 25 at 9:36 pm

  28. продвижение сайта в топ 10 профессионалами [url=https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]https://www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .

  29. «Частный Медик 24» — это медицинский контроль, поддержка и лечение на всех этапах вывода из запоя.
    Узнать больше – [url=https://vyvod-iz-zapoya-v-stacionare23.ru/]вывод из запоя в стационаре нижний новгород[/url]

    Jordanwrive

    21 Oct 25 at 9:39 pm

  30. Galera, quero deixar registrado sobre o Bingoemcasa porque me ganhou de verdade. O site tem um jeito leve que lembra um barzinho cheio de risadas. As salas de bingo sao movimentadas, e ainda testei alguns caca-niqueis modernos, todos vieram com graficos bonitos. O atendimento no chat foi respondeu em segundos, o que ja me deixou bem a vontade. As retiradas foram instantaneas, inclusive testei cripto e super tranquilo. Se pudesse apontar algo, diria que senti falta de ofertas extras, mas nada que estrague a experiencia. Enfim, o Bingoemcasa foi uma otima descoberta. Eu mesmo ja voltei varias vezes
    bingoemcasa net|

    mysticotter71zef

    21 Oct 25 at 9:40 pm

  31. рейтинг seo компаний [url=https://seo-prodvizhenie-reiting.ru/]рейтинг seo компаний[/url] .

  32. Где купить Альфу в Покачие?Друзья, расскажите – вот нашел https://hostel-loft.ru
    . Цены нормальные, доставка есть. Кто-нибудь сталкивался с ними? Насколько качественно?

    Stevenref

    21 Oct 25 at 9:41 pm

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

  34. топ 10 сео продвижение [url=https://seo-prodvizhenie-reiting.ru/]топ 10 сео продвижение[/url] .

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

  36. продвижение сайтов топ 10 [url=reiting-kompanii-po-prodvizheniyu-sajtov.ru]reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .

  37. заказать seo продвижение сайта в топ 10 [url=http://www.seo-prodvizhenie-reiting-kompanij.ru]заказать seo продвижение сайта в топ 10[/url] .

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

  39. лучшие seo агентства [url=http://reiting-seo-kompanii.ru]лучшие seo агентства[/url] .

  40. Joined $MTAUR token hunt—presale bonuses stacking. Maze treasures and creature fights immersive. This project’s viral potential high.
    mtaur token

    WilliamPargy

    21 Oct 25 at 9:52 pm

  41. Play safely at Joy Palace, a PAGCOR licensed online casino in the Philippines.

    Enjoy hundreds of slot games, live baccarat, and more.

    Register now to claim your free welcome bonus!

  42. everythingyouneedtoday – Content feels fresh and well-organized, making it easy to consume.

    Boyce Gonales

    21 Oct 25 at 9:53 pm

  43. продвижение сайта топ 1 [url=https://www.seo-prodvizhenie-reiting.ru]продвижение сайта топ 1[/url] .

  44. creativityneverends – Found some fantastic ideas here for creative routines and daily inspiration.

    Ayako Bahun

    21 Oct 25 at 9:54 pm

  45. Здравствуйте!
    Vitebsk State University named after P.M. Masherov, one of the oldest universities in Belarus, invites you to get the education of European quality! Undoubted advantages of studying in VSU are affordability, high level of the quality of the educational process, great experience in training foreign students.
    Полная информация по ссылке – https://vsu.by/inostrannym-abiturientam/vypuskniki.html
    foreign student, Магистрантура, вторая ступень образования, 高等职业技术和再培训学院
    онлайн обучение, [url=https://vsu.by/studentam/vakantnye-byudzhetnye-mesta.html]sale[/url], university olympiad
    Удачи и успехов в учебе!

    KeithAligo

    21 Oct 25 at 9:56 pm

  46. seo оптимизация москва [url=www.reiting-seo-agentstv-moskvy.ru/]www.reiting-seo-agentstv-moskvy.ru/[/url] .

  47. Вывод из запоя в стационаре — это шанс начать путь к трезвой жизни, и в Самаре этот шанс предоставляет «Частный Медик 24».
    Подробнее – [url=https://vyvod-iz-zapoya-v-stacionare-samara23.ru/]вывод из запоя в стационаре клиника[/url]

    Jerryrip

    21 Oct 25 at 10:00 pm

  48. прокладка трассы для кондиционера Установка Кондиционеров Под Ключ в Москве: Полный Спектр Услуг от Проектирования до Обслуживания Мы предлагаем установку кондиционеров под ключ в Москве, избавляя вас от необходимости поиска различных подрядчиков. Наша команда берет на себя все этапы работ: проектирование системы кондиционирования, подбор оборудования, доставку, монтаж, пуско-наладку и последующее обслуживание. Вы получаете готовое решение, полностью соответствующее вашим требованиям.

    Johnniemuh

    21 Oct 25 at 10:00 pm

  49. Госпитализация в стационар помогает быстрее и надежнее справиться с последствиями запоя.
    Углубиться в тему – [url=https://vyvod-iz-zapoya-v-stacionare21.ru/]стационар вывод из запоя в нижний новгороде[/url]

    Eduardonibre

    21 Oct 25 at 10:01 pm

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

Leave a Reply