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 120,027 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 , , ,

120,027 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=www.elektrokarniz777.ru/]автоматические карнизы[/url] .

  2. Наркологическая клиника в Новокузнецке предоставляет профессиональную помощь людям, столкнувшимся с зависимостью от алкоголя, наркотиков и психоактивных веществ. Лечение проводится под наблюдением опытных специалистов с применением современных медицинских методик. Основная цель работы клиники — не только устранить физическую зависимость, но и восстановить психологическое равновесие пациента, вернуть мотивацию и способность жить без употребления веществ.
    Изучить вопрос глубже – [url=https://narkologicheskaya-clinica-v-novokuzneczke17.ru/]запой наркологическая клиника[/url]

    GeorgeCow

    31 Oct 25 at 10:53 pm

  3. бамбуковые электрожалюзи [url=www.elektricheskie-zhalyuzi97.ru/]www.elektricheskie-zhalyuzi97.ru/[/url] .

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

    Diplomi_gysa

    31 Oct 25 at 10:55 pm

  5. safe place to order meds UK: online pharmacy – UkMedsGuide

    Johnnyfuede

    31 Oct 25 at 10:55 pm

  6. I want to to thank you for this fantastic read!!
    I certainly enjoyed every little bit of it. I’ve got you book marked to check out new things you post…

  7. MichaelPione

    31 Oct 25 at 10:56 pm

  8. I like the helpful info you provide for your articles.
    I will bookmark your weblog and take a look at again right here frequently.

    I’m quite certain I will be informed a lot of new stuff right right here!

    Good luck for the following!

  9. MichaelPione

    31 Oct 25 at 10:57 pm

  10. duphalac

    31 Oct 25 at 10:57 pm

  11. организация онлайн трансляции мероприятия [url=https://zakazat-onlayn-translyaciyu4.ru]организация онлайн трансляции мероприятия[/url] .

  12. I simply could not leave your site prior to suggesting that I extremely enjoyed the usual information an individual provide for your visitors?
    Is gonna be again steadily to inspect new posts

  13. прокарниз [url=https://elektrokarniz777.ru/]https://elektrokarniz777.ru/[/url] .

  14. организация онлайн трансляций москва [url=https://zakazat-onlayn-translyaciyu5.ru]https://zakazat-onlayn-translyaciyu5.ru[/url] .

  15. купить диплом в троицке [url=http://rudik-diplom12.ru/]http://rudik-diplom12.ru/[/url] .

    Diplomi_agPi

    31 Oct 25 at 11:01 pm

  16. заказать трансляцию конференции [url=www.zakazat-onlayn-translyaciyu5.ru/]www.zakazat-onlayn-translyaciyu5.ru/[/url] .

  17. best pharmacy sites with discounts: online pharmacy – trusted online pharmacy USA

    Johnnyfuede

    31 Oct 25 at 11:02 pm

  18. It’s no secret how President Donald Trump feels about sports teams turning away from Native American mascots. He’s repeatedly called for the return of the Washington Redskins and Cleveland Indians, claiming their recent rebrands were part of a “woke” agenda designed to erase history.

    But one surprising team has really gotten the president’s attention: the Massapequa Chiefs.

    The Long Island school district has refused to change its logo and name under a mandate from New York state banning schools from using team mascots appropriating Indigenous culture. Schools were given two years to rebrand, but Massapequa is the lone holdout, having missed the June 30 deadline to debut a new logo.
    [url=https://kra37cc.net]kra40 cc[/url]
    The district lost an initial lawsuit it filed against the state but now has the federal government on its side. In May, Trump’s Department of Education intervened on the district’s behalf, claiming the state’s mascot ban is itself discriminatory.

    Massapequa’s Chiefs logo — an American Indian wearing a yellow feathered headdress — is expected to still be prominently displayed when the fall sports season kicks off soon, putting the quiet Long Island hamlet at the center of a political firestorm.
    [url=https://kra–40-cc.ru]kra38 cc[/url]
    The district is now a key “battleground,” said Oliver Roberts, a Massapequa alum and the lawyer representing the school board in its fresh lawsuit against New York claiming that the ban is unconstitutional and discriminatory.

    The Trump administration claims New York’s mascot ban violates Title VI of the Civil Rights Act of 1964, which prohibits recipients of federal funds from engaging in discriminatory behavior based on race, color or national origin — teeing up a potentially precedent-setting fight.

    The intervention on behalf of Massapequa follows a pattern for a White House that has aggressively applied civil rights protections to police “reverse discrimination” and coerced schools and universities into policy concessions by withholding federal funds.

    “Our goal is to assist nationally,” Roberts said. “It’s us putting forward our time and effort to try and assist with this national movement and push back against the woke bureaucrats trying to cancel our country’s history and tradition.”
    kra40
    https://kra-37-cc.net

    DanielPlepe

    31 Oct 25 at 11:04 pm

  19. online pharmacy: Uk Meds Guide – online pharmacy

    HaroldSHems

    31 Oct 25 at 11:05 pm

  20. организация онлайн трансляции конференции [url=http://www.zakazat-onlayn-translyaciyu4.ru]http://www.zakazat-onlayn-translyaciyu4.ru[/url] .

  21. где купить диплом техникума хорошую [url=http://frei-diplom11.ru/]где купить диплом техникума хорошую[/url] .

    Diplomi_wmsa

    31 Oct 25 at 11:05 pm

  22. It’s amazing to visit this web page and reading the views of all colleagues about
    this post, while I am also eager of getting experience.

  23. рольшторы на окна купить в москве [url=http://avtomaticheskie-rulonnye-shtory77.ru]http://avtomaticheskie-rulonnye-shtory77.ru[/url] .

  24. Great blog here! Also your website loads up fast!
    What web host are you using? Can I get your affiliate
    link to your host? I wish my website loaded up as
    quickly as yours lol

  25. Howdy, i read your blog from time to time and i own a similar one
    and i was just wondering if you get a lot of spam responses?

    If so how do you prevent it, any plugin or anything you can suggest?
    I get so much lately it’s driving me mad so any help is very
    much appreciated.

    igtoto login

    31 Oct 25 at 11:07 pm

  26. Irish online pharmacy reviews

    Edmundexpon

    31 Oct 25 at 11:08 pm

  27. https://ukmedsguide.com/# affordable medications UK

    Haroldovaph

    31 Oct 25 at 11:08 pm

  28. организация онлайн трансляций цена [url=http://zakazat-onlayn-translyaciyu5.ru/]http://zakazat-onlayn-translyaciyu5.ru/[/url] .

  29. When I originally commented I seem to have clicked the -Notify me
    when new comments are added- checkbox and now whenever a comment is added I get four emails with the same comment.

    Is there a way you are able to remove me from that service?
    Many thanks!

  30. Fastidious answers in return of this matter with real arguments and telling all regarding that.

  31. диплом колледжа купить в москве [url=http://frei-diplom11.ru/]http://frei-diplom11.ru/[/url] .

    Diplomi_ivsa

    31 Oct 25 at 11:12 pm

  32. жалюзи для умного дома [url=http://elektricheskie-zhalyuzi97.ru/]жалюзи для умного дома[/url] .

  33. заказать трансляцию [url=www.zakazat-onlayn-translyaciyu5.ru]заказать трансляцию[/url] .

  34. организация онлайн трансляции москва [url=www.zakazat-onlayn-translyaciyu4.ru]организация онлайн трансляции москва[/url] .

  35. Наши услуги в Ростове-на-Дону включают не только физическую детоксикацию, но и психологическую поддержку для более эффективного восстановления.
    Разобраться лучше – [url=https://vyvod-iz-zapoya-rostov112.ru/]нарколог на дом вывод из запоя ростов-на-дону[/url]

    DarrenBrupe

    31 Oct 25 at 11:14 pm

  36. купить диплом электромонтера [url=http://rudik-diplom9.ru/]купить диплом электромонтера[/url] .

    Diplomi_rkei

    31 Oct 25 at 11:15 pm

  37. электрокарнизы для штор [url=http://elektrokarniz777.ru/]электрокарнизы для штор[/url] .

  38. Your mode of telling everything in this piece of writing is in fact nice,
    all be capable of without difficulty be aware of it, Thanks a lot.

    achtformpool

    31 Oct 25 at 11:15 pm

  39. гардина с электроприводом [url=elektrokarniz777.ru]elektrokarniz777.ru[/url] .

  40. организация онлайн трансляций мероприятий [url=http://zakazat-onlayn-translyaciyu5.ru/]организация онлайн трансляций мероприятий[/url] .

  41. UK online pharmacies list: best UK pharmacy websites – non-prescription medicines UK

    Johnnyfuede

    31 Oct 25 at 11:21 pm

  42. онлайн трансляция под ключ [url=zakazat-onlayn-translyaciyu5.ru]zakazat-onlayn-translyaciyu5.ru[/url] .

  43. Uk Meds Guide [url=https://ukmedsguide.shop/#]trusted online pharmacy UK[/url] best UK pharmacy websites

    Hermanengam

    31 Oct 25 at 11:22 pm

  44. автоматические гардины для штор [url=elektrokarniz777.ru]elektrokarniz777.ru[/url] .

  45. карниз для штор электрический [url=www.elektrokarniz777.ru]карниз для штор электрический[/url] .

  46. онлайн трансляция под ключ [url=https://zakazat-onlayn-translyaciyu4.ru]https://zakazat-onlayn-translyaciyu4.ru[/url] .

  47. Магазин одежды в современных реалиях — это не просто торговая точка, а полноценный интернет магазин одежды и онлайн магазин одежды с удобным каталогом, где можно купить одежду и обувь, сравнить цены и оформить доставку по России.
    https://grandemporio.ru/catalog/accessories
    босоножки италия купить
    Официальный сайт магазина одежды часто совмещает каталог магазин одежда официальный сайт и разделы «магазин детской одежды», «магазин одежды и обуви», «бутик одежда» и премиум коллекции: брендовая одежда, одежда люкс и итальянские бренды одежды. Для тех, кто ценит удобство, интернет магазин одежды с доставкой по России предлагает опцию заказать одежду с примеркой, оформить возврат и выбрать подходящий размер.
    [url=https://grandemporio.ru/catalog]бренды одежды в россии[/url]
    Каталог одежды интернет магазин официальный содержит фото, цена каталог одежда каталог и фильтры по брендам — популярные бренды одежды и бренды обуви позволяют быстро найти белые кеды, брендовые кроссовки, замшевые лоферы или брендовые шлепки. В разделе «модная одежда» и «магазин модной одежды» представлены тренды, стильная одежда и оригинальная одежда для тех, кто хочет купить одежду лучше и выразить индивидуальность. Розница магазины одежды и интернет магазины доставки одежды работают как с бюджетными позициями, так и с одеждой премиум класса: брендовые толстовки, кардиганы, водолазки, рубашки и пиджаки можно заказать онлайн. Интернет магазины одежды каталоги цен отражают акции и скидки, а сайт бренда одежды часто даёт ссылки на официальный интернет одежды и магазин официальный сайт. Если нужно купить летнюю одежду, базовые футболки купить в пару кликов, а заказывать туфли, босоножки или эспадрильи удобно через каталог сандалей и раздел «обувь». Таким образом, магазин одежды — это универсальное решение: купить одежду в магазине или онлайн магазин одежды, просмотреть каталог, сравнить цену на одежду и заказать доставку по России — всё доступно в одном месте.

    LouisEncat

    31 Oct 25 at 11:27 pm

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

    Diplomi_asei

    31 Oct 25 at 11:28 pm

  49. MorganPlece

    31 Oct 25 at 11:28 pm

  50. организация трансляции [url=http://zakazat-onlayn-translyaciyu4.ru]организация трансляции[/url] .

Leave a Reply