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 114,726 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 , , ,

114,726 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. kraken darknet
    kraken РФ

    Henryamerb

    28 Oct 25 at 11:58 pm

  2. комплексное продвижение сайтов москва [url=optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru]комплексное продвижение сайтов москва[/url] .

  3. cd player alarm [url=https://www.alarm-radio-clocks.com]https://www.alarm-radio-clocks.com[/url] .

  4. Very soon this web page will be famous amid all blog visitors, due
    to it’s fastidious articles or reviews

  5. устранение протечек в подвале [url=www.gidroizolyaciya-cena-8.ru/]устранение протечек в подвале[/url] .

  6. маркетинг в интернете блог [url=https://statyi-o-marketinge7.ru]https://statyi-o-marketinge7.ru[/url] .

  7. мелбет [url=www.melbetofficialsite.ru/]мелбет[/url] .

    bk melbet_fuEa

    29 Oct 25 at 12:01 am

  8. услуги гидроизоляции подвала [url=https://www.gidroizolyaciya-podvala-cena.ru]https://www.gidroizolyaciya-podvala-cena.ru[/url] .

  9. seo аудит веб сайта [url=https://www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru]seo аудит веб сайта[/url] .

  10. Oh, mathematics acts ⅼike the base block іn primary learning,
    assisting children іn spatial reasoning to building routes.

    Oh dear, minus strong maths іn Junior College, no matter tօp establishment children mіght falter at
    secondary algebra, tһuѕ build this promрtly leh.

    Anglo-Chinese Junior College stands аs a beacon of balanced
    education, blending strenuous academics ѡith a
    nurturing Christian principles tһat motivates moral integrity
    ɑnd individual development. Тhe college’ѕ ѕtate-of-the-art facilities and skilled professors support outstanding performance іn ƅoth arts and sciences, wіth
    trainees often attaining ttop awards. Througһ іtѕ focus on sports аnd performing arts, trainees establish discipline, camaraderie, аnd a passion for excellence
    beуond the classroom. International collaborations and exchange chances
    enhance tһe learning experience, fostering worldwide awareness аnd cultural gratitude.
    Alumni flourish іn varied fields, testimony to tһе college’s role in shaping principled leaders ɑll set to contribute favorably tⲟ society.

    St. Joseph’ѕ Institution Junior College upholds treasured Lasallian traditions оf faith, service, and
    intellectual curiosity, developing ɑn empowering environment wheгe trainees pursue understanding
    ԝith passion and dedicate tһemselves tߋ uplifting otһers
    thгough thoughtful actions. Ꭲhе incorporated program ensures а fluid development
    frоm secondary to pre-university levels, ԝith a concentrate on bilingual proficiency аnd innovative curricula supported Ƅy facilities ⅼike state-of-thе-art carrying ⲟut arts centers and science
    research study labs that motivate imaginative ɑnd analytical excellence.

    Global immersion experiences, consisting ⲟf worldwide service trips ɑnd cultural exchange programs,
    widen students’ horizons, enhance linguistic skills, аnd
    cultivate ɑ deep appreciation fοr diverse worldviews.
    Opportunities f᧐r innovative research, leadership functions іn student companies, аnd mentorship from accomplished faculty
    develop confidence, vital thinking, аnd a commitment to
    long-lasting learning. Graduates ɑrе understood for their empathy and higһ accomplishments, protecting рlaces in prominent universities
    ɑnd standing out in professions tһat line up with tһe college’ѕ
    values of service and intellectual rigor.

    Ⅾon’t take lightly lah, link a reputable Junior College alongside
    mathematics excellence fⲟr guarantee superior
    A Levels marks ɑnd effortless chаnges.
    Parents, worry ɑbout the disparity hor, mathematics foundation proves critical аt
    Junior College to comprehending іnformation, crucial f᧐r today’ѕ online market.

    Listen ᥙp, Singapore folks, mathematics іs perhaps the mߋst essential primary
    topic, fostering imagination throuցh problem-solving to groundbreaking careers.

    Wah lao, еvеn whetһer establishment rekains
    hіgh-end, math serves аs the make-or-break topic fⲟr building poise witһ calculations.

    Aiyah, primary math educates everyday applications liкe budgeting, tһus ensure yօur child ցets it correctly ƅeginning earⅼʏ.

    Withⲟut Math proficiency, options fοr economics majors shrink dramatically.

    Ⅾon’t take lightly lah, pair a gooɗ Junior College witһ
    math proficiency іn order to guarantee һigh А Levels resuⅼts аs weⅼl as effortless сhanges.

    Look ɑt my web site secondary school

    secondary school

    29 Oct 25 at 12:03 am

  11. Henryamerb

    29 Oct 25 at 12:03 am

  12. аудит продвижения сайта [url=https://www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]аудит продвижения сайта[/url] .

  13. руководства по seo [url=http://statyi-o-marketinge6.ru/]руководства по seo[/url] .

  14. Greetings! I’ve been following your website for some
    time now and finally got the bravery to go ahead and give you
    a shout out from Kingwood Tx! Just wanted to say keep up the excellent
    job!

  15. seo partner [url=https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru/]optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru[/url] .

  16. торкретирование цена [url=http://torkretirovanie-1.ru/]торкретирование цена[/url] .

  17. When I initially left a comment I seem to have clicked on the
    -Notify me when new comments are added- checkbox and now each time
    a comment is added I receive 4 emails with the same comment.
    Perhaps there is a way you can remove me from that service?

    Appreciate it!

  18. kraken вход
    kraken РФ

    Henryamerb

    29 Oct 25 at 12:09 am

  19. top clock radio [url=https://alarm-radio-clocks.com]https://alarm-radio-clocks.com[/url] .

  20. [url=https://ocean-finance.pl/leasing/maszyny/]https://ocean-finance.pl/leasing/maszyny/[/url] can take up to placement, is quite accessible . Just click on picture of the game where you desire play, and find between demo mode and the game for real funds.

    EdithLag

    29 Oct 25 at 12:11 am

  21. seo partners [url=https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru]https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru[/url] .

  22. comprare medicinali online legali: Spedra prezzo basso Italia – FarmaciaViva

    Jamesaleds

    29 Oct 25 at 12:11 am

  23. Hi there! I know this is somewhat off topic but I was wondering if
    you knew where I could locate a captcha plugin for my comment form?
    I’m using the same blog platform as yours and I’m having trouble finding one?

    Thanks a lot!

  24. гидроизоляция цена за рулон [url=www.gidroizolyaciya-cena-8.ru/]гидроизоляция цена за рулон[/url] .

  25. торкретирование стен цена [url=https://torkretirovanie-1.ru/]https://torkretirovanie-1.ru/[/url] .

  26. Operation Game Canada: A classic, fun-filled board game where players test their precision by removing ailments from the patient without triggering the buzzer: Operation game tips and tricks

    GabrielLyday

    29 Oct 25 at 12:16 am

  27. Calvindreli

    29 Oct 25 at 12:17 am

  28. продвижения сайта в google [url=www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru/]продвижения сайта в google[/url] .

  29. kraken vk5
    kraken 2025

    Henryamerb

    29 Oct 25 at 12:18 am

  30. гидроизоляция подвала под ключ [url=www.gidroizolyaciya-podvala-cena.ru]www.gidroizolyaciya-podvala-cena.ru[/url] .

  31. Calvindreli

    29 Oct 25 at 12:19 am

  32. best cd alarm clock radio [url=https://alarm-radio-clocks.com/]https://alarm-radio-clocks.com/[/url] .

  33. magnificent issues altogether, you simply won a new reader.
    What might you recommend in regards to your submit that you made some days ago?
    Any positive?

  34. мелбет онлайн [url=https://melbetofficialsite.ru]мелбет онлайн[/url] .

    bk melbet_bqEa

    29 Oct 25 at 12:22 am

  35. кракен вход
    kraken qr code

    Henryamerb

    29 Oct 25 at 12:23 am

  36. торкретирование стен цена за м2 [url=https://torkretirovanie-1.ru]https://torkretirovanie-1.ru[/url] .

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

    [url=https://avtomaticheskie-zhalyuzi-s-privodom.ru/]электрические жалюзи на окна внутренние Прокарниз[/url] обеспечивают удобство и стиль в вашем доме, позволяя управлять светом одним нажатием кнопки.
    Автоматические жалюзи на окна с электроприводом становятся все более популярными. Эти изделия обеспечивают высокий уровень комфорта и функциональности для любого интерьера. Такие жалюзи могут управляться с помощью пульта дистанционного управления или смартфона. Это значительно упрощает процесс их использования.

    Еще одним важным аспектом является экономия энергии. С правильной эксплуатацией этих жалюзи можно значительно уменьшить расходы на обогрев и кондиционирование. С автоматическими жалюзи будет проще контролировать температуру в помещении. Таким образом, они не только удобны, но и экономически оправданы.

    Установка автоматических жалюзи может проводиться как опытными мастерами, так и самостоятельно. Вам решать, устанавливать ли жалюзи самостоятельно или обратиться к специалистам. Для самостоятельной установки необходимо точно придерживаться рекомендаций производителей. Следуя инструкциям, вы сможете избежать ошибок и гарантировать корректное функционирование системы.

  38. I want to to thank you for this excellent read!! I certainly loved every bit of it.
    I have you bookmarked to look at new things you post…

  39. seo network [url=www.optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru]seo network[/url] .

  40. Hey There. I found your blog using msn. This is an extremely well written article.
    I will make sure to bookmark it and come back to read more of your
    useful information. Thanks for the post. I’ll certainly return.

  41. купить диплом в каспийске [url=www.rudik-diplom14.ru/]www.rudik-diplom14.ru/[/url] .

    Diplomi_jmea

    29 Oct 25 at 12:28 am

  42. торкретирование москва [url=https://www.torkretirovanie-1.ru]https://www.torkretirovanie-1.ru[/url] .

  43. Henryamerb

    29 Oct 25 at 12:29 am

  44. Valuable info. Lucky me I discovered your web site
    by accident, and I am surprised why this twist of fate didn’t took place earlier!
    I bookmarked it.

  45. hd tabletop radio [url=http://alarm-radio-clocks.com/]http://alarm-radio-clocks.com/[/url] .

  46. Calvindreli

    29 Oct 25 at 12:30 am

  47. Расташоп

    29 Oct 25 at 12:30 am

  48. технического аудита сайта [url=http://optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru/]http://optimizaciya-i-seo-prodvizhenie-sajtov-moskva.ru/[/url] .

  49. компании занимающиеся продвижением сайтов [url=https://optimizaciya-i-seo-prodvizhenie-sajtov-moskva-1.ru]компании занимающиеся продвижением сайтов[/url] .

Leave a Reply