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,186 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,186 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. Брал первый раз дживик качество вроде норм))))Еще хотел совет попросить как из 250 самый норм микс сделать?Помогите плиз.
    https://shakhtyorskgp.ru
    Отзыв коротенько. Закладка на месте. Обьяснение распологает. Фото имеется. Бот чёткий. бошки хороши. Вес норма! … ну вот и всё Коротко и ладно)

    ErwinAroug

    21 Oct 25 at 1:56 pm

  2. BJ88 香港 — 安全遊玩、快速派彩、貼心客服。老虎機、真人娛樂場與體育投注一站式體驗,立即加入享專屬獎勵。

  3. пин ап как получить выигрыш [url=www.pinup5007.ru]www.pinup5007.ru[/url]

    pin_up_uz_fbsr

    21 Oct 25 at 1:57 pm

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

  5. seo agency ranking [url=https://www.reiting-seo-kompanii.ru]https://www.reiting-seo-kompanii.ru[/url] .

  6. wettanbieter mit paysafecard

    my web blog Wetten halbzeit endstand

  7. DarylCeviZ

    21 Oct 25 at 2:01 pm

  8. Woah! I’m really digging the template/theme of this site.
    It’s simple, yet effective. A lot of times it’s tough to get that “perfect balance” between superb usability and appearance.

    I must say you’ve done a awesome job with this.
    Additionally, the blog loads super fast for me
    on Chrome. Outstanding Blog!

  9. This is a good tip particularly to those fresh to the blogosphere.

    Short but very accurate info… Thank you for sharing
    this one. A must read post!

  10. Здравствуйте!
    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 Vitebsk State University P.M.Masherov University is an educational center. VSU.by provides training in: chemistry, biology, history, physics, programming, pedagogy, psychology, mathematics.
    Полная информация по ссылке – https://vsu.by/cn/magistratura-cn/2019-02-21-10-03-38.html
    VSU recruitment for the I and II stages of higher education, foreign student, курсы витебск
    поступить университет, [url=https://vsu.by/inostrannym-abiturientam/reklamnye-videoroliki.html]курсы витебск[/url], Выпускники ВГУ Витебск
    Удачи и успехов в учебе!

    KeithAligo

    21 Oct 25 at 2:02 pm

  11. 안녕하세요! 정말 멋진 사이트입니다!!
    아저씨 .. 훌륭하다 .. 놀랍다 ..
    즐겨찾기할 것이고 추가로 받을 건가요?
    행복하게 수많은 유용한 내용을 여기 게시에서
    찾았습니다, 이에 대해 더 많은 기술을
    개발 필요가 있습니다, 공유해줘서 고맙습니다.
    . . . . .

  12. Hello, every time i used to check weblog posts here in the
    early hours in the break of day, since i
    love to gain knowledge of more and more.

    LT88.COM

    21 Oct 25 at 2:04 pm

  13. Danielignit

    21 Oct 25 at 2:04 pm

  14. DarylCeviZ

    21 Oct 25 at 2:07 pm

  15. pin up sport tikish [url=http://pinup5008.ru]http://pinup5008.ru[/url]

    pin_up_uz_ywSt

    21 Oct 25 at 2:07 pm

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

  17. DarylCeviZ

    21 Oct 25 at 2:08 pm

  18. купить диплом колледжа в москве [url=www.frei-diplom10.ru/]www.frei-diplom10.ru/[/url] .

    Diplomi_ovEa

    21 Oct 25 at 2:08 pm

  19. Как купить Фен в Бузулуке?Посмотрите https://xboxplanet.ru
    – цены вроде адекватные, доставка быстрая. Кто-нибудь пробовал у них? Как с чистотой товар?

    Stevenref

    21 Oct 25 at 2:08 pm

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

  21. firma seo [url=www.reiting-seo-agentstv.ru/]firma seo[/url] .

  22. пинап [url=pinup5008.ru]пинап[/url]

    pin_up_uz_acSt

    21 Oct 25 at 2:09 pm

  23. Hi I am so glad I found your weblog, I really found you by error, while I was browsing on Aol for something else, Anyways
    I am here now and would just like to say thank you for a incredible post and
    a all round entertaining blog (I also love the theme/design), I don’t have time
    to look over it all at the minute but I have book-marked it and also included your RSS feeds, so when I have time I will be back to read
    much more, Please do keep up the great b.

    xn88 link

    21 Oct 25 at 2:10 pm

  24. Сервис Stop-Alko предлагает помощь при запое на дому в Екатеринбурге. Услуга доступна 24/7.
    Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-ekaterinburg27.ru/]вывод из запоя круглосуточно в екатеринбурге[/url]

    DannyLox

    21 Oct 25 at 2:10 pm

  25. Если домашние методы не помогают, в «Частном Медике 24» обеспечат профессиональный вывод из запоя в стационаре.
    Исследовать вопрос подробнее – http://vyvod-iz-zapoya-v-stacionare22.ru

    Douglasvex

    21 Oct 25 at 2:11 pm

  26. DarylCeviZ

    21 Oct 25 at 2:12 pm

  27. seo agency ranking [url=https://www.reiting-seo-kompanii.ru]https://www.reiting-seo-kompanii.ru[/url] .

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

    Jasonsoata

    21 Oct 25 at 2:13 pm

  29. online wettbüro eröffnen – Leonor, wettseite

    Leonor

    21 Oct 25 at 2:13 pm

  30. пин ап активация бонуса [url=www.pinup5007.ru]пин ап активация бонуса[/url]

    pin_up_uz_vusr

    21 Oct 25 at 2:15 pm

  31. DarylCeviZ

    21 Oct 25 at 2:17 pm

  32. سلام به همه زیرا در پی سرگرمی سریع
    می‌گردند. سایت‌های بازی شرطی دام بزرگی می‌باشند که منجر
    اعتیاد همچنین زیان عمیق می‌شوند.

    من هزاران ریال نابود کردم و حالا
    ناراحت می‌باشم. خواهش می‌کنم اجتناب شوید و در امور مفید روی شوید!

  33. We stumbled over here from a different web address and
    thought I should check things out. I like what I see
    so now i’m following you. Look forward to looking at your web page for a second time.

  34. где купить диплом техникума в краснодаре [url=frei-diplom10.ru]где купить диплом техникума в краснодаре[/url] .

    Diplomi_cbEa

    21 Oct 25 at 2:19 pm

  35. Danielignit

    21 Oct 25 at 2:19 pm

  36. Danielignit

    21 Oct 25 at 2:20 pm

  37. https://medtronik.ru узнайте, какие акции действуют прямо сейчас

    Aaronawads

    21 Oct 25 at 2:25 pm

  38. топ агентства seo [url=https://reiting-seo-kompanii.ru/]топ агентства seo[/url] .

  39. https://potenzvital.com/# cialis generika

    MickeySum

    21 Oct 25 at 2:26 pm

  40. An impressive share! I have just forwarded this onto
    a coworker who has been doing a little research on this.
    And he in fact bought me lunch simply because I discovered it for him…

    lol. So allow me to reword this…. Thanks for the meal!! But
    yeah, thanks for spending the time to talk about this subject here on your site.

  41. DarylCeviZ

    21 Oct 25 at 2:29 pm

  42. Danielignit

    21 Oct 25 at 2:30 pm

  43. pin up aviator demo [url=https://pinup5007.ru]https://pinup5007.ru[/url]

    pin_up_uz_vlsr

    21 Oct 25 at 2:31 pm

  44. DarylCeviZ

    21 Oct 25 at 2:31 pm

  45. DarylCeviZ

    21 Oct 25 at 2:31 pm

  46. кракен как войти: https://obecretuvka.cz

  47. Sou totalmente viciado em BETesporte Casino, e uma plataforma que vibra como um estadio em dia de final. A variedade de titulos e estonteante, com sessoes ao vivo cheias de energia. Fortalece seu saldo inicial. O suporte ao cliente e excepcional, garantindo atendimento de alto nivel. O processo e simples e direto, no entanto recompensas extras seriam um hat-trick. No fim, BETesporte Casino garante diversao constante para fas de cassino online ! Vale destacar a plataforma e visualmente impactante, facilita uma imersao total. Igualmente impressionante o programa VIP com niveis exclusivos, fortalece o senso de comunidade.
    Descobrir mais|

    VortexGoalW2zef

    21 Oct 25 at 2:32 pm

  48. medtronik.ru инструкции, как активировать бонусные программы и акции

    Aaronawads

    21 Oct 25 at 2:32 pm

  49. рейтинг seo компаний [url=www.luchshie-digital-agencstva.ru/]рейтинг seo компаний[/url] .

  50. DarylCeviZ

    21 Oct 25 at 2:33 pm

Leave a Reply