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 122,577 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 , , ,

122,577 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. http://ukmedsguide.com/# non-prescription medicines UK

    Haroldovaph

    2 Nov 25 at 2:20 am

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

    Harolddom

    2 Nov 25 at 2:21 am

  3. Вызывали вывести тараканов недавно, результат отличный!
    вывести тараканов

    Wernermog

    2 Nov 25 at 2:22 am

  4. Здравствуйте!
    Многие модели коммерческих автомобилей в России — КамАЗ, Газель, Валдай — оснащены двигателями Cummins. Эти моторы отличаются надежностью, но для их стабильной работы важно соблюдать правила обслуживания. Недавно я искал информацию по своему КамАЗу и наткнулся на полезный ресурс. На сайте https://specteh.blog/ подробно изложены все нюансы эксплуатации, ремонта и диагностики двигателей Cummins. Грамотное обслуживание, качественные масла и своевременная проверка позволяют двигателю работать долго и безотказно.
    Капитальный ремонт двигателя Cummins, Cummins проверка давления масла, Объем масла Cummins инструкция
    Cummins ESN где смотреть Валдай, [url=https://specteh.blog/gazel-s-cummins-isf-2-8-moj-opyt-i-realnyj-rashod-topliva/]Расход топлива Cummins ISF 2.8 Газель[/url], Регулировка клапанов Cummins пошаговое руководство
    Удачи и комфортной езды!

    Cumminsmt

    2 Nov 25 at 2:22 am

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

    Diplomi_deEa

    2 Nov 25 at 2:23 am

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

    Diplomi_uhoi

    2 Nov 25 at 2:23 am

  7. MichaelPione

    2 Nov 25 at 2:24 am

  8. click through the next document

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

  9. SafeMedsGuide: Safe Meds Guide – trusted online pharmacy USA

    HaroldSHems

    2 Nov 25 at 2:25 am

  10. MichaelPione

    2 Nov 25 at 2:25 am

  11. JustinAcecy

    2 Nov 25 at 2:27 am

  12. mostbet kg [url=https://www.mostbet12033.ru]https://www.mostbet12033.ru[/url]

    mostbet_kg_mipa

    2 Nov 25 at 2:28 am

  13. 1 xbet giri? [url=www.1xbet-giris-5.com]www.1xbet-giris-5.com[/url] .

  14. рейтинг рунета сео [url=http://reiting-seo-agentstv.ru/]http://reiting-seo-agentstv.ru/[/url] .

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

    Diplomi_hhSa

    2 Nov 25 at 2:31 am

  16. лидеры seo продвижения веб студия [url=https://reiting-seo-agentstv.ru/]reiting-seo-agentstv.ru[/url] .

  17. What we’re covering
    • Zelensky in Washington: European leaders will join Ukrainian President Volodymyr Zelensky at the White House, as he meets with US President Donald Trump this afternoon. Trump said Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
    [url=https://kra35at.com]kra34 СЃСЃ[/url]
    • Potential security guarantees: At last week’s summit with Trump, Russian President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
    [url=https://kra32-cc.com]kra35 cc[/url]
    • On the ground: Zelensky condemned Russia’s latest strikes across Ukraine, which killed at least 10 people, saying the Kremlin intends to “humiliate diplomatic efforts” and underscores “why reliable security guarantees are required.”
    kra35 СЃСЃ
    https://kra37-at.cc

    RichardJek

    2 Nov 25 at 2:33 am

  18. pharmacy online: online pharmacy australia – compare pharmacy websites

    HaroldSHems

    2 Nov 25 at 2:34 am

  19. купить аттестат школы [url=http://rudik-diplom14.ru]купить аттестат школы[/url] .

    Diplomi_fnea

    2 Nov 25 at 2:35 am

  20. mostbet kg [url=www.mostbet12033.ru]www.mostbet12033.ru[/url]

    mostbet_kg_vvpa

    2 Nov 25 at 2:35 am

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

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

  23. mostbet kg [url=http://mostbet12034.ru/]http://mostbet12034.ru/[/url]

    mostbet_kg_ghPr

    2 Nov 25 at 2:38 am

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

    RobertTut

    2 Nov 25 at 2:42 am

  25. ANAK MEMEK

    ANAK MEMEK

    2 Nov 25 at 2:43 am

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

  27. В Ростове-на-Дону мы гарантируем полную анонимность и конфиденциальность на всех этапах лечения, без постановки на учёт. Клиника в Ростове-на-Дону работает круглосуточно, обеспечивая доступность помощи в любое время дня и ночи.
    Подробнее – [url=https://vyvod-iz-zapoya-rostov117.ru/]наркологический вывод из запоя ростов-на-дону[/url]

    Anthonysmima

    2 Nov 25 at 2:43 am

  28. What we’re covering
    [url=https://megaweb-2at.com]mgmarket6 at[/url]
    • Israel is facing growing condemnation after it attacked Hamas leadership in the capital of Qatar, a US ally and key mediator in Gaza ceasefire talks — putting hostage negotiations at risk.
    [url=https://megaweb-7at.com]mgmarket6.at[/url]
    • Hamas said the strike killed five members but failed to assassinate the negotiating delegation, the target of the strikes.
    • US President Donald Trump has criticized the strike, saying that by the time his administration learned of the attack and told the Qataris, there was little he could do to stop it.

    • The attack is the first publicly acknowledged strike on a Gulf state by Israel. Qatar’s prime minister was visibly angry and said his country’s tradition of diplomacy “won’t be deterred.”
    https://megaweb-1at.com
    megaweb5.com

    JamesBus

    2 Nov 25 at 2:44 am

  29. online pharmacy reviews and ratings [url=https://safemedsguide.shop/#]trusted online pharmacy USA[/url] cheapest pharmacies in the USA

    Hermanengam

    2 Nov 25 at 2:46 am

  30. http://safemedsguide.com/# compare online pharmacy prices

    Haroldovaph

    2 Nov 25 at 2:48 am

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

  32. компании сео [url=https://www.reiting-seo-agentstv.ru]https://www.reiting-seo-agentstv.ru[/url] .

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

    Ricardoben

    2 Nov 25 at 2:51 am

  34. Increíble artículo sobre los juegos más populares
    de Pin-Up Casino en México. Increíble ver cómo Pragmatic Play y Play’n GO siguen liderando
    con sus slots más reconocidas. Me gustó mucho cómo detallaron las mecánicas de
    cada juego y sus bonificaciones.

    Recomiendo leer el artículo completo si quieres descubrir qué juegos están marcando tendencia en Pin Up Casino.

    Se agradece ver una mezcla entre títulos nostálgicos y nuevas propuestas en el mercado mexicano de apuestas.

    Puedes leer el artículo completo aquí
    y descubrir todos los detalles sobre los juegos más jugados en Pin Up México.

    info

    2 Nov 25 at 2:52 am

  35. motbet [url=http://mostbet12033.ru]motbet[/url]

    mostbet_kg_qspa

    2 Nov 25 at 2:52 am

  36. топ seo агентств мира [url=http://reiting-seo-kompaniy.ru/]http://reiting-seo-kompaniy.ru/[/url] .

  37. best Irish pharmacy websites

    Edmundexpon

    2 Nov 25 at 2:53 am

  38. Me encantó este contenido sobre las casino tragamonedas más destacadas en Pin-Up México.

    Me sorprendió ver cómo títulos como Gates of Olympus y Sweet Bonanza siguen dominando entre los jugadores mexicanos.
    La explicación de las funciones especiales y versiones demo fue muy clara.

    Vale la pena visitar la publicación original y conocer en detalle por qué estos
    títulos son tan jugados en 2025.

    Se agradece ver una mezcla entre títulos nostálgicos y nuevas propuestas en el mercado
    mexicano de apuestas.

    Te recomiendo visitar el post original para conocer las tragamonedas más populares de
    2025 en Pin-Up Casino.

    url

    2 Nov 25 at 2:53 am

  39. irishpharmafinder

    Edmundexpon

    2 Nov 25 at 2:54 am

  40. fashiondailydeals – Overall a pleasant visit—nice deals, friendly design, worth returning to.

    Otilia Loehner

    2 Nov 25 at 2:55 am

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

    Diplomi_jfsr

    2 Nov 25 at 2:56 am

  42. 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]kra39[/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-35cc.ru]kra40[/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-34.com

    DanielPlepe

    2 Nov 25 at 2:56 am

  43. shopwithhappiness –Definitely bookmarking this site for when I need something fun and reliable.

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

    AltonPoula

    2 Nov 25 at 2:58 am

  45. online pharmacy: top rated online pharmacies – compare online pharmacy prices

    Johnnyfuede

    2 Nov 25 at 2:58 am

  46. 1xbet g?ncel giri? [url=http://1xbet-giris-4.com]1xbet g?ncel giri?[/url] .

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

  48. купить диплом в нижнем новгороде [url=https://www.rudik-diplom14.ru]купить диплом в нижнем новгороде[/url] .

    Diplomi_mkea

    2 Nov 25 at 3:01 am

  49. LP tokens you receive from a Uniswap pool are representative of your deposit; they can often be traded or staked further, adding strategy layers.
    uniswap pool app
    uniswap-pool-info.cc

  50. hlfsxx.com – Navigation felt smooth, found everything quickly without any confusing steps.

Leave a Reply