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 93,679 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 , , ,

93,679 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=https://frei-diplom9.ru/]как купить диплом в колледже[/url] .

    Diplomi_htea

    17 Oct 25 at 4:53 am

  2. promo bet Don’t start betting without a valid betting promo code. Maximize your potential winnings with exclusive promotions, bonus funds, and risk-free bets. Act now!

    Caseypeash

    17 Oct 25 at 4:53 am

  3. AlbertEnark

    17 Oct 25 at 4:55 am

  4. AlbertEnark

    17 Oct 25 at 4:56 am

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

    Diplomi_kdOi

    17 Oct 25 at 4:57 am

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

    Diplomi_tyPt

    17 Oct 25 at 4:58 am

  7. generic Cialis online pharmacy: cialis – cialis

    Andresstold

    17 Oct 25 at 4:59 am

  8. Brentsek

    17 Oct 25 at 5:02 am

  9. Right here is the perfect web site for anyone who hopes
    to find out about this topic. You realize a whole
    lot its almost hard to argue with you (not that I really would want to…HaHa).
    You certainly put a new spin on a topic that’s been written about
    for many years. Excellent stuff, just great!

  10. купить диплом в кемерово [url=https://rudik-diplom2.ru/]купить диплом в кемерово[/url] .

    Diplomi_mmpi

    17 Oct 25 at 5:05 am

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

    Diplomi_hkea

    17 Oct 25 at 5:06 am

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

    Diplomi_ppei

    17 Oct 25 at 5:08 am

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

    Diplomi_rkPl

    17 Oct 25 at 5:10 am

  14. Клиника принимает 24/7 без очередей: ночной блок специально настроен под «трудные часы», когда усиливаются панические мысли и реактивность пульса. Для тех, кому легче дома, выездная служба приводит помощь в знакомое пространство; если нужны короткие контрольные включения, применяем видеосвязь вечером (15–20 минут), чтобы корректно настроить ритуалы засыпания, дыхательные циклы и «световые правила». Маршрут фиксируется в единой карте наблюдения — этот документ доступен команде по ролям и защищает от «повторов заново», когда формат меняется (дом – амбулатория – стационар).
    Разобраться лучше – http://narkologicheskaya-klinika-v-stavropole15.ru

    BrianSoafe

    17 Oct 25 at 5:10 am

  15. Вы, случайно, не эксперт?
    in the event that you deposit the minimum amount that meets the requirements (twenty bucks), [url=http://crown-green-casino.org/]crowngreen casino[/url] you will receive 15 dollars of bonus money to personal account at gambling establishment.

    Kiameery

    17 Oct 25 at 5:12 am

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

    Diplomi_zfOi

    17 Oct 25 at 5:14 am

  17. Kaizenaire.com stands tall witһ Singapore’ѕ ideal shopping deals ɑnd promotions.

    Singapore stands аpɑrt as a shopping paradise, ѡhere Singaporeans’ excitement for deals ɑnd promotions knoѡs
    no bounds.

    Reviewing novels at cozy collections рrovides а peaceful escape fоr bookish Singaporeans, and keеp in mind tο stay updated on Singapore’s most current promotions ɑnd shopping deals.

    Adidas ɡives sportswear and sneakers, cherished ƅʏ Singaporeans fߋr tһeir elegant activewear and recommendation ƅy local athletes.

    Ginlee crafts classic females’ѕ wear with toρ quality
    materials leh, preferred ƅy sophisticated Singaporeans f᧐r their
    enduring design оne.

    Aalst Chocolate crafts Belgian-inspired chocolates, enjoyed fоr smooth, indulgent bars ɑnd neighborhood developments.

    Eh, wһy pay fuⅼl rate mah, regularly search Kaizenaire.ⅽom for the ѵery beѕt
    promotions lah.

    Check ⲟut my site: singapore promotions

  18. Этот интересный отчет представляет собой сборник полезных фактов, касающихся актуальных тем. Мы проанализируем данные, чтобы вы могли сделать обоснованные выводы. Читайте, чтобы узнать больше о последних трендах и значимых событиях!
    Что ещё нужно знать? – https://royaltea.in/benefits-of-indian-spices-in-your-tea

    Jamesmow

    17 Oct 25 at 5:16 am

  19. AlbertEnark

    17 Oct 25 at 5:17 am

  20. купить диплом медсестры [url=https://frei-diplom13.ru]купить диплом медсестры[/url] .

    Diplomi_abkt

    17 Oct 25 at 5:17 am

  21. AlbertEnark

    17 Oct 25 at 5:18 am

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

    Diplomi_voea

    17 Oct 25 at 5:19 am

  23. купить диплом техникума с реестром [url=https://www.frei-diplom1.ru]купить диплом техникума с реестром[/url] .

    Diplomi_idOi

    17 Oct 25 at 5:22 am

  24. What are the benefits of yoga

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

  25. купить диплом об окончании техникума в москве [url=https://frei-diplom12.ru]купить диплом об окончании техникума в москве[/url] .

    Diplomi_gvPt

    17 Oct 25 at 5:22 am

  26. AlbertEnark

    17 Oct 25 at 5:23 am

  27. Автоматизация избавляет от рутины актуальные зеркала kraken kraken рабочая ссылка onion сайт kraken onion kraken darknet

    RichardPep

    17 Oct 25 at 5:23 am

  28. AlbertEnark

    17 Oct 25 at 5:24 am

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

    Diplomi_lqPl

    17 Oct 25 at 5:24 am

  30. Please let me know if you’re looking for a article writer for your site.
    You have some really great posts and I believe I would be a good asset.
    If you ever want to take some of the load off, I’d really like to write some articles for your blog in exchange for a link back to mine.
    Please blast me an e-mail if interested. Many thanks!

  31. купить диплом техникума 1997 [url=http://www.frei-diplom8.ru]купить диплом техникума 1997[/url] .

    Diplomi_tdsr

    17 Oct 25 at 5:27 am

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

    Diplomi_qfOi

    17 Oct 25 at 5:27 am

  33. Ранняя врачебная помощь не только снижает тяжесть абстинентного синдрома, но и предотвращает опасные осложнения, даёт шанс пациенту быстрее вернуться к обычной жизни, а его близким — обрести уверенность в завтрашнем дне.
    Узнать больше – https://vyvod-iz-zapoya-shchelkovo6.ru/vyvod-iz-zapoya-na-domu-v-shchelkovo/

    VictorVok

    17 Oct 25 at 5:29 am

  34. купить диплом в горном колледже [url=http://frei-diplom12.ru]http://frei-diplom12.ru[/url] .

    Diplomi_ukPt

    17 Oct 25 at 5:31 am

  35. Just swapped BNB for $MTAUR—smooth on BSC. Referral rewards motivate sharing. Game’s power-ups via tokens strategic.
    minotaurus coin

    WilliamPargy

    17 Oct 25 at 5:34 am

  36. Hello Dear, are you actually visiting this website daily, if so then you will definitely obtain good knowledge.

  37. CameronJaisp

    17 Oct 25 at 5:36 am

  38. Bullish on Minotaurus ICO’s viral referrals. $MTAUR utility strong. Sector expansion aids.
    mtaur token

    WilliamPargy

    17 Oct 25 at 5:38 am

  39. BearPrint — типография полного цикла в Москве: цифровая и офсетная печать визиток, листовок, буклетов, каталогов, этикеток и упаковочных шуберов, плюс широкоформат и постпечатная обработка. Команда подключается от дизайна до сборки тиража, работает срочно и аккуратно, с доставкой по городу. Посмотрите услуги и контакты на https://bearprint.pro/ — там же форма «Свяжитесь со мной», WhatsApp и Telegram. Чёткое качество, понятные сроки и цены ниже рынка на сопоставимом уровне.

    jukyveRop

    17 Oct 25 at 5:38 am

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

    Diplomi_quPl

    17 Oct 25 at 5:38 am

  41. linebet partner

    17 Oct 25 at 5:39 am

  42. Brentsek

    17 Oct 25 at 5:39 am

  43. возможно ли купить диплом техникума [url=http://frei-diplom8.ru/]возможно ли купить диплом техникума[/url] .

    Diplomi_lmsr

    17 Oct 25 at 5:41 am

  44. Very quickly this web site will be famous amid all blog viewers, due to it’s pleasant
    articles or reviews

  45. Register at glory game casino and receive bonuses on your first deposit on online casino games and slots right now!

    Miguelhen

    17 Oct 25 at 5:42 am

  46. Leroypap

    17 Oct 25 at 5:43 am

  47. купить свидетельство о рождении [url=https://www.rudik-diplom10.ru]купить свидетельство о рождении[/url] .

    Diplomi_lrSa

    17 Oct 25 at 5:45 am

  48. AlbertEnark

    17 Oct 25 at 5:46 am

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

    Diplomi_luOi

    17 Oct 25 at 5:47 am

  50. Если на любом этапе проявляется нестабильность давления/ритма, падает сатурация или ухудшается контакт, врач эскалирует формат немедленно. Важно: в стационаре мы продолжаем тот же курс, не «перепридумывая» его с нуля — благодаря единой карте наблюдения теряется меньше времени и сил.
    Получить больше информации – [url=https://vyvod-iz-zapoya-stavropol15.ru/]наркологический вывод из запоя[/url]

    Ronaldgag

    17 Oct 25 at 5:47 am

Leave a Reply