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 89,931 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 , , ,

89,931 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. Charleston Car Accident Lawyer: Your Advocate After a Crash
    Car accidents can change your life in an instant—leaving you
    with physical injuries, emotional trauma, and overwhelming financial burdens.
    If you’ve been injured in a car wreck in Charleston, South Carolina, you don’t have to face the aftermath alone.
    A skilled Charleston car accident lawyer
    can help you fight for the compensation you deserve and guide you through every step of the legal process.

    Why Hire a Charleston Car Accident Attorney?
    Whether it was a minor fender-bender or a catastrophic collision, dealing with insurance companies can be exhausting.

    They may try to minimize your claim or deny it altogether.
    A knowledgeable personal injury attorney in Charleston will:

    Investigate the accident scene

    Gather evidence such as traffic cam footage and witness statements

    Handle all communication with insurance adjusters

    Calculate damages for medical bills, lost wages, pain and
    suffering, and more

    Represent you in court if a fair settlement cannot be reached

    I have been surfing online more than 4 hours today,
    yet I never found any interesting article
    like yours. It is pretty worth enough for me. Personally, if all web owners and bloggers made good content as you did, the web will be much more useful than ever before.

    What Makes Charleston Unique for Car Accident Claims?
    Charleston’s historic roads and growing population lead to a unique mix of traffic challenges.
    From the Ravenel Bridge to busy intersections downtown, collisions happen every day.

    South Carolina law allows injured victims to pursue compensation—but strict deadlines apply.
    This is why hiring a local car accident lawyer with experience in Charleston’s courts is critical.

    I couldn’t refrain from commenting. Well written!

    Common Injuries from Car Accidents
    Auto accidents can cause both visible and invisible injuries,
    such as:

    Whiplash and neck trauma

    Concussions or traumatic brain injuries (TBI)

    Broken bones

    Back and spinal cord injuries

    Emotional distress or PTSD

    Even if your injuries seem minor, it’s important to seek medical
    attention and consult a legal professional. A Charleston car accident attorney will work to ensure every aspect of your recovery is accounted for.

    I’ll immediately take hold of your rss feed as I can not in finding
    your email subscription link or e-newsletter
    service. Do you’ve any? Kindly permit me recognize in order that I may
    just subscribe. Thanks.

    Contact a Trusted Charleston Car Accident Lawyer Today
    If you or a loved one has been involved in a car accident in Charleston, don’t wait.
    Reach out to a qualified personal injury attorney today to schedule a free consultation. Many car accident lawyers work on a contingency fee basis—meaning you
    pay nothing unless they win your case.

    Let a local legal team take the pressure off your shoulders and
    fight for the justice you deserve.

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

    Diplomi_jfei

    14 Oct 25 at 6:44 pm

  3. электрокарнизы для штор купить в москве [url=https://elektrokarnizy797.ru]https://elektrokarnizy797.ru[/url] .

  4. We’re a gaggle of volunteers and opening a brand
    new scheme in our community. Your web site provided us with helpful info
    to work on. You’ve done an impressive activity and our whole community will likely be thankful to you.

    situs scam

    14 Oct 25 at 6:46 pm

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

    Diplomi_owPi

    14 Oct 25 at 6:47 pm

  6. перепланировка нежилого здания [url=www.pereplanirovka-nezhilogo-pomeshcheniya9.ru]перепланировка нежилого здания[/url] .

  7. Estou completamente apaixonado por PlayPIX Casino, proporciona uma aventura pulsante. O catalogo e exuberante e multifacetado, com slots de design inovador. Com uma oferta inicial para impulsionar. O suporte ao cliente e excepcional, acessivel a qualquer momento. O processo e simples e elegante, as vezes bonus mais variados seriam incriveis. No fim, PlayPIX Casino e essencial para jogadores para entusiastas de jogos modernos ! Acrescentando que o design e moderno e vibrante, adiciona um toque de conforto. Outro destaque o programa VIP com niveis exclusivos, assegura transacoes confiaveis.
    Descobrir mais|

    BlazeRhythmQ6zef

    14 Oct 25 at 6:49 pm

  8. абонемент в фитнес клуб абонемент в фитнес клуб

    fitnes-klub-523

    14 Oct 25 at 6:50 pm

  9. потолочкин отзывы клиентов самара [url=natyazhnye-potolki-samara-2.ru]natyazhnye-potolki-samara-2.ru[/url] .

  10. Why viewers still make use of to read news papers when in this technological
    globe the whole thing is accessible on web?

  11. потолочкин отзывы клиентов самара [url=www.stretch-ceilings-samara-1.ru/]www.stretch-ceilings-samara-1.ru/[/url] .

  12. потолочкин натяжные потолки самара отзывы [url=http://www.natyazhnye-potolki-samara-2.ru]http://www.natyazhnye-potolki-samara-2.ru[/url] .

  13. согласование перепланировки нежилого помещения в москве [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru]https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .

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

    Diplomi_bgei

    14 Oct 25 at 6:58 pm

  15. Nathanhip

    14 Oct 25 at 6:58 pm

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

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

  18. Thanks for the marvelous posting! I really enjoyed reading it, you are a great author.
    I will be sure to bookmark your blog and will eventually come back very
    soon. I want to encourage you to continue your great posts, have a nice weekend!

  19. купить диплом механика [url=www.rudik-diplom15.ru]купить диплом механика[/url] .

    Diplomi_mjPi

    14 Oct 25 at 7:05 pm

  20. pjvefgc

    14 Oct 25 at 7:06 pm

  21. электрокарнизы [url=elektrokarnizy797.ru]электрокарнизы[/url] .

  22. Wow that was strange. I just wrote an really long comment but after I clicked submit my comment didn’t
    appear. Grrrr… well I’m not writing all that over again. Regardless, just wanted to say fantastic blog!

    bokep SMA

    14 Oct 25 at 7:08 pm

  23. Сегодня мы отправимся на виртуальную экскурсию в уникальные уголки природы России.

    Зацепил материал про Изучение ООПТ России: парки, заповедники, водоемы.

    Вот, делюсь ссылкой:

    [url=https://alloopt.ru]https://alloopt.ru[/url]

    Что думаете о красоте природы России? Делитесь мнениями!

    fixRow

    14 Oct 25 at 7:08 pm

  24. I do not even know how I ended up here, but I thought this post was great.
    I do not know who you are but definitely you’re going to a
    famous blogger if you aren’t already 😉 Cheers!

    pepek

    14 Oct 25 at 7:09 pm

  25. потолки [url=https://natyazhnye-potolki-samara-1.ru/]https://natyazhnye-potolki-samara-1.ru/[/url] .

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

  27. online sportwetten ohne lugas

    Also visit my web-site – Wetten öSterreich

  28. перепланировка нежилого помещения в многоквартирном доме [url=pereplanirovka-nezhilogo-pomeshcheniya9.ru]перепланировка нежилого помещения в многоквартирном доме[/url] .

  29. потолочкин натяжные потолки отзывы клиентов самара [url=https://natyazhnye-potolki-samara-1.ru/]natyazhnye-potolki-samara-1.ru[/url] .

  30. $MTAUR coin stands out with its audited security focus. Extending vesting for bonuses is a no-brainer. Maze battles against creatures? Count me in. minotaurus token

    WilliamPargy

    14 Oct 25 at 7:12 pm

  31. potolochkin ru [url=http://stretch-ceilings-samara.ru/]http://stretch-ceilings-samara.ru/[/url] .

  32. Правильный подбор лекарственных средств позволяет не только уменьшить проявления синдрома отмены, но и стабилизировать эмоциональное состояние пациента, снижая риск срывов. Реабилитационные программы включают физиотерапию, спортивные занятия и коррекцию образа жизни, что способствует полноценному восстановлению организма.
    Ознакомиться с деталями – [url=https://lechenie-narkomanii-tver0.ru/]принудительное лечение наркомании тверь[/url]

    MatthewNoG

    14 Oct 25 at 7:13 pm

  33. Attractive section of content. I just stumbled
    upon your web site and in accession capital to assert that I get
    in fact enjoyed account your blog posts. Any way I’ll be subscribing
    to your augment and even I achievement you access
    consistently fast.

    useful source

    14 Oct 25 at 7:15 pm

  34. Наркологическая клиника в Твери представляет собой современное медицинское учреждение, специализирующееся на диагностике и лечении алкогольной, наркотической и других видов зависимости. В клинике «Гелиос» применяются инновационные методы терапии, направленные на полное восстановление физического и психологического состояния пациентов.
    Выяснить больше – https://narkologicheskaya-klinika-tver0.ru/narkolog-tver-anonimno/

    Briangaw

    14 Oct 25 at 7:16 pm

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

    Diplomi_wwsa

    14 Oct 25 at 7:18 pm

  36. Hey there! Do you use Twitter? I’d like to follow you if that would
    be ok. I’m definitely enjoying your blog and look
    forward to new updates.

  37. самара натяжные потолки [url=https://natyazhnye-potolki-samara-2.ru]самара натяжные потолки[/url] .

  38. электрокарниз двухрядный цена [url=www.elektrokarnizy797.ru/]www.elektrokarnizy797.ru/[/url] .

  39. согласование перепланировки в нежилом помещении [url=https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru]https://www.pereplanirovka-nezhilogo-pomeshcheniya9.ru[/url] .

  40. sportwetten online wetten mit paysafecard (vegasdombankietowy.pl) bonus ohne einzahlung

  41. купить диплом машиниста [url=http://rudik-diplom14.ru/]купить диплом машиниста[/url] .

    Diplomi_alea

    14 Oct 25 at 7:27 pm

  42. Для купирования абстинентного синдрома и нормализации функций организма применяются препараты, которые оказывают детоксицирующее, нейропротекторное и общеукрепляющее действие. Врач подбирает лекарства индивидуально с учетом состояния пациента и наличия сопутствующих заболеваний.
    Получить больше информации – [url=https://narkologicheskaya-klinika-vladimir0.ru/]наркологические клиники алкоголизм владимир[/url]

    Jaimenef

    14 Oct 25 at 7:28 pm

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

  44. Good day! This post could not be written any better! Reading through
    this post reminds me of my previous room mate! He always kept chatting about this.
    I will forward this article to him. Fairly
    certain he will have a good read. Many thanks for sharing!

    toto

    14 Oct 25 at 7:29 pm

  45. Hello my loved one! I want to say that this post is awesome, great written and include approximately all vital infos.
    I’d like to look extra posts like this .

    Click here

    14 Oct 25 at 7:29 pm

  46. перепланировка нежилых помещений [url=www.pereplanirovka-nezhilogo-pomeshcheniya9.ru/]перепланировка нежилых помещений[/url] .

  47. самара натяжные потолки [url=https://natyazhnye-potolki-samara-2.ru]самара натяжные потолки[/url] .

  48. женский фитнес клуб сеть фитнес клубов

    fitnes-klub-754

    14 Oct 25 at 7:32 pm

  49. Nathanhip

    14 Oct 25 at 7:33 pm

  50. equgcwo

    14 Oct 25 at 7:34 pm

Leave a Reply