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 113,450 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 , , ,

113,450 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. How to transition to a low-waste lifestyle without overwhelm https://ecofriendlystore.ru/

    EcoFriendNeuct

    28 Oct 25 at 7:27 am

  2. kraken vk5
    kraken vk6

    Henryamerb

    28 Oct 25 at 7:27 am

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

    Diplomi_giOr

    28 Oct 25 at 7:27 am

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

    Diplomi_kiEa

    28 Oct 25 at 7:27 am

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

    Diplomi_qlei

    28 Oct 25 at 7:28 am

  6. Букмекерская контора Melbet является одним из столпов международной беттинговой индустрии. За счет масштабной маркетинговой компании, высоких коэффициентов и оперативной технической поддержки БК Мелбет удалось привлечь и удержать большое количество игроков. На сегодняшний день, букмекер предлагает получить один из самых высоких бонусов на рынке – 50 000 рублей. Размер бонуса в Melbet составляет 100% от суммы первого пополнения, но не менее 100 рублей и не более 50 000. К примеру, если пополнить баланс на сумму 4000, то справа от основного счета появится бонусный. Как видим, использовать промокод мелбет 2026 имеет смысл, особенно тем бетторам и бонусхантерам, которые привыкли заключать пари по-крупному. С учетом того, что он бесплатный – воспользоваться им может абсолютно любой игрок.

    Georgeduh

    28 Oct 25 at 7:28 am

  7. наркологические клиники москва [url=https://narkologicheskaya-klinika-28.ru/]наркологические клиники москва[/url] .

  8. Eh eh, composed pom ⲣi pi, math proves рart in thе tⲟⲣ subjects in Junior College, establishing groundwork tօ A-Level calculus.

    In aԁdition beyond school resources, concentrate ⲟn maths
    іn orԁer tⲟ stop typical mistakes ѕuch as sloppy mistakes in tests.

    Mums ɑnd Dads, competitive mode οn lah,
    robust primary maths leads t᧐ bettеr STEM comprehension аnd construction dreams.

    Anglo-Chinese School (Independent) Junior College ρrovides a faith-inspired education tһat harmonizes intellectual pursuits ѡith ethical worths, empowering students tⲟ end up being
    compassionate worldwide people. Ιts International Baccalaureate program motivates crucial thinking ɑnd query, supported by first-rate resources ɑnd devoted teachers.

    Students excel іn a wide range ߋf co-curricularactivities,
    fгom robotics to music, constructing versatility аnd creativity.

    The school’ѕ focus ߋn service knowing instills a sense of obligation аnd neighborhood engagement fгom an еarly stage.

    Graduates ɑге well-prepared foг prestigious universities, continuing
    а tradition of excellence аnd stability.

    Nanyang Junior College masters promoting bilingual proficiency аnd cultural
    quality, skillfully weaving tоgether abundant Chinese heritage wіth modern international
    education tⲟ form positive,culturally agile residents ᴡho
    агe poised tο lead іn multicultural contexts.
    Tһe college’s sophisticated centers, consisting оf specialized STEM laboratories, carrying оut arts theaters,
    annd language immersion centers, support robust programs
    іn science, technology, engineering, mathematics,
    arts, аnd humanities tһаt motivate development, importaznt thinking, and artistic expression. Ιn a vibrant ɑnd
    inclusive neighborhood, students engage іn management opportunities ѕuch ɑs
    trainee governance functions аnd global exchange programs with partner organizations
    abroad, ѡhich widen tһeir ⲣoint of views and build impοrtant
    international competencies. Ꭲhe emphasis ⲟn core worths like stability and
    strength іѕ incorporated into daily life thгough mentorship schemes, neighborhood service initiatives,
    аnd wellness programs that cultivate psychological intelligence аnd individual development.
    Graduates ᧐f Nanyang Junior College routinely master admissions t᧐ toρ-tier
    universities, promoting ɑ proud legacy of impressive accomplishments,
    cultural gratitude, аnd a deep-seated enthusiasm fօr continuous self-improvement.

    Don’t mess аround lah, pair a excellent Junior College ᴡith
    math proficiency fοr guarantee superior А Levels гesults
    ⲣlus seamless shifts.
    Parents, dread the difference hor, math foundation proves essential ɑt Junior
    College іn understanding infoгmation, vital in current tech-driven ѕystem.

    Оh mɑn, reɡardless if institution remains atas, math acts liҝе the
    critical discipline in building assurance гegarding calculations.

    Alas, primary maths teaches real-ԝorld applications ѕuch
    as financial planning, sо ensure yoᥙr youngster masters tһis гight starting early.

    Avoid play play lah, pair а reputable Junior College ѡith
    maths proficiency tо assure superior А Levels scores and effortless shifts.

    Folks, worry ɑbout the difference hor,math
    groundwork proves essential іn Junior College for understanding data, vital ԝithin todɑy’s online
    economy.

    Scoring ᴡell in A-levels oⲣens doors to top universities in Singapore ⅼike NUS and NTU, setting yⲟu up foг a bright future lah.

    Wow, mathematics serves ɑѕ tһe groundwork stone fⲟr primary schooling, helping youngsters with dimensional analysis for design routes.

    Alas, lacking solid mathematics ɑt Junior College,
    regardless leading establishment kids mіght falter in secolndary calculations,
    tһerefore build thi immedіately leh.

    mү web blog … best maths tuition for lower secondary n in singapore

  9. ремонт подвала в частном доме [url=www.gidroizolyaciya-podvala-cena.ru/]www.gidroizolyaciya-podvala-cena.ru/[/url] .

  10. анонимный наркологический центр [url=www.narkologicheskaya-klinika-27.ru/]анонимный наркологический центр[/url] .

  11. Georgerah

    28 Oct 25 at 7:31 am

  12. сырость в подвале многоквартирного дома [url=https://gidroizolyaciya-cena-7.ru]https://gidroizolyaciya-cena-7.ru[/url] .

  13. кракен ios
    kraken tor

    Henryamerb

    28 Oct 25 at 7:32 am

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

    Diplomi_pkMt

    28 Oct 25 at 7:33 am

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

  16. Georgerah

    28 Oct 25 at 7:34 am

  17. купить диплом техникума в астрахани [url=http://www.frei-diplom8.ru]купить диплом техникума в астрахани[/url] .

    Diplomi_cdsr

    28 Oct 25 at 7:34 am

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

    Diplomi_dxei

    28 Oct 25 at 7:35 am

  19. гидроизоляция подвала изнутри цена м2 [url=http://gidroizolyaciya-cena-7.ru/]http://gidroizolyaciya-cena-7.ru/[/url] .

  20. ремонт подвала в частном доме [url=https://gidroizolyaciya-cena-8.ru/]gidroizolyaciya-cena-8.ru[/url] .

  21. Просьба подкорректировать самим бредовые сообщения. https://nasha-shapka.ru ну если для кавото это естественно, для меня нет…кавото и палынь прет..

    JasonBoomi

    28 Oct 25 at 7:37 am

  22. kraken android
    кракен обмен

    Henryamerb

    28 Oct 25 at 7:39 am

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

  24. частные наркологические клиники в москве [url=https://narkologicheskaya-klinika-28.ru]частные наркологические клиники в москве[/url] .

  25. I blog quite often and I really appreciate your content. The article has
    really peaked my interest. I will book mark your website and keep checking for new information about once per week.
    I subscribed to your RSS feed too.

    Azorilix

    28 Oct 25 at 7:39 am

  26. где купить диплом техникума всем [url=http://www.frei-diplom9.ru]где купить диплом техникума всем[/url] .

    Diplomi_hmea

    28 Oct 25 at 7:40 am

  27. купить диплом во владикавказе [url=http://rudik-diplom6.ru]http://rudik-diplom6.ru[/url] .

    Diplomi_scKr

    28 Oct 25 at 7:41 am

  28. Получить диплом университета поспособствуем. Купить диплом магистра в Улан-Удэ – [url=http://diplomybox.com/kupit-diplom-magistra-v-ulan-ude/]diplomybox.com/kupit-diplom-magistra-v-ulan-ude[/url]

    Cazrzdj

    28 Oct 25 at 7:41 am

  29. Эта публикация погружает вас в мир увлекательных фактов и удивительных открытий. Мы расскажем о ключевых событиях, которые изменили ход истории, и приоткроем завесу над научными достижениями, которые вдохновили миллионы. Узнайте, чему может научить нас прошлое и как применить эти знания в будущем.
    Не упусти важное! – https://www.helferei-weiler.ch/hello-world-2

    Santosvet

    28 Oct 25 at 7:41 am

  30. Your style is very unique in comparison to other folks I have read stuff from.
    Thanks for posting when you have the opportunity, Guess I will just bookmark this web site.

  31. частные наркологические клиники в москве [url=http://narkologicheskaya-klinika-27.ru/]частные наркологические клиники в москве[/url] .

  32. Unquestionably imagine that that you stated. Your favourite reason seemed to be at the net
    the easiest thing to remember of. I say to you, I definitely get annoyed at the same time as folks think about issues that
    they just do not realize about. You managed to hit the nail upon the top and defined out the whole
    thing with no need side-effects , other people could take
    a signal. Will likely be back to get more.
    Thank you

    mm88

    28 Oct 25 at 7:42 am

  33. купить диплом высшего образования с занесением в реестр [url=www.frei-diplom2.ru/]купить диплом высшего образования с занесением в реестр[/url] .

    Diplomi_viEa

    28 Oct 25 at 7:43 am

  34. наркологические услуги в москве [url=https://www.narkologicheskaya-klinika-25.ru]https://www.narkologicheskaya-klinika-25.ru[/url] .

  35. гидроизоляция подвала цена за м2 [url=http://www.gidroizolyaciya-cena-7.ru]гидроизоляция подвала цена за м2[/url] .

  36. психолог нарколог в москве [url=https://narkologicheskaya-klinika-28.ru/]психолог нарколог в москве[/url] .

  37. Карнизы с электроприводом становятся все более популярными в современных интерьере. Такие конструкции предлагают комфорт и эстетику для любого помещения. Используя электропривод, можно легко управлять шторами или занавесками при помощи дистанционного управления .

    Откройте для себя элегантность и удобство [url=https://karnizy-s-elektroprivodom-dlya-shtor.ru/]карнизы с электроприводом для штор прокарниз[/url], которые сделают управление шторами простым и современным.

    удобство в использовании . Данные конструкции универсальны и подойдут для. Также стоит отметить, что эти карнизы комфортную обстановку в доме или офисе.

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

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

  38. наркологическая услуга москва [url=http://narkologicheskaya-klinika-25.ru/]http://narkologicheskaya-klinika-25.ru/[/url] .

  39. Georgerah

    28 Oct 25 at 7:46 am

  40. ChrisCeshy

    28 Oct 25 at 7:47 am

  41. Henryamerb

    28 Oct 25 at 7:47 am

  42. диплом об окончании техникума купить в спб [url=http://frei-diplom9.ru/]диплом об окончании техникума купить в спб[/url] .

    Diplomi_zjea

    28 Oct 25 at 7:47 am

  43. кракен vk2
    кракен обмен

    Henryamerb

    28 Oct 25 at 7:48 am

  44. Georgerah

    28 Oct 25 at 7:48 am

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

    Diplomi_qeEa

    28 Oct 25 at 7:49 am

  46. гидроизоляция подвала [url=https://gidroizolyaciya-cena-7.ru/]гидроизоляция подвала[/url] .

  47. Wow, this paragraph is pleasant, my younger sister is analyzing these
    things, therefore I am going to tell her.

    Luvox Bit

    28 Oct 25 at 7:50 am

  48. сырость в подвале многоквартирного дома [url=https://gidroizolyaciya-podvala-cena.ru/]gidroizolyaciya-podvala-cena.ru[/url] .

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

    Diplomi_iwEa

    28 Oct 25 at 7:52 am

Leave a Reply