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,860 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,860 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. pin up ruletka [url=https://www.pinup5008.ru]https://www.pinup5008.ru[/url]

    pin_up_uz_ruSt

    21 Oct 25 at 3:54 pm

  2. топ компаний по продвижению сайтов [url=http://seo-prodvizhenie-reiting.ru/]http://seo-prodvizhenie-reiting.ru/[/url] .

  3. pin up demo aviator o‘ynash [url=http://pinup5008.ru/]http://pinup5008.ru/[/url]

    pin_up_uz_vrSt

    21 Oct 25 at 3:57 pm

  4. диплом педагогического колледжа купить [url=https://frei-diplom10.ru/]https://frei-diplom10.ru/[/url] .

    Diplomi_rlEa

    21 Oct 25 at 3:58 pm

  5. pin up uz [url=http://pinup5007.ru]http://pinup5007.ru[/url]

    pin_up_uz_qpsr

    21 Oct 25 at 3:58 pm

  6. кракен vk3

    Here is my blog; https://kraken-russia.com

  7. можно купить диплом медсестры [url=https://www.frei-diplom13.ru]можно купить диплом медсестры[/url] .

    Diplomi_qykt

    21 Oct 25 at 3:58 pm

  8. seo optimization agency [url=https://reiting-seo-kompanii.ru]https://reiting-seo-kompanii.ru[/url] .

  9. pin up uz [url=https://www.pinup5007.ru]pin up uz[/url]

    pin_up_uz_mxsr

    21 Oct 25 at 4:01 pm

  10. продвижение сайтов лидеры [url=seo-prodvizhenie-reiting.ru]продвижение сайтов лидеры[/url] .

  11. рейтинг компаний по продвижению сайтов [url=http://www.luchshie-digital-agencstva.ru]рейтинг компаний по продвижению сайтов[/url] .

  12. Everyone loves what you guys tend to be up too. This kind of clever work and
    exposure! Keep up the excellent works guys I’ve added you guys
    to blogroll.

    EquiLoomPRO

    21 Oct 25 at 4:02 pm

  13. Today, I went to the beach front with my kids. I found a sea shell and gave it to my 4 year old daughter and said “You can hear the ocean if you put this to your ear.” She put the shell to her ear and screamed. There was a hermit crab inside and it pinched her ear. She never wants to go back! LoL I know this is totally off topic but I had to tell someone!
    https://staffinggoals.com/

    IsmaelNek

    21 Oct 25 at 4:03 pm

  14. JosephDum

    21 Oct 25 at 4:04 pm

  15. JosephDum

    21 Oct 25 at 4:05 pm

  16. рейтинг seo агентств москвы [url=www.reiting-seo-agentstv-moskvy.ru/]рейтинг seo агентств москвы[/url] .

  17. We’re a group of volunteers and opening a new scheme in our community.
    Your web site provided us with valuable info to work on. You have
    done a formidable job and our whole community will be thankful to you.

    dewascatter slot

    21 Oct 25 at 4:07 pm

  18. Larryjeats

    21 Oct 25 at 4:07 pm

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

    Diplomi_gnkt

    21 Oct 25 at 4:09 pm

  20. I know this if off topic but I’m looking into starting my own blog and was
    wondering what all is required to get set up?
    I’m assuming having a blog like yours would cost a pretty penny?
    I’m not very web savvy so I’m not 100% positive.

    Any recommendations or advice would be greatly appreciated.

    Cheers

    topics

    21 Oct 25 at 4:10 pm

  21. seo consultant best [url=https://top-10-seo-prodvizhenie.ru]https://top-10-seo-prodvizhenie.ru[/url] .

  22. Hey very interesting blog!

  23. Thanks for a marvelous posting! I seriously enjoyed reading it, you might
    be a great author.I will always bookmark your blog and will eventually
    come back sometime soon. I want to encourage that you continue your great work,
    have a nice evening!

    au 88

    21 Oct 25 at 4:10 pm

  24. pin up apk yuklab olish [url=pinup5008.ru]pinup5008.ru[/url]

    pin_up_uz_vpSt

    21 Oct 25 at 4:11 pm

  25. Jamesmot

    21 Oct 25 at 4:12 pm

  26. Sildenafil side effects and safe dosage: difference between Viagra and generic Sildenafil – Viagra generic over the counter

    WilliamUnjup

    21 Oct 25 at 4:12 pm

  27. Промокод 1xBet на сегодня и бесплатно. Промокоды 1хБет 2026 требуется использовать те, которые предоставят игрокам самые лучшие бонусы. Каждый из них позволяет увеличить первый депозит в 2 раза, максимальная сумма увеличения – 100 долларов. Большое количество промокодов — одна из причин того, что на сайте регистрируется огромное количество новых игроков каждый день. На данный момент их количество превышает пятьсот тысяч уникальных пользователей каждый день. Действующие промокоды позволяют увеличить размер приветственных баллов до 32500 рублей. Для этого нужно лишь активировать при регистрации имеющийся код, скопировав его в соответствующее поле. Букмекерская контора 1хБет является одной из самых влиятельных на рынке игорного бизнеса в России и не нуждается в особом представлении. Впрочем, букмекер продолжает держать статус одного из самых щедрых и предлагает своим клиентам воспользоваться промокодами для халявы, о которой я более подробно расскажу в этом материале 1xbet промокод ввести.

    Stanleyvonna

    21 Oct 25 at 4:13 pm

  28. Где купить Экстази в Мархе?Вот есть сайт https://one-two-slim-kapli.ru
    – цены конкурентные, есть разные варианты доставки. Кто-то брал у них? Как с качеством продукта?

    Stevenref

    21 Oct 25 at 4:15 pm

  29. рейтинг digital агентств [url=www.luchshie-digital-agencstva.ru]рейтинг digital агентств[/url] .

  30. продвижение сайта в топ москва [url=https://reiting-seo-agentstv-moskvy.ru/]reiting-seo-agentstv-moskvy.ru[/url] .

  31. NormanJaf

    21 Oct 25 at 4:17 pm

  32. https://t.me/alexssplit Установка кондиционеров под ключ в Москве: Комплексный Подход к Климатическому Комфорту Мы предлагаем установку кондиционеров под ключ в Москве, избавляя вас от необходимости заниматься организационными вопросами. Наш комплексный подход включает в себя подбор оборудования, доставку, монтаж и настройку системы. Мы берем на себя все хлопоты, чтобы вы могли наслаждаться комфортным микроклиматом в своем доме или офисе.

    Johnniemuh

    21 Oct 25 at 4:17 pm

  33. диплом колледж купить [url=https://frei-diplom10.ru/]https://frei-diplom10.ru/[/url] .

    Diplomi_rvEa

    21 Oct 25 at 4:17 pm

  34. Heya are using WordPress for your blog platform?

    I’m new to the blog world but I’m trying to get started and set
    up my own. Do you require any html coding knowledge to make your own blog?
    Any help would be greatly appreciated!

  35. пин ап как вывести деньги [url=www.pinup5008.ru]пин ап как вывести деньги[/url]

    pin_up_uz_rxSt

    21 Oct 25 at 4:19 pm

  36. рейтинг seo [url=www.seo-prodvizhenie-reiting.ru]www.seo-prodvizhenie-reiting.ru[/url] .

  37. «Неман» — оптовый поставщик хозтоваров в Санкт-Петербурге для бизнеса и эксплуатации: мешки для мусора, перчатки, ветошь, бытовая химия, черенки, швабры, ведра, плёнки и ленты. Каталог удобен по категориям, есть прайс-лист и быстрая доставка по городу. Оформить заказ легко на http://nemans.ru — от граблей и лопат до бумаги SvetoCopy и дозаторов. Прямые цены, поддержка менеджеров и отгрузка кратными партиями помогают держать склады в тонусе без переплат и простоев.

    xeqyqncof

    21 Oct 25 at 4:22 pm

  38. Jamesmot

    21 Oct 25 at 4:23 pm

  39. топ интернет агентств москвы [url=luchshie-digital-agencstva.ru]топ интернет агентств москвы[/url] .

  40. пин ап скачать авиатор [url=http://pinup5008.ru/]http://pinup5008.ru/[/url]

    pin_up_uz_hpSt

    21 Oct 25 at 4:26 pm

  41. лучшие seo агентства москвы [url=http://www.reiting-seo-agentstv-moskvy.ru]лучшие seo агентства москвы[/url] .

  42. magnificent publish, very informative. I wonder why the other specialists of this sector do
    not notice this. You should proceed your writing.
    I am confident, you have a great readers’ base already!

  43. Промокод при регистрации 1xBet на 32500 рублей. Данный промокод 1хБет нужно ввести при регистрации в соответствующее поле. 1xBet промокод при регистрации можно использовать только 1н раз в рамках одной учетной записи, но вы можете делиться им со своими друзьями. В 1xBet регистрация по номеру телефона является бесплатным и вторым по простоте способом создать личный аккаунт. Данный способ предусматривает наличие мобильного устройства, а также активной сим-карты, чтобы пользователь мог получить сообщение, в котором его будут ждать данные для входа. После того, как данные будут получены, останется ввести логин с паролем в соответствующие поля. Воспользуйся где взять промокод на 1хбет, получи бесплатную возможность увеличить свой первый депозит до 32500 рублей в БК 1xBet. Промокоды 1xBet актуальные сегодня. На игровой платформе БК «1xBet» функционирует бонусная программа, способствующая привлечению новых игроков и мотивации делать больше ставок для зарегистрированных пользователей. Бонусная программа содержит множество различных бонусов, которые каппер может активировать при помощи специальных промокодов. 125% бонус от первого депозита на ставки. Получай бонус до 125%, но не превышающий 32500 рублей на ставки от 1xBet. Переходим на сайт букмекера.

    Stanleyvonna

    21 Oct 25 at 4:28 pm

  44. https://santehommefrance.com/# sildenafil 50 mg ou 100 mg posologie

    LanceHek

    21 Oct 25 at 4:28 pm

  45. pin up savollar va javoblar [url=http://pinup5008.ru]http://pinup5008.ru[/url]

    pin_up_uz_slSt

    21 Oct 25 at 4:29 pm

  46. лучшие компании seo [url=www.top-10-seo-prodvizhenie.ru]www.top-10-seo-prodvizhenie.ru[/url] .

  47. кто нибудь работает медсестрой по купленному диплому [url=https://frei-diplom13.ru/]https://frei-diplom13.ru/[/url] .

    Diplomi_urkt

    21 Oct 25 at 4:30 pm

  48. NormanJaf

    21 Oct 25 at 4:32 pm

  49. список seo агентств [url=https://www.reiting-seo-kompanii.ru]https://www.reiting-seo-kompanii.ru[/url] .

  50. NormanJaf

    21 Oct 25 at 4:33 pm

Leave a Reply