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 88,401 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 , , ,

88,401 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://rudik-diplom1.ru/]купить свидетельство о рождении[/url] .

    Diplomi_oaer

    14 Oct 25 at 2:45 am

  2. На протяжении процедуры врач постоянно наблюдает за пациентом. Контролируются витальные показатели, корректируется скорость инфузии, дозировки и последовательность введения препаратов. При любых нестандартных реакциях схема лечения тут же адаптируется. Мы не используем «универсальных» капельниц: только персонализированные решения, основанные на состоянии конкретного человека.
    Получить дополнительные сведения – https://narkolog-na-dom-krasnogorsk6.ru/vyzov-narkologa-na-dom-v-krasnogorske/

    Danielunato

    14 Oct 25 at 2:45 am

  3. Brentsek

    14 Oct 25 at 2:46 am

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

    Diplomi_wfOi

    14 Oct 25 at 2:48 am

  5. карнизы для штор с электроприводом [url=http://www.karniz-shtor-elektroprivodom.ru]карнизы для штор с электроприводом[/url] .

  6. buy viagra online: buy viagra online – viagra uk

    Brettesofe

    14 Oct 25 at 2:49 am

  7. электрокарниз москва [url=http://karniz-elektroprivodom.ru]http://karniz-elektroprivodom.ru[/url] .

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

    Diplomi_ajkt

    14 Oct 25 at 2:50 am

  9. техникум диплом купить [url=https://frei-diplom9.ru]техникум диплом купить[/url] .

    Diplomi_rcea

    14 Oct 25 at 2:51 am

  10. tpzpcfy

    14 Oct 25 at 2:51 am

  11. проект перепланировки нежилого помещения стоимость [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru/]http://pereplanirovka-nezhilogo-pomeshcheniya11.ru/[/url] .

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

    Diplomi_ajei

    14 Oct 25 at 2:52 am

  13. рулонные шторы на большие окна [url=https://rulonnaya-shtora-s-elektroprivodom.ru/]рулонные шторы на большие окна[/url] .

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

    Diplomi_wyPl

    14 Oct 25 at 2:54 am

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

    Diplomi_fjsr

    14 Oct 25 at 2:55 am

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

    Diplomi_eqMt

    14 Oct 25 at 2:56 am

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

    Diplomi_ewMi

    14 Oct 25 at 2:57 am

  18. карниз электроприводом штор купить [url=https://karniz-elektroprivodom.ru]https://karniz-elektroprivodom.ru[/url] .

  19. В «Новом Пути» используются только научно обоснованные и одобренные Минздравом РФ технологии кодирования. К основным направлениям относятся:
    Узнать больше – [url=https://kodirovanie-ot-alkogolizma-ehlektrostal6.ru/]кодирование от алкоголизма телефон[/url]

    ScottCet

    14 Oct 25 at 3:02 am

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

    Diplomi_ddSa

    14 Oct 25 at 3:02 am

  21. электрокарнизы [url=www.karniz-shtor-elektroprivodom.ru]электрокарнизы[/url] .

  22. согласование перепланировки нежилого помещения в нежилом здании [url=http://pereplanirovka-nezhilogo-pomeshcheniya11.ru]http://pereplanirovka-nezhilogo-pomeshcheniya11.ru[/url] .

  23. рулонные шторы на окна недорого [url=rulonnaya-shtora-s-elektroprivodom.ru]рулонные шторы на окна недорого[/url] .

  24. электрокарниз двухрядный [url=http://karniz-elektroprivodom.ru/]http://karniz-elektroprivodom.ru/[/url] .

  25. потолочник натяжные потолки отзывы [url=http://stretch-ceilings-samara.ru/]http://stretch-ceilings-samara.ru/[/url] .

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

    Diplomi_dgOl

    14 Oct 25 at 3:04 am

  27. куплю диплом цена [url=https://rudik-diplom7.ru]куплю диплом цена[/url] .

    Diplomi_gmPl

    14 Oct 25 at 3:05 am

  28. купить диплом для иностранцев [url=http://www.rudik-diplom13.ru]купить диплом для иностранцев[/url] .

    Diplomi_tfon

    14 Oct 25 at 3:05 am

  29. купить диплом о высшем образовании с занесением в реестр цены [url=https://frei-diplom2.ru]купить диплом о высшем образовании с занесением в реестр цены[/url] .

    Diplomi_pfEa

    14 Oct 25 at 3:06 am

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

    Diplomi_ktOi

    14 Oct 25 at 3:07 am

  31. купил диплом легально [url=frei-diplom3.ru]купил диплом легально[/url] .

    Diplomi_odKt

    14 Oct 25 at 3:08 am

  32. Scientists discovered something alarming seeping out from beneath the ocean around Antarctica
    [url=https://otzovik.com/reviews/zhilischniy_kooperativ_best_way_russia_sankt-peterburg/]гей порно член[/url]
    Planet-heating methane is escaping from cracks in the Antarctic seabed as the region warms, with new seeps being discovered at an “astonishing rate,” scientists have found, raising fears that future global warming predictions may have been underestimated.

    Huge amounts of methane lie in reservoirs that have formed over millennia beneath the seafloor around the world. This invisible, climate-polluting gas can escape into the water through fissures in the sea floor, often revealing itself with a stream of bubbles weaving their way up to the ocean surface.
    https://wap-tools.com/novosti/item/119517-gemcy-gem-cy-novaya-piramida-vasilenko
    домашний анальный секс
    Relatively little is known about these underwater seeps, how they work, how many there are, and how much methane reaches the atmosphere versus how much is eaten by methane-munching microbes living beneath the ocean.

    But scientists are keen to better understand them, as this super-polluting gas traps around 80 times more heat than carbon dioxide in its first 20 years in the atmosphere.

    Methane seeps in Antarctica are among the least understood on the planet, so a team of international scientists set out to find them. They used a combination of ship-based acoustic surveys, remotely operated vehicles and divers to sample a range of sites in the Ross Sea, a bay in Antarctica’s Southern Ocean, at depths between 16 and 790 feet.

    What they found surprised them. They identified more than 40 methane seeps in the shallow water of the Ross Sea, according to the study published this month in Nature Communications.

    Bubbles rising from a methane seep at Cape Evans, Antarctica. Leigh Tate, Earth Sciences New Zealand
    Many of the seeps were found at sites that had been repeatedly studied before, suggesting they were new. This may indicate a “fundamental shift” in the methane released in the region, according to the report.

    Methane seeps are relatively common globally, but previously there was only one confirmed active seep in the Antarctic, said Sarah Seabrook, a report author and a marine scientist at Earth Sciences New Zealand, a research organization. “Something that was thought to be rare is now seemingly becoming widespread,” she told CNN.

    Every seep they discovered was accompanied by an “immediate excitement” that was “quickly replaced with anxiety and concern,” Seabrook said.

    The fear is these seeps could rapidly transfer methane into the atmosphere, making them a source of planet-heating pollution that is not currently factored into future climate change predictions.

    The scientists are also concerned the methane could have cascading impacts on marine life.

    DonaldCix

    14 Oct 25 at 3:10 am

  33. купить диплом в чебоксарах [url=https://rudik-diplom10.ru]купить диплом в чебоксарах[/url] .

    Diplomi_cpSa

    14 Oct 25 at 3:12 am

  34. рулонные шторы купить москва недорого [url=http://www.rulonnaya-shtora-s-elektroprivodom.ru]рулонные шторы купить москва недорого[/url] .

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

    Diplomi_ohEa

    14 Oct 25 at 3:13 am

  36. Форматы вывода из запоя в Пушкино
    Исследовать вопрос подробнее – https://vyvod-iz-zapoya-pushkino7.ru/vyvod-iz-zapoya-kruglosutochno-v-pushkino

    CharlesBoync

    14 Oct 25 at 3:13 am

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

    Diplomi_nlOr

    14 Oct 25 at 3:14 am

  38. Very nice article. I absolutely love this website.

    Keep writing!

    @SEO_LINKK

    14 Oct 25 at 3:15 am

  39. купить диплом с реестром цена [url=www.frei-diplom3.ru/]купить диплом с реестром цена[/url] .

    Diplomi_nhKt

    14 Oct 25 at 3:15 am

  40. рулонные шторы на окна недорого [url=https://rulonnaya-shtora-s-elektroprivodom.ru/]рулонные шторы на окна недорого[/url] .

  41. I wanted to thank you for this good read!! I absolutely loved every little bit of it.
    I’ve got you saved as a favorite to look at new things you post…

    89BET

    14 Oct 25 at 3:16 am

  42. электрокарнизы москва [url=https://karniz-shtor-elektroprivodom.ru/]karniz-shtor-elektroprivodom.ru[/url] .

  43. карниз для штор с электроприводом [url=https://karniz-elektroprivodom.ru/]карниз для штор с электроприводом[/url] .

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

    Diplomi_poKt

    14 Oct 25 at 3:19 am

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

    Diplomi_gxOi

    14 Oct 25 at 3:22 am

  46. купить диплом в тамбове [url=https://www.rudik-diplom3.ru]купить диплом в тамбове[/url] .

    Diplomi_hzei

    14 Oct 25 at 3:23 am

  47. натяжные потолки цена самара [url=https://www.stretch-ceilings-samara.ru]https://www.stretch-ceilings-samara.ru[/url] .

  48. тканевый натяжной потолок самара [url=www.natyazhnye-potolki-samara-1.ru/]www.natyazhnye-potolki-samara-1.ru/[/url] .

  49. электрокарниз [url=https://karniz-shtor-elektroprivodom.ru]электрокарниз[/url] .

  50. рулонные шторы на пластиковые окна на кухню [url=rulonnaya-shtora-s-elektroprivodom.ru]рулонные шторы на пластиковые окна на кухню[/url] .

Leave a Reply