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 123,062 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 , , ,

123,062 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-diplom4.ru/]купить диплом проведенный[/url] .

    Diplomi_tsOl

    2 Nov 25 at 5:53 pm

  2. When I originally commented I clicked the “Notify me when new comments are added”
    checkbox and now each time a comment is added I get several e-mails with the same
    comment. Is there any way you can remove people from that service?
    Thank you!

    VU88

    2 Nov 25 at 5:53 pm

  3. 745648.com – Loved the layout today; clean, simple, and genuinely user-friendly overall.

    Jessie Camlin

    2 Nov 25 at 5:55 pm

  4. 1xbet yeni adresi [url=www.1xbet-giris-4.com]www.1xbet-giris-4.com[/url] .

  5. 1xbet g?ncel giri? [url=https://1xbet-giris-5.com/]1xbet g?ncel giri?[/url] .

  6. AbrahamERAME

    2 Nov 25 at 5:56 pm

  7. потолочкин ру натяжные потолки [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru]потолочкин ру натяжные потолки[/url] .

  8. บทความนี้เกี่ยวกับพวงหรีดดอกไม้ เป็นประโยชน์สุดๆ
    กำลังค้นหาข้อมูลเรื่องนี้อยู่พอดี ถือว่าเจอบทความดีๆ เลย

    จะเก็บข้อมูลนี้ไว้ใช้แน่นอน ขอบคุณอีกครั้งครับ/ค่ะ

    Alsoo visit my web blog – ร้านจัดดอกไม้งานศพ

  9. 1xbet giri? 2025 [url=http://1xbet-giris-2.com/]http://1xbet-giris-2.com/[/url] .

  10. легально купить диплом о высшем образовании [url=http://www.frei-diplom3.ru]легально купить диплом о высшем образовании[/url] .

    Diplomi_jvKt

    2 Nov 25 at 5:58 pm

  11. trusted online pharmacy UK: Uk Meds Guide – online pharmacy

    Johnnyfuede

    2 Nov 25 at 6:00 pm

  12. купить диплом вуза с проводкой [url=http://frei-diplom4.ru/]http://frei-diplom4.ru/[/url] .

    Diplomi_obOl

    2 Nov 25 at 6:00 pm

  13. PokerPhantom

    2 Nov 25 at 6:00 pm

  14. агентство продвижения сайтов [url=http://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]агентство продвижения сайтов[/url] .

  15. AlbertTeery

    2 Nov 25 at 6:02 pm

  16. 1xbet giri? linki [url=https://1xbet-giris-4.com]https://1xbet-giris-4.com[/url] .

  17. 1 x bet giri? [url=https://1xbet-giris-2.com]https://1xbet-giris-2.com[/url] .

  18. AlbertTeery

    2 Nov 25 at 6:04 pm

  19. “[url=https://peretyazhka-bel.ru/]Перетяжка диванов[/url]”
    Перетяжка позволяет вернуть предметам интерьера первоначальную свежесть.

    Такой подход не только экономит бюджет, но и позволяет индивидуализировать интерьер. Вы можете выбрать любой цвет и фактуру ткани под стиль комнаты.


    ### **2. Какие материалы лучше использовать?**
    Для перетяжки применяют различные ткани, отличающиеся износостойкостью и внешним видом. Хлопок и лён подойдут для помещений с невысокой нагрузкой.

    Также важно учитывать наполнитель, который влияет на комфорт. Поролон средней плотности обеспечит мягкость и долговечность.


    ### **3. Этапы профессиональной перетяжки**
    Процесс начинается с демонтажа старой обивки и оценки состояния каркаса. Мастер удаляет изношенную ткань и проверяет прочность конструкции.

    Далее выбирают материал и производят раскрой. Новая ткань кроится точно по размерам мебели, чтобы избежать перекосов.


    ### **4. Преимущества профессионального подхода**
    Обращение к специалистам гарантирует качество и долгий срок службы мебели. Профессионалы используют надёжные крепления и прочные швы.

    Кроме того, экономится время и исключаются ошибки. Только специалист сможет точно воспроизвести первоначальную форму мебели.


    ### **Спин-шаблон:**

    #### **1. Почему стоит выбрать перетяжку мебели?**
    – Смена ткани помогает сохранить любимый диван или кресло, избежав покупки новой мебели.
    – Это отличный способ адаптировать мебель под меняющиеся предпочтения в оформлении дома.

    #### **2. Какие материалы лучше использовать?**
    – Кожа и экокожа придают мебели благородный вид и просты в уходе.
    – Холофайбер и синтепон лучше сохраняют форму и упругость.

    #### **3. Этапы профессиональной перетяжки**
    – Старая ткань аккуратно снимается, а каркас проверяется на наличие повреждений.
    – Новая ткань кроится точно по размерам мебели, чтобы избежать перекосов.

    #### **4. Преимущества профессионального подхода**
    – Профессионалы используют надёжные крепления и прочные швы.
    – Самостоятельная перетяжка может привести к перекосам и быстрому износу.

    peretyazhk_wlKi

    2 Nov 25 at 6:05 pm

  20. купить проведенный диплом высокие [url=frei-diplom3.ru]купить проведенный диплом высокие[/url] .

    Diplomi_uaKt

    2 Nov 25 at 6:05 pm

  21. купить диплом с реестром вуза [url=http://www.frei-diplom4.ru]купить диплом с реестром вуза[/url] .

    Diplomi_syOl

    2 Nov 25 at 6:08 pm

  22. 1xbet giri? [url=https://1xbet-giris-5.com/]1xbet giri?[/url] .

  23. сео агентство [url=https://reiting-kompanii-po-prodvizheniyu-sajtov.ru/]сео агентство[/url] .

  24. Отличное качество реги! Советую! https://priv-church.ru/sankt-peterburg.html В итоге-“радостно” ожидал курьера эти дни,забавлянка придет мне позже желаемого… ;(

    ThomasronsE

    2 Nov 25 at 6:13 pm

  25. trusted online pharmacy UK: cheap medicines online UK – best UK pharmacy websites

    HaroldSHems

    2 Nov 25 at 6:13 pm

  26. Hey there, You have done a great job. I will definitely digg
    it and personally suggest to my friends. I am sure they’ll be benefited
    from this site.

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

    Diplomi_dgKr

    2 Nov 25 at 6:17 pm

  28. verified pharmacy coupon sites Australia [url=http://aussiemedshubau.com/#]best Australian pharmacies[/url] best Australian pharmacies

    Hermanengam

    2 Nov 25 at 6:17 pm

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

  30. прицеп 5440: Легендарная модель, проверенная временем. Надежность и простота обслуживания. Отличный выбор для опытных водителей.

    Richardaquat

    2 Nov 25 at 6:18 pm

  31. купить вкладыш к диплому техникума [url=https://frei-diplom10.ru]купить вкладыш к диплому техникума[/url] .

    Diplomi_yvEa

    2 Nov 25 at 6:18 pm

  32. куплю диплом младшей медсестры [url=https://frei-diplom14.ru]https://frei-diplom14.ru[/url] .

    Diplomi_huoi

    2 Nov 25 at 6:18 pm

  33. купить диплом в казани [url=https://www.rudik-diplom14.ru]купить диплом в казани[/url] .

    Diplomi_ezea

    2 Nov 25 at 6:19 pm

  34. Вызвать уничтожение тараканов горячим туманом на дом, кто знает номер?
    санитарная обработка

    KennethceM

    2 Nov 25 at 6:19 pm

  35. Complimenti per il contenuto! È sempre utile leggere approfondimenti sul mondo delle biciclette
    cargo. Anche noi di Green Speedy stiamo lavorando a nuove soluzioni modulari
    per rendere la mobilità urbana più accessibile ed ecologica.

  36. 1 xbet [url=https://1xbet-giris-5.com/]https://1xbet-giris-5.com/[/url] .

  37. pharmacy discount codes AU [url=http://aussiemedshubau.com/#]online pharmacy australia[/url] best Australian pharmacies

    Hermanengam

    2 Nov 25 at 6:23 pm

  38. top digital agency [url=http://www.luchshie-digital-agencstva.ru]top digital agency[/url] .

  39. продвижение сайта в топ 10 профессионалами [url=http://reiting-kompanii-po-prodvizheniyu-sajtov.ru]http://reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .

  40. What we’re covering
    [url=https://megaweb-13at.com]megaweb5.com[/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-16at.com]megaweb 4[/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://mgmarket8.net
    mgmarket5 at

    JamesBus

    2 Nov 25 at 6:27 pm

  41. Однако детская [url=https://www.petlovestudio.com/stomatologicheskaja-klinika-zdorovye-zuby-dlja/]https://www.petlovestudio.com/stomatologicheskaja-klinika-zdorovye-zuby-dlja/[/url] является важным учреждением здравоохранения для малышей. Потерять временную жевательную единицу можно и весьма раньше, к примеру, из-за кариеса, бруксизма, флюороза, травм, воспалительных болезней десен и т.д.

    RobertTub

    2 Nov 25 at 6:28 pm

  42. This design is spectacular! You obviously know how to
    keep a reader amused. Between your wit and
    your videos, I was almost moved to start my own blog (well, almost…HaHa!) Wonderful job.

    I really loved what you had to say, and more than that, how you presented it.
    Too cool!

  43. 1xbetgiri? [url=1xbet-giris-2.com]1xbet-giris-2.com[/url] .

  44. 1xbet tr [url=http://1xbet-giris-4.com/]1xbet tr[/url] .

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

    Diplomi_auEa

    2 Nov 25 at 6:31 pm

  46. hey there and thank you for your information – I’ve definitely
    picked up anything new from right here. I did however expertise some technical points using this website, since I experienced to
    reload the site a lot of times previous to I could get
    it to load properly. I had been wondering if your web host is OK?
    Not that I am complaining, but sluggish loading instances times will sometimes affect your
    placement in google and can damage your high-quality score
    if ads and marketing with Adwords. Anyway I am
    adding this RSS to my e-mail and can look out for much more of your respective exciting
    content. Make sure you update this again soon.

  47. UK online pharmacies list: affordable medications UK – UkMedsGuide

    Johnnyfuede

    2 Nov 25 at 6:36 pm

  48. this link

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

    this link

    2 Nov 25 at 6:36 pm

  49. “[url=https://peretyazhka-bel.ru/]Перетяжка прямых диванов[/url]”
    Перетяжка позволяет вернуть предметам интерьера первоначальную свежесть.

    Такой подход не только экономит бюджет, но и позволяет индивидуализировать интерьер. Вы можете выбрать любой цвет и фактуру ткани под стиль комнаты.


    ### **2. Какие материалы лучше использовать?**
    Для перетяжки применяют различные ткани, отличающиеся износостойкостью и внешним видом. Микрофибра и жаккард устойчивы к истиранию и подходят для ежедневного использования.

    Также важно учитывать наполнитель, который влияет на комфорт. Поролон средней плотности обеспечит мягкость и долговечность.


    ### **3. Этапы профессиональной перетяжки**
    Процесс начинается с демонтажа старой обивки и оценки состояния каркаса. Сначала снимают старую обивку, затем осматривают деревянные и металлические элементы.

    Далее выбирают материал и производят раскрой. Раскрой выполняется с запасом для удобства последующего натяжения.


    ### **4. Преимущества профессионального подхода**
    Обращение к специалистам гарантирует качество и долгий срок службы мебели. Мастера подбирают оптимальные методы перетяжки для разных типов мебели.

    Кроме того, экономится время и исключаются ошибки. Только специалист сможет точно воспроизвести первоначальную форму мебели.


    ### **Спин-шаблон:**

    #### **1. Почему стоит выбрать перетяжку мебели?**
    – Смена ткани помогает сохранить любимый диван или кресло, избежав покупки новой мебели.
    – Новая обивка позволяет полностью изменить дизайн старой мебели.

    #### **2. Какие материалы лучше использовать?**
    – Хлопок и лён подойдут для помещений с невысокой нагрузкой.
    – Поролон средней плотности обеспечит мягкость и долговечность.

    #### **3. Этапы профессиональной перетяжки**
    – Сначала снимают старую обивку, затем осматривают деревянные и металлические элементы.
    – Обивочный материал тщательно размечается и вырезается с учётом всех деталей.

    #### **4. Преимущества профессионального подхода**
    – Мастера подбирают оптимальные методы перетяжки для разных типов мебели.
    – Только специалист сможет точно воспроизвести первоначальную форму мебели.

    peretyazhk_kvKi

    2 Nov 25 at 6:36 pm

  50. продвижение сайта агентство [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru/]продвижение сайта агентство[/url] .

Leave a Reply