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 111,193 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 , , ,

111,193 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://www.medicinskoe–oborudovanie.ru]медицинская аппаратура[/url] .

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

    Diplomi_bpEa

    27 Oct 25 at 11:18 am

  3. Henryamerb

    27 Oct 25 at 11:19 am

  4. наркологическая помощь [url=https://www.narkologicheskaya-klinika-24.ru]наркологическая помощь[/url] .

  5. What’s up, yeah this piece of writing is really
    nice and I have learned lot of things from it on the topic of blogging.
    thanks.

  6. Hey! I’m at work browsing your blog from my new apple iphone!

    Just wanted to say I love reading your blog and look forward to all your posts!
    Keep up the superb work!

    Here is my web site :: zinnat02

    zinnat02

    27 Oct 25 at 11:19 am

  7. Как купить Лсд в Кургане?Как думаете, нормально ли заказывать у https://lordfilmsh24.ru
    ? Цены хорошие, доставку обещают. Но переживаю насчет качества.

    Stevenref

    27 Oct 25 at 11:21 am

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

    Diplomi_vpPi

    27 Oct 25 at 11:24 am

  9. не в курсе купить онлайн мефедрон, экстази, бошки В скайпе ответил что вопрос решаеться,будем надеяться на лучшее,а насчёт красной темы-даже думать не хочеться.Всем мир!!!

    RichardDring

    27 Oct 25 at 11:25 am

  10. кракен vk3
    кракен обмен

    Henryamerb

    27 Oct 25 at 11:27 am

  11. I’m gone to tell my little brother, that he should also go to see this web site on regular basis to get updated from latest news update.
    https://confortvgb.com.ar/obzor-bukmekerskoy-kontory-melbet-2025/

    LewisGuatt

    27 Oct 25 at 11:27 am

  12. Henryamerb

    27 Oct 25 at 11:28 am

  13. аппараты медицинские [url=https://medicinskoe–oborudovanie.ru/]https://medicinskoe–oborudovanie.ru/[/url] .

  14. В обзорной статье вы найдете собрание важных фактов и аналитики по самым разнообразным темам. Мы рассматриваем как современные исследования, так и исторические контексты, чтобы вы могли получить полное представление о предмете. Погрузитесь в мир знаний и сделайте шаг к пониманию!
    А что дальше? – https://rtowndiner.com/product/bacon-cheese-fries

    Michaelzex

    27 Oct 25 at 11:29 am

  15. где купить диплом [url=http://www.rudik-diplom12.ru]где купить диплом[/url] .

    Diplomi_lhPi

    27 Oct 25 at 11:31 am

  16. наркологическая клиника [url=https://www.narkologicheskaya-klinika-24.ru]наркологическая клиника[/url] .

  17. kraken ссылка
    kraken СПб

    Henryamerb

    27 Oct 25 at 11:33 am

  18. где купить диплом железнодорожного техникума [url=https://frei-diplom10.ru]где купить диплом железнодорожного техникума[/url] .

    Diplomi_auEa

    27 Oct 25 at 11:38 am

  19. платный наркологический диспансер москва [url=www.narkologicheskaya-klinika-28.ru]www.narkologicheskaya-klinika-28.ru[/url] .

  20. E28BET میں خوش آمدید – ایشیا پیسیفک کی نمبر 1 آن لائن
    جوئے کی سائٹ۔ بونس، دلچسپ گیمز، اور قابل
    اعتماد آن لائن بیٹنگ کے تجربے کا لطف اٹھائیں۔

  21. кракен даркнет
    kraken зеркало

    Henryamerb

    27 Oct 25 at 11:39 am

  22. MichaelWoode

    27 Oct 25 at 11:39 am

  23. купить диплом автомобильного техникума [url=http://frei-diplom7.ru/]купить диплом автомобильного техникума[/url] .

    Diplomi_vjei

    27 Oct 25 at 11:40 am

  24. worldcityexpo.com – Color palette felt calming, nothing distracting, just focused, thoughtful design.

    Fidela Macmaster

    27 Oct 25 at 11:42 am

  25. linked internet page

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

  26. медицинское оборудование для больниц [url=https://medicinskoe–oborudovanie.ru/]medicinskoe–oborudovanie.ru[/url] .

  27. психолог нарколог в москве [url=http://www.narkologicheskaya-klinika-24.ru]http://www.narkologicheskaya-klinika-24.ru[/url] .

  28. more tips here

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

    more tips here

    27 Oct 25 at 11:45 am

  29. This post gives clear idea in support of the new visitors of
    blogging, that in fact how to do running a blog.

  30. kraken tor
    kraken vk6

    Henryamerb

    27 Oct 25 at 11:48 am

  31. Pretty nice post. I simply stumbled upon your
    blog and wished to mention that I’ve really enjoyed browsing your weblog
    posts. In any case I will be subscribing for your rss feed and I am hoping you write again soon!

  32. kraken сайт
    кракен зеркало

    Henryamerb

    27 Oct 25 at 11:48 am

  33. Juggling the demands of the fiat and crypto ecosystems has always been a major pain point for many in the GSA community.
    The constant friction and opaque processes between fiat and crypto platforms can severely slow down vital transactions.
    This is precisely why the Paybis fintech platform is worth a closer
    look. They aren’t just another crypto exchange;
    they’ve built a remarkably fluid gateway that masterfully consolidates both fiat
    and cryptocurrency banking. Imagine managing treasury across
    USD, EUR, and a vast selection of major digital assets—all
    from a single, secure dashboard. Their focus on robust security measures means you
    can transact with confidence. A brief comment can’t possibly do justice
    to the full scope of their offerings, especially their advanced tools
    for high-volume traders. To get a complete picture of how Paybis is solving
    the fiat-crypto problem, you absolutely need to read the detailed analysis in the
    full article. It breaks down their KYC process, supported regions, and API integration in a
    way that is incredibly insightful. I highly recommend check out the piece to see if their platform aligns with your operational requirements.
    It’s a comprehensive overview for anyone in our field looking to stay ahead
    of the curve. The link is in the main post—it’s well worth your time.

    website

    27 Oct 25 at 11:49 am

  34. right here on befine.click

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

  35. педагогический колледж купить диплом [url=http://frei-diplom7.ru/]педагогический колледж купить диплом[/url] .

    Diplomi_jiei

    27 Oct 25 at 11:51 am

  36. Купить диплом любого ВУЗа можем помочь. Купить диплом бакалавра в Сургуте – [url=http://diplomybox.com/kupit-diplom-bakalavra-v-surgute/]diplomybox.com/kupit-diplom-bakalavra-v-surgute[/url]

    Cazruuy

    27 Oct 25 at 11:52 am

  37. аппараты медицинские [url=https://medicinskoe–oborudovanie.ru]https://medicinskoe–oborudovanie.ru[/url] .

  38. I’m really enjoying the design and layout of your website.
    It’s a very easy on the eyes which makes it much more
    pleasant for me to come here and visit more often. Did you hire out a developer to create your theme?
    Exceptional work!

  39. Henryamerb

    27 Oct 25 at 11:53 am

  40. Great post! We are linking to this great article on our website.

    Keep up the good writing.

  41. Excellent beat ! I would like to apprentice even as you amend your website,
    how could i subscribe for a weblog site? The account aided me a appropriate deal.
    I had been a little bit acquainted of this your broadcast provided vivid clear idea

    먹튀

    27 Oct 25 at 11:55 am

  42. частная клиника наркологическая [url=www.narkologicheskaya-klinika-24.ru]www.narkologicheskaya-klinika-24.ru[/url] .

  43. Georgerah

    27 Oct 25 at 11:56 am

  44. [url=https://promodj.com/zenitbet/tracks/7801688/Melbet_zerkalo_rabochiy_dostup_k_saytu_Melbet_na_segodnya]melbet зеркало рабочее[/url] — мой go-to, когда основной домен «в тени». Работает стабильно, без перебоев, и главное — безопасно. Никаких фишингов, никаких «введите пароль повторно». Всё шифруется, всё под защитой. Ставлю в лайве, кэшаутю, вывожу — всё как по маслу. Для тех, кто ценит время и нервы — идеальный вариант.

  45. By celebrating small triumphes underway tracking, OMT nurtures а favorable connection ԝith
    mathematics, inspiring trainees fоr exam
    quality.

    Founded in 2013 by Mr. Justin Tan, OMT Math Tuition hаѕ assisted countless students ace tests ⅼike PSLE, O-Levels, and
    A-Levels ԝith tested analytical methods.

    Ꭲhe holistic Singapore Math technique, ᴡhich constructs multilayered analytical capabilities,
    highlights ѡhy math tuition іs essential
    for mastering thе curriculum ɑnd getting ready fоr future professions.

    Ϝor PSLE success, tuition ρrovides tailored assistance tⲟ weak aгeas,
    liҝе ratio and portion issues, preventing common risks tһroughout
    the test.

    Tuition promotes innovative analytic skills, vital fоr resolving tһe facility, multi-step concerns tһat define O Level
    math difficulties.

    Junior college math tuition іs essential for A Levels ɑs
    it gгows understanding օf advanced calculus subjects ⅼike
    assimilation techniques ɑnd differential formulas,
    ԝhich aгe main to the examination curriculum.

    OMT attracts attention ѡith its syllabus ⅽreated to sustain MOE’s by including mindfulness techniques t᧐ lower mathematics stress ɑnd anxiety durіng researches.

    Unlimited retries on tests sіa, perfect for mastering subjects ɑnd
    achieving those А grades in math.

    Ꮤith mathematics scores affeсting secondary school positionings,
    tuition іs essential for Singapore primary trainees ցoing for elite establishments tһrough PSLE.

    My site: coronation plaza math tuition

  46. Georgerah

    27 Oct 25 at 11:59 am

  47. I got this website from my pal who shared with me about this website and
    at the moment this time I am browsing this site
    and reading very informative content at this place.

    Cashinvenix

    27 Oct 25 at 11:59 am

  48. лечение зависимостей [url=https://www.narkologicheskaya-klinika-25.ru]лечение зависимостей[/url] .

  49. kraken обмен
    кракен зеркало

    Henryamerb

    27 Oct 25 at 12:00 pm

  50. An outstanding share! I’ve just forwarded this onto a friend who has been doing a little homework on this.

    And he in fact ordered me dinner simply because I found it for him…
    lol. So allow me to reword this…. Thanks for
    the meal!! But yeah, thanks for spending the time to talk about this matter here on your website.

    39bet

    27 Oct 25 at 12:01 pm

Leave a Reply