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 97,034 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 , , ,

97,034 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=soglasovanie-pereplanirovki-kvartiry4.ru]перепланировка квартир[/url] .

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

    Diplomi_ymOl

    19 Oct 25 at 1:19 am

  3. купить диплом в техникуме [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .

    Diplomi_dhea

    19 Oct 25 at 1:20 am

  4. проектная организация для перепланировки квартиры [url=https://proekt-pereplanirovki-kvartiry17.ru/]https://proekt-pereplanirovki-kvartiry17.ru/[/url] .

  5. Thematic systems in OMT’s syllabus attach mathematics tⲟ rate оf іnterests ⅼike technology, firing սp inquisitiveness аnd drive
    for leading exam scores.

    Experience flexible learning anytime, аnywhere thrοugh OMT’s tһorough online е-learning platform, including endless access tο video lessons and interactive quizzes.

    Ԍiven that mathematics plays a critical role іn Singapore’s economic development аnd development, investing іn specialized math tuition gears ᥙр students with tһe problem-solving skills neеded tߋ thrive in a competitive
    landscape.

    Tuition іn primary math iѕ key fοr PSLE preparation, as іt
    introduces innovative methods fοr dealing with non-routine
    problems that stump numerous candidates.

    Detailed comments from tuition instructors on technique attempts aids secondary pupils pick ᥙp
    from blunders, enhancing precision fⲟr the actual O Levels.

    Ꮃith normal simulated examinations аnd detailed responses, tuition aids junior college trainees
    determine ɑnd deal with weak points befоrе tһe actual А Levels.

    Wһat makes OMT extraordinary іs its proprietary educational program tһat lines up with MOE
    ѡhile introducing aesthetic һelp like bar modeling in ingenious methods
    fоr primary learners.

    OMT’s οn tһe internet community offers assistance leh, where yoս сan ask inquiries and enhance
    youг discovering for muсh bettеr grades.

    Singapore’s focus օn probⅼem-solving in mathematics
    exams mаkes tuition importɑnt foг creating crucial thinking
    abilities ƅeyond school һours.

    Hеre is mү blog post: singapore Primary 4 math Tuition

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

    Diplomi_ewOl

    19 Oct 25 at 1:21 am

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

    Diplomi_ooMt

    19 Oct 25 at 1:21 am

  8. мелбет зеркало сайта [url=http://melbetbonusy.ru/]мелбет зеркало сайта[/url] .

    melbet_crOi

    19 Oct 25 at 1:21 am

  9. If you wish for to take a good deal from this piece of writing then you have to apply such strategies to your
    won webpage.

  10. узаконить перепланировку цена [url=https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru]https://www.zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .

  11. shopandshine – Packages arrived earlier than expected which was an awesome surprise.

    Modesto Lazusky

    19 Oct 25 at 1:22 am

  12. купить диплом машиниста [url=rudik-diplom13.ru]купить диплом машиниста[/url] .

    Diplomi_smon

    19 Oct 25 at 1:23 am

  13. купить диплом электрика [url=rudik-diplom5.ru]купить диплом электрика[/url] .

    Diplomi_ckma

    19 Oct 25 at 1:24 am

  14. I’m gone to say to my little brother, that he should also pay a visit
    this website on regular basis to obtain updated from newest reports.

    유흥알바

    19 Oct 25 at 1:24 am

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

    Diplomi_pnei

    19 Oct 25 at 1:24 am

  16. согласование перепланировки квартиры под ключ цена [url=https://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]https://stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .

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

    Diplomi_zeOr

    19 Oct 25 at 1:26 am

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

    Diplomi_xber

    19 Oct 25 at 1:26 am

  19. поставка медоборудования [url=www.xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai]www.xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai[/url] .

  20. диплом нефтяного техникума купить [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .

    Diplomi_knea

    19 Oct 25 at 1:27 am

  21. купить диплом в ярославле [url=http://rudik-diplom11.ru]купить диплом в ярославле[/url] .

    Diplomi_ivMi

    19 Oct 25 at 1:27 am

  22. сколько стоит согласовать перепланировку квартиры [url=www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/]www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru/[/url] .

  23. Angelolix

    19 Oct 25 at 1:28 am

  24. yourtradingmentor – Fantastic mentorship tips and real-world trading help, highly recommend.

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

    Diplomi_deEa

    19 Oct 25 at 1:28 am

  26. Стационар «Частного Медика 24» в Воронеже — место, где пациент, страдающий от длительного запоя, получает не просто деньги-стоимость услуги, а полноценную помощь: диагностику, детоксикацию, медикаментозную поддержку и психологическую помощь с уважением к личному пространству и анонимности.
    Углубиться в тему – [url=https://vyvod-iz-zapoya-v-stacionare-voronezh24.ru/]быстрый вывод из запоя в стационаре[/url]

    Stuartbooms

    19 Oct 25 at 1:29 am

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

    Diplomi_ywei

    19 Oct 25 at 1:29 am

  28. проект перепланировки квартиры в москве [url=http://www.proekt-pereplanirovki-kvartiry17.ru]http://www.proekt-pereplanirovki-kvartiry17.ru[/url] .

  29. согласование перепланировок [url=http://soglasovanie-pereplanirovki-kvartiry3.ru/]http://soglasovanie-pereplanirovki-kvartiry3.ru/[/url] .

  30. cjukfcjdfybt [url=https://soglasovanie-pereplanirovki-kvartiry14.ru]https://soglasovanie-pereplanirovki-kvartiry14.ru[/url] .

  31. купить диплом в новочебоксарске [url=www.rudik-diplom5.ru]www.rudik-diplom5.ru[/url] .

    Diplomi_nfma

    19 Oct 25 at 1:32 am

  32. купить диплом техникума в Днепре [url=educ-ua7.ru]educ-ua7.ru[/url] .

    Diplomi_xoea

    19 Oct 25 at 1:32 am

  33. согласование перепланировки цена в москве [url=https://zakazat-proekt-pereplanirovki-kvartiry11.ru]https://zakazat-proekt-pereplanirovki-kvartiry11.ru[/url] .

  34. Адекватное лечение, комфорт и забота — так проходят дни в стационаре «Частного Медика 24» во время вывода из запоя.
    Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]стационар вывод из запоя в самаре[/url]

    GilbertCoeby

    19 Oct 25 at 1:35 am

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

    Diplomi_tfMi

    19 Oct 25 at 1:35 am

  36. Добро пожаловать в удивительный мир природы России!

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

    Смотрите сами:

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

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

    fixRow

    19 Oct 25 at 1:37 am

  37. купить диплом в нижнем тагиле [url=www.rudik-diplom5.ru]купить диплом в нижнем тагиле[/url] .

    Diplomi_eama

    19 Oct 25 at 1:37 am

  38. проект перепланировки квартиры для согласования цена [url=https://www.proekt-pereplanirovki-kvartiry17.ru]https://www.proekt-pereplanirovki-kvartiry17.ru[/url] .

  39. купить диплом в анжеро-судженске [url=www.rudik-diplom10.ru]www.rudik-diplom10.ru[/url] .

    Diplomi_agSa

    19 Oct 25 at 1:37 am

  40. Алкогольная зависимость требует правильного подхода. В новом материале Blogimam рассказывается о доступных методах кодирования в Саратове: от медикаментозных до психологических программ. Подробнее можно узнать тут – http://www.artlib.ru/index.php?id=26&idr=21&idt=52033

    Crystaldum

    19 Oct 25 at 1:37 am

  41. мелбет вход в личный кабинет [url=http://www.melbetbonusy.ru]http://www.melbetbonusy.ru[/url] .

    melbet_isOi

    19 Oct 25 at 1:38 am

  42. Minotaurus token’s DAO governance empowers users. Presale’s multi-crypto support widens access. Battling obstacles feels epic.
    minotaurus coin

    WilliamPargy

    19 Oct 25 at 1:39 am

  43. купить диплом с проводкой кого [url=https://www.frei-diplom6.ru]купить диплом с проводкой кого[/url] .

    Diplomi_oyOl

    19 Oct 25 at 1:39 am

  44. купить диплом воспитателя [url=https://www.rudik-diplom11.ru]купить диплом воспитателя[/url] .

    Diplomi_avMi

    19 Oct 25 at 1:40 am

  45. You can certainly see your expertise in the work you write.
    The arena hopes for even more passionate writers such as you who aren’t afraid to say how they believe.

    All the time follow your heart.

    xóc đĩa

    19 Oct 25 at 1:42 am

  46. медицинское оборудование [url=http://xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai/]http://xn—–6kcdfldbfd2aga1bqjlbbb4b4d7d1fzd.xn--p1ai/[/url] .

  47. куплю диплом медсестры в москве [url=www.frei-diplom14.ru]куплю диплом медсестры в москве[/url] .

    Diplomi_izoi

    19 Oct 25 at 1:43 am

  48. перепланировка квартиры в москве цена [url=https://www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru]https://www.stoimost-soglasovaniya-pereplanirovki-kvartiry.ru[/url] .

  49. регистрация перепланировки [url=http://soglasovanie-pereplanirovki-kvartiry14.ru/]http://soglasovanie-pereplanirovki-kvartiry14.ru/[/url] .

  50. купить диплом биолога [url=http://rudik-diplom1.ru]купить диплом биолога[/url] .

    Diplomi_fher

    19 Oct 25 at 1:44 am

Leave a Reply