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 100,351 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 , , ,

100,351 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.rudik-diplom4.ru]купить диплом психолога[/url] .

    Diplomi_zmOr

    21 Oct 25 at 9:38 am

  2. Jaredvaf

    21 Oct 25 at 9:39 am

  3. Jaredvaf

    21 Oct 25 at 9:41 am

  4. топ диджитал агентств россии [url=https://luchshie-digital-agencstva.ru/]топ диджитал агентств россии[/url] .

  5. компания по продвижению сайтов [url=www.reiting-kompanii-po-prodvizheniyu-sajtov.ru]www.reiting-kompanii-po-prodvizheniyu-sajtov.ru[/url] .

  6. JamesDaync

    21 Oct 25 at 9:43 am

  7. диплом педагогического колледжа купить [url=www.frei-diplom12.ru]www.frei-diplom12.ru[/url] .

    Diplomi_mhPt

    21 Oct 25 at 9:44 am

  8. Antoniooscig

    21 Oct 25 at 9:44 am

  9. куплю диплом цена [url=https://www.rudik-diplom10.ru]куплю диплом цена[/url] .

    Diplomi_pbSa

    21 Oct 25 at 9:45 am

  10. Antoniomerty

    21 Oct 25 at 9:46 am

  11. топ сео компаний [url=www.reiting-seo-kompaniy.ru]топ сео компаний[/url] .

  12. Antoniooscig

    21 Oct 25 at 9:46 am

  13. Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
    Ознакомиться с полной информацией – https://www.kanoonsadat.ir/1398/10/14/chalesh-javanan-shahidsolimani

    PeterDrell

    21 Oct 25 at 9:48 am

  14. pin up yuklash android [url=https://www.pinup5007.ru]https://www.pinup5007.ru[/url]

    pin_up_uz_dtsr

    21 Oct 25 at 9:48 am

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

    Diplomi_xyOl

    21 Oct 25 at 9:48 am

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

    Diplomi_ddEa

    21 Oct 25 at 9:49 am

  17. купить диплом в кузнецке [url=www.rudik-diplom3.ru]www.rudik-diplom3.ru[/url] .

    Diplomi_ygei

    21 Oct 25 at 9:49 am

  18. Hello there! This is my first visit to your blog!
    We are a team of volunteers and starting a new project
    in a community in the same niche. Your blog provided us useful information to work on. You have done a wonderful job!

  19. Промокод 1xBet на сегодня. Промокод на 2026-2026. На официальном сайте букмекерской конторы 1xBet появилась опция, которая позволяет “бесплатно” ознакомиться с функционалом сайта и при удачном стечении обстоятельств еще и выиграть некую сумму денежных средств. Теперь это стало доступно по специальному промокоду 1хБет. Он дает возможность получить до 32500? (100$). Актуальные промокоды 1xBet на сегодня. Рабочие промокоды 1xBet в 2026 Все промокоды для 1хБет бесплатно: при регистрации, на ставку (купон), на бонус, на сегодня. 1xBet — одна из самых известных компаний в сфере беттинга. Свою популярность контора заработала во многом благодаря большому количеству специальных предложений. Так, к примеру, каждый пользователь может воспользоваться одним из действующих промокодов 1xBet на сегодня бесплатно. Ознакомиться с их полным перечнем можно в данной статье.

    Stanleyvonna

    21 Oct 25 at 9:50 am

  20. kraken tor
    кракен vk2

    JamesDaync

    21 Oct 25 at 9:51 am

  21. seo agencies list [url=http://www.reiting-seo-kompaniy.ru]http://www.reiting-seo-kompaniy.ru[/url] .

  22. VictorChash

    21 Oct 25 at 9:53 am

  23. Jaredvaf

    21 Oct 25 at 9:54 am

  24. раскрутка сайтов москва [url=https://reiting-seo-agentstv-moskvy.ru/]раскрутка сайтов москва[/url] .

  25. Profitez d’une offre 1xBet : beneficiez un bonus de 100% pour l’inscription jusqu’a 130€. Renforcez votre solde facilement en placant des paris avec un multiplicateur de cinq fois. Le code bonus est valide tout au long de l’annee 2026. Pour activer ce code, rechargez votre compte a partir de 1€. Decouvrez cette offre exclusive sur ce lien — 1xbet Code Bonus Sans Depot. Le code promo 1xBet aujourd’hui est disponible pour les joueurs du Cameroun, du Senegal et de la Cote d’Ivoire. Avec le 1xBet code promo bonus, obtenez jusqu’a 130€ de bonus promotionnel du code 1xBet. Ne manquez pas le dernier code promo 1xBet 2026 pour les paris sportifs et les jeux de casino.

    Marvinspaft

    21 Oct 25 at 9:55 am

  26. I was suggested this website by my cousin. I am not
    sure whether this post is written by him as nobody else know such detailed about my problem.
    You are wonderful! Thanks!

  27. seo раскрутка продвижение [url=https://reiting-runeta-seo.ru/]seo раскрутка продвижение[/url] .

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

    Diplomi_bmSa

    21 Oct 25 at 9:57 am

  29. pin up mobil ilova [url=https://www.pinup5007.ru]https://www.pinup5007.ru[/url]

    pin_up_uz_pjsr

    21 Oct 25 at 9:57 am

  30. The Supreme Court agreed Monday to decide if the federal government may bar certain drug users from owning guns or if the law violates the Second Amendment, taking up a second significant guns case of its current term.
    [url=https://kra-42cc.net]kra42[/url]
    The appeal represents a rare circumstance in which the Trump administration is defending a gun prohibition, which it described in briefing at the Supreme Court as a “narrow” limitation on one of “Americans’ most cherished freedoms.”
    [url=https://kra—42–at.ru]kra42 at[/url]
    The case centers on Ali Danial Hemani, a dual citizen of the United States and Pakistan, who was indicted in 2023 on a single count of violating the guns-and-drugs law after the FBI found a 9mm pistol, 60 grams of marijuana, and 4.7 grams of cocaine at his family home. This prosecution, the government told the high court, rested Hemani’s habitual use of marijuana.

    The court will likely hear arguments in the Hemani case next year and hand down a decision by the end of June.
    kra42 сс
    https://kra-42—at.ru
    A federal district court dismissed the charge, noting a landmark decision from the Supreme Court in 2022 that made it easier for Americans to carry handguns in public and also required similar gun prohibitions to have a connection to history.

    But just how closely analogous prosecutors must come to a historic law has been a matter of debate. Last year, for instance, the Supreme Court upheld a federal law that bars guns for Americans who are the subject of certain domestic abuse restraining orders, rejecting an argument pressed by gun rights groups that the prohibition violated the Second Amendment.

    The conservative 5th US Circuit Court of Appeals upheld that decision, holding in a brief decision that the historical record points only to laws that barred guns for Americans who are actively intoxicated or under the influence of drugs at the time of their arrest. The government, the court ruled, could not target habitual users.

    The Trump administration appealed that decision.

    KevinWal

    21 Oct 25 at 9:57 am

  31. Мы собрали для вас самые захватывающие факты из мира науки и истории. От малознакомых деталей до грандиозных событий — эта статья расширит ваш кругозор и подарит новое понимание того, как устроен наш мир.
    Интересует подробная информация – https://www.luke-hardisty.co.uk/blog_4-2

    JamesHipsy

    21 Oct 25 at 9:57 am

  32. Timothydrart

    21 Oct 25 at 9:58 am

  33. Hi, Neat post. There is a problem together with your
    website in web explorer, could test this? IE
    still is the market chief and a huge section of folks will
    leave out your great writing because of this problem.

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

    Diplomi_plMi

    21 Oct 25 at 9:59 am

  35. я купил диплом с проводкой [url=frei-diplom5.ru]я купил диплом с проводкой[/url] .

    Diplomi_vyPa

    21 Oct 25 at 9:59 am

  36. Antoniooscig

    21 Oct 25 at 9:59 am

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

    Diplomi_ssOl

    21 Oct 25 at 9:59 am

  38. кракен сайт
    kraken vpn

    JamesDaync

    21 Oct 25 at 10:00 am

  39. купить диплом в белово [url=rudik-diplom3.ru]rudik-diplom3.ru[/url] .

    Diplomi_vkei

    21 Oct 25 at 10:01 am

  40. купить диплом техникум [url=http://frei-diplom10.ru]купить диплом техникум[/url] .

    Diplomi_uuEa

    21 Oct 25 at 10:01 am

  41. Antoniomerty

    21 Oct 25 at 10:02 am

  42. медсестра которая купила диплом врача [url=http://frei-diplom13.ru/]медсестра которая купила диплом врача[/url] .

    Diplomi_uykt

    21 Oct 25 at 10:03 am

  43. Этот обзор дает возможность взглянуть на историю и науку под новым углом. Мы представляем редкие факты, неожиданные связи и значимые события, которые помогут вам глубже понять развитие цивилизации и роль человека в ней.
    Есть чему поучиться – https://iyashinosato.cm/?page_id=17

    Jesusheigh

    21 Oct 25 at 10:03 am

  44. Бесплатные промокоды. Давайте сразу начну с того, что перечислю несколько актуальных Промокодов 1xBet на сегодня. Смело вводите промокод в соответствующее поле и получайте прикольные «плюшки» в подарок от щедрого букмекера! Букмекерская контора 1xBet отличается от конкурентов наличием широкой программы лояльности. Важной ее частью является предоставление клиентам бонусов при вводе промокода. 1xbet casino промокод. В системе действует программа приветственных бонусов, благодаря которой каждый новичок получает определённую сумму за регистрацию на сайте. Такие акции действуют для казино и букмекерской конторы. Чтобы принять участие в приветственной программе, достаточно активировать при регистрации любой рабочий промокод.

    Stanleyvonna

    21 Oct 25 at 10:04 am

  45. Offre promotionnelle 1xBet pour 2026 : profitez d’un bonus de bienvenue de 100% jusqu’a 130€ en vous inscrivant des maintenant. Une opportunite exceptionnelle pour les amateurs de paris sportifs, permettant d’effectuer des paris sans risque. Inscrivez-vous avant la fin de l’annee 2026. Le lien ci-dessous vous menera vers le code promo officiel 1xBet — Code Promo 1xbet Pour L’inscription. Le code promo 1xBet vous permet d’activer un bonus d’inscription 1xBet exclusif et de commencer a parier avec un avantage. Le code promotionnel 1xBet 2026 est valable pour les paris sportifs, le casino en ligne et les tours gratuits. Decouvrez des aujourd’hui le meilleur code promo 1xBet et profitez du bonus de bienvenue 1xBet sans depot initial.

    Marvinspaft

    21 Oct 25 at 10:05 am

  46. Бонусы также отличаются по формату. Некоторые из них предоставляются новичкам. При регистрации на 1xBet, введите промокод и заберите 100% приветственный бонус до 32500 рублей.Компания 1xBet даёт возможность пользователям ставить и выигрывать с использованием акционных предложений. Это увеличивает вовлечённость к игровому процессу и гарантирует надежность игры.Актуальный промокод можно получить по этой ссылке — http://www.medtronik.ru/images/pages/1hbet_2021_promokod_pri_registracii.html.

    Jasonbrado

    21 Oct 25 at 10:06 am

  47. кракен маркетплейс
    кракен маркетплейс

    JamesDaync

    21 Oct 25 at 10:06 am

Leave a Reply