Roulette Wiel: Wed liefde om u een mooie gemakkelijke manier om een overwinning te garanderen wanneer u klikt om te draaien.
  • 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.
  • 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 23,884 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 , , ,

    23,884 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://prognozy-na-khokkej1.ru/]прогнозы на хоккей на сегодня[/url] .

    2. Наркологическая клиника “Ресурс здоровья” — специализированное медицинское учреждение, предназначенное для оказания профессиональной помощи лицам, страдающим от алкогольной и наркотической зависимости. Наша цель — предоставить эффективные методы лечения и поддержку, чтобы помочь пациентам преодолеть пагубное пристрастие и восстановить контроль над своей жизнью.
      Узнать больше – https://narco-vivod.ru

      CharlesKef

      22 Aug 25 at 2:39 am

    3. Hello There. I found your blog using msn. This is a very well written article.

      I will be sure to bookmark it and return to read more of your useful information. Thanks for the
      post. I will definitely comeback.

      Here is my webpage – AWS AMI

      AWS AMI

      22 Aug 25 at 2:40 am

    4. Ukrainian President Volodymyr Zelensky condemned Russian attacks on the Ukrainian regions of Kharkiv, Zaporizhzhia and Sumy on Monday, saying that the Kremlin intends to “humiliate diplomatic efforts” just hours before European leaders visit the White House.
      [url=https://kra22a.cc]kra25 cc[/url]
      “The Russian war machine continues to destroy lives despite everything,” Zelensky said in a statement, hours before he’s due to meet US President Donald Trump in the Oval Office. “That is precisely why we are seeking assistance to put an end to the killings. That is why reliable security guarantees are required. That is why Russia should not be rewarded for its participation in this war.”
      [url=https://kpa29.cc]kra27[/url]
      “Everyone seeks dignified peace and true security,” the Ukrainian president said. “And at this very moment, the Russians are attacking Kharkiv, Zaporizhzhia, the Sumy region, and Odesa, destroying residential buildings and our civilian infrastructure.”

      At least seven people were killed in Russia’s attack? on Kharkiv and a further three killed in the ballistic missile strike on the city of Zaporizhzhia, with scores more injured, according to Ukrainian authorities.

      “This was a demonstrative and cynical Russian strike,” Zelensky added.
      kra25 at
      https://kraken23-at.net

      Rafaelwem

      22 Aug 25 at 2:40 am

    5. GroverPycle

      22 Aug 25 at 2:43 am

    6. купить диплом украины цена [url=https://www.educ-ua4.ru]купить диплом украины цена[/url] .

      Diplomi_ttPl

      22 Aug 25 at 2:45 am

    7. лампа лупа косметологическая лампа лупа для косметолога купить

    8. Hello, this weekend is pleasant designed for me,
      because this occasion i am reading this great informative piece of writing here at my
      house.

      kikototo

      22 Aug 25 at 2:50 am

    9. I have read so many articles or reviews about the blogger lovers however this article is actually a nice piece of writing,
      keep it up.

      krnl executor

      22 Aug 25 at 2:51 am

    10. Medication information sheet. What side effects?
      cost of olmesartan tablets
      Best about meds. Read information here.

    11. купить диплом занесенный реестр [url=https://www.arus-diplom32.ru]купить диплом занесенный реестр[/url] .

    12. Excellent post but I was wondering if you could write a litte
      more on this subject? I’d be very grateful if you could elaborate a little bit more.
      Thanks!

    13. If you want to get much from this post then you have to
      apply such strategies to your won weblog. https://whitestarre.com/agent/melanie081595/

    14. консультация психиатра по телефону
      psikhiatr-moskva003.ru
      психиатр на дом

      psihiatrmskNeT

      22 Aug 25 at 3:01 am

    15. Undeniably believe that which you said. Your favorite justification seemed
      to be on the web the simplest thing to be aware of.
      I say to you, I definitely get irked while people think about worries
      that they just don’t know about. You managed to hit the nail upon the top
      as well as defined out the whole thing without having side
      effect , people could take a signal. Will probably be back
      to get more. Thanks

      keo nha cai

      22 Aug 25 at 3:02 am

    16. Процедура вывода из запоя проводится опытными наркологами с применением современных протоколов и сертифицированных препаратов. Процесс включает несколько ключевых этапов:
      Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-odincovo6.ru/]skoraya-vyvod-iz-zapoya[/url]

      Gregoryflony

      22 Aug 25 at 3:03 am

    17. виза в китай стоит Возможность онлайн оформления визы в Китай зависит от типа визы и региона подачи заявления.

      Grahamkar

      22 Aug 25 at 3:03 am

    18. блочная комплектная трансформаторная подстанция [url=http://transformatornye-podstancii-kupit1.ru/]блочная комплектная трансформаторная подстанция[/url] .

    19. GroverPycle

      22 Aug 25 at 3:04 am

    20. Каждый день запоя увеличивает риск для жизни. Не рискуйте — специалисты в Санкт-Петербурге приедут на дом и окажут экстренную помощь. Без боли, стресса и ожидания.
      Получить дополнительные сведения – [url=https://vyvod-iz-zapoya-v-sankt-peterburge11.ru/]ленинградская область[/url]

      GilbertHek

      22 Aug 25 at 3:06 am

    21. This design is steller! You obviously know how to
      keep a reader entertained. Between your wit and your videos,
      I was almost moved to start my own blog (well, almost…HaHa!) Great job.
      I really enjoyed what you had to say, and more than that, how
      you presented it. Too cool!

      Bluewave Nexor

      22 Aug 25 at 3:08 am

    22. Hello, I enjoy reading all of your article post.
      I like tto write a little comment to support you.

      Review my web site – отдых в лучших курортах Турции

    23. купить диплом колледжа недорого [url=http://educ-ua4.ru/]http://educ-ua4.ru/[/url] .

      Diplomi_iuPl

      22 Aug 25 at 3:09 am

    24. It’s an amazing piece of writing designed for all
      the online users; they will obtain benefit from it I
      am sure.

      Here is my web-site: 안전놀이터

      안전놀이터

      22 Aug 25 at 3:09 am

    25. Атмосферная игра ждёт в Казино Cat слот 100 Lucky Bell.

      Alfonzohut

      22 Aug 25 at 3:11 am

    26. vps hosting europe vps hosting germany

      vps-hosting-4

      22 Aug 25 at 3:12 am

    27. NewEra Protect is a natural supplement designed to strengthen the
      immune system and boost overall wellness. Its blend of carefully
      chosen ingredients helps the body stay resilient, reduce fatigue,
      and maintain daily vitality. Many users like it because it offers
      a simple, safe, and effective way to protect long-term health.

      NewEra Protect

      22 Aug 25 at 3:14 am

    28. ivermectin drops: IverGrove – ivermectin antifungal

      FrankCax

      22 Aug 25 at 3:20 am

    29. Casino On-X предлагает своим игрокам уникальную
      программу лояльности, которая делает каждую игру более увлекательной и выгодной.

    30. Алкогольный запой представляет собой опасное состояние, когда организм не способен самостоятельно справиться с токсической нагрузкой, вызванной длительным употреблением спиртного. Если запой продолжается более двух-трёх дней, у пациента могут появляться симптомы сильной рвоты, головокружения, спутанности сознания, судорог, резких колебаний артериального давления, а также выраженный абстинентный синдром с паническими атаками и бессонницей. При таких показаниях оперативное вмешательство становится жизненно необходимым для предотвращения серьезных осложнений и ускорения процесса восстановления.
      Выяснить больше – [url=https://kapelnica-ot-zapoya-nizhniy-novgorod00.ru/]поставить капельницу от запоя в нижний новгороде[/url]

      Jamesvob

      22 Aug 25 at 3:23 am

    31. Откройте для себя мир азартных игр на [url=https://888starz2.ru]888starz вход в личный кабинет russia[/url].
      позволяющая пользователям наслаждаться азартными играми в удобном формате. На сайте можно найти различные игры, включая слоты и настольные игры.

      888starz предлагает удобный интерфейс, что делает игру более комфортной. Каждый пользователь может найти нужный раздел без труда.

      Пользователи могут быстро зарегистрироваться и начать игру. Чтобы создать аккаунт, достаточно заполнить небольшую анкету и подтвердить свои данные.

      888starz радует своих игроков щедрыми бонусами и многочисленными акциями. За счет бонусов пользователи могут увеличить свои шансы на выигрыш и продлить время игры.

      888starz_jton

      22 Aug 25 at 3:24 am

    32. GroverPycle

      22 Aug 25 at 3:25 am

    33. Pretty element of content. I just stumbled upon your web site and in accession capital to assert that I get in fact loved
      account your blog posts. Anyway I’ll be subscribing on your feeds and even I achievement you access persistently
      fast.

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

      RandyFatty

      22 Aug 25 at 3:27 am

    35. I all the time emailed this webpage post page to all my contacts, because
      if like to read it next my friends will too.

    36. I’ll immediately snatch your rss as I can not in finding your email subscription hyperlink or e-newsletter service.
      Do you have any? Please allow me realize in order that I could subscribe.
      Thanks.

    37. купить диплом в черкассах [url=www.educ-ua4.ru/]www.educ-ua4.ru/[/url] .

      Diplomi_prPl

      22 Aug 25 at 3:34 am

    38. DonaldCab

      22 Aug 25 at 3:34 am

    39. Hi there are using WordPress for your site platform?
      I’m new to the blog world but I’m trying to get started and create my own. Do you require any html coding expertise to make your own blog?

      Any help would be greatly appreciated!

    40. У вас есть сайт, но мало трафика и звонков? Решение очевидно — [url=https://mihaylov.digital/prodvizhenie-sajta-v-google/]продвижение сайта через гугл[/url]. Опытные специалисты знают, как грамотно оптимизировать страницы, составить контент-стратегию и привлечь целевую аудиторию. Такой подход помогает бизнесу выйти на новый уровень: увеличиваются продажи, растёт доверие к бренду, а конкуренты остаются позади. Google — это площадка, где формируется репутация, и важно занять лидирующие позиции именно там.

      Mihaylov.digital — агентство комплексного SEO-продвижения сайтов. Делаем аудит, оптимизацию, выводим проекты в ТОП Google и Яндекс. Работаем с бизнесом любого масштаба. Адрес: Москва, Одесская ул., 2кС, 117638.

    41. Hi, all the time i used to check webpage posts here in the
      early hours in the break of day, as i like to learn more and more.

    42. Далее проводится сама процедура: при медикаментозном варианте препарат может вводиться внутривенно, внутримышечно или имплантироваться под кожу; при психотерапевтическом — работа проходит в специально оборудованном кабинете, в спокойной атмосфере. После кодирования пациент находится под наблюдением, чтобы исключить осложнения и закрепить эффект. Важно помнить, что соблюдение рекомендаций и поддержка семьи играют решающую роль в сохранении трезвости.
      Исследовать вопрос подробнее – [url=https://kodirovanie-ot-alkogolizma-kolomna6.ru/]кодирование от алкоголизма[/url]

      EdwardEmamn

      22 Aug 25 at 3:37 am

    43. ivermectin dose for chickens: IverGrove – IverGrove

      WayneViemo

      22 Aug 25 at 3:39 am

    44. PrimeBiome is a gut health supplement designed to support digestion, nutrient absorption, and overall balance in the microbiome.
      Its natural blend of probiotics and supportive ingredients
      works to ease bloating, improve regularity, and strengthen the immune system.

      Many users appreciate it as a simple and effective way to maintain digestive wellness and boost overall vitality.

      primebiome

      22 Aug 25 at 3:40 am

    45. GroverPycle

      22 Aug 25 at 3:45 am

    46. IverGrove: stromectol 6 mg tablet – durvet ivermectin ingredients

      WayneViemo

      22 Aug 25 at 3:46 am

    47. I was recommended this web site by my cousin. I’m not
      sure whether this post is written by him as nobody else know such detailed about my
      trouble. You’re amazing! Thanks!

    48. купить аттестаты в москве за 11 классов [url=http://arus-diplom22.ru/]купить аттестаты в москве за 11 классов[/url] .

      Diplomi_nlsl

      22 Aug 25 at 3:49 am

    49. I seriously love your blog.. Excellent colors & theme.

      Did you build this site yourself? Please reply back as I’m hoping to create my own website and would like
      to find out where you got this from or exactly what the theme is named.
      Kudos!

    Leave a Reply