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 41,716 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 , , ,

    41,716 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. Женский онлайн-журнал https://feminine.kyiv.ua мода, красота, здоровье, отношения и семья. Полезные советы, вдохновляющие статьи, лайфхаки для дома и карьеры. Всё самое интересное для современных женщин.

      StephenVew

      10 Sep 25 at 6:37 pm

    2. Автомобильный портал https://troeshka.com.ua онлайн-ресурс для автовладельцев. Каталог машин, тест-драйвы, аналитика авторынка и советы специалистов. Будьте в курсе новинок и технологий автоиндустрии.

      ClaytonAnaer

      10 Sep 25 at 6:38 pm

    3. Сайт для женщин https://lolitaquieretemucho.com мода, красота, здоровье, отношения, семья и карьера. Полезные советы, статьи, рецепты и лайфхаки. Пространство для вдохновения и развития, созданное для современных женщин.

      MichaelWOULP

      10 Sep 25 at 6:39 pm

    4. Все будет равно чувак!!!!!!!!
      https://rant.li/fzihmeca/kirov-kupit-narkotik
      Вот мой отзыв по работе данного магазина.

      RogerCer

      10 Sep 25 at 6:39 pm

    5. This is really interesting, You’re a very skilled blogger.
      I’ve joined your rss feed and look forward to seeking more
      of your excellent post. Also, I’ve shared your site in my social networks!

    6. швейная фабрика [url=http://www.nitkapro.ru]http://www.nitkapro.ru[/url] .

    7. I every time used to read paragraph in news papers but now as I am
      a user of internet so Niagara Falls Tours from Toronto
      now I am using net for content, thanks to web.

    8. 1win vhod [url=https://1win12002.ru]https://1win12002.ru[/url]

      1win_kwKa

      10 Sep 25 at 6:41 pm

    9. Получить диплом о высшем образовании можем помочь. Купить диплом Барнаул – [url=http://diplomybox.com/kupit-diplom-barnaul/]diplomybox.com/kupit-diplom-barnaul[/url]

      Cazrrrj

      10 Sep 25 at 6:43 pm

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

    11. Клиника «НаркоМед Плюс» использует комплексный подход для эффективного снятия симптомов ломки с применением современных методов детоксикации и поддержки организма. Основные группы препаратов включают:
      Подробнее можно узнать тут – https://snyatie-lomki-nnovgorod8.ru/

      Larrymit

      10 Sep 25 at 6:45 pm

    12. где можно купить диплом [url=www.educ-ua5.ru]где можно купить диплом[/url] .

      Diplomi_ykKl

      10 Sep 25 at 6:45 pm

    13. J’adore l’exuberance de MrPlay Casino, c’est un casino en ligne qui deborde de panache comme un festival. La selection de jeux du casino est une veritable parade de divertissement, offrant des sessions de casino en direct qui font danser. Le personnel du casino offre un accompagnement digne d’un maestro, repondant en un clin d’?il festif. Les paiements du casino sont securises et fluides, quand meme plus de tours gratuits au casino ce serait enivrant. Dans l’ensemble, MrPlay Casino c’est un casino a rejoindre sans attendre pour les joueurs qui aiment parier avec style au casino ! A noter la navigation du casino est intuitive comme une danse, facilite une experience de casino festive.
      mr.play mobiili|

      zanycricket2zef

      10 Sep 25 at 6:45 pm

    14. авиатор игра [url=http://www.aviator-igra-3.ru]авиатор игра[/url] .

      aviator igra_eomi

      10 Sep 25 at 6:47 pm

    15. I am not sure where you are getting your information,
      but great topic. I needs to spend some time learning much more or understanding more.
      Thanks for great info I was looking for this information for
      my mission.

      Alfonzo

      10 Sep 25 at 6:48 pm

    16. excellent points altogether, you simply won a brand new reader.
      What could you recommend about your submit that you just
      made some days ago? Any positive?

      BlorBytAi

      10 Sep 25 at 6:48 pm

    17. When I originally commented I seem to have clicked the -Notify me when new comments are
      added- checkbox and now each time a comment
      is added I recieve four emails with the same comment.

      Is there a way you can remove me from that service? Thanks!

    18. авиатор 1win [url=https://aviator-igra-5.ru/]авиатор 1win[/url] .

      aviator igra_pmKt

      10 Sep 25 at 6:50 pm

    19. купить диплом в полтаве [url=http://educ-ua5.ru]http://educ-ua5.ru[/url] .

      Diplomi_jqKl

      10 Sep 25 at 6:51 pm

    20. Thank you for the auspicious writeup. It if truth
      be told used to be a entertainment account
      it. Glance complicated to more added agreeable from you!

      By the way, how can we keep up a correspondence?

      Chong

      10 Sep 25 at 6:51 pm

    21. masbet [url=https://mostbet12004.ru]masbet[/url]

      mostbet_cmOt

      10 Sep 25 at 6:52 pm

    22. где играть в авиатор [url=https://aviator-igra-3.ru]где играть в авиатор[/url] .

      aviator igra_wvmi

      10 Sep 25 at 6:52 pm

    23. I really like your blog.. very nice colors & theme. Did you create this website
      yourself or did you hire someone to do it for you?

      Plz answer back as I’m looking to design my own blog and
      would like to find out where u got this from. many thanks

    24. промокод 1win на пополнение [url=www.1win12005.ru]www.1win12005.ru[/url]

      1win_adol

      10 Sep 25 at 6:53 pm

    25. Анонимная помощь при запое — врачи «Alco.Rehab» (Москва) приедут к вам в течение часа.
      Детальнее – http://vyvod-iz-zapoya-moskva13.ru/

      Williamvaw

      10 Sep 25 at 6:53 pm

    26. авиатор игра 1win [url=http://www.aviator-igra-5.ru]авиатор игра 1win[/url] .

      aviator igra_cpKt

      10 Sep 25 at 6:54 pm

    27. Outstanding quest there. What happened after?

      Take care!

    28. Доброго!
      Долго думал как поднять сайт и свои проекты и нарастить ИКС Яндекса и узнал от крутых seo,
      топовых ребят, именно они разработали недорогой и главное лучший прогон Хрумером – https://monstros.site
      Линкбилдинг seo помогает достигать лучших результатов. Он включает создание ссылок и работу с трастовыми площадками. Программы для автоматизации ускоряют процесс. Чем больше качественных ссылок, тем выше позиции. Линкбилдинг seo – залог успешного продвижения.
      продвижение сайта ремонт, kpi seo продвижения, Ссылочные прогоны и их эффективность
      линкбилдинг сео, способов раскрутки сайта, продвижение сайта за звонки
      !!Удачи и роста в топах!!

      Seofoumn

      10 Sep 25 at 6:54 pm

    29. It’s really a cool and useful piece of information. I’m satisfied that you shared this
      helpful info with us. Please stay us informed like this.

      Thanks for sharing.

      Madonna

      10 Sep 25 at 6:55 pm

    30. gtoqtkj

      10 Sep 25 at 6:56 pm

    31. играть в авиатор [url=https://www.aviator-igra-5.ru]играть в авиатор[/url] .

      aviator igra_vwKt

      10 Sep 25 at 6:56 pm

    32. Ahaa, its pleasant discussion about this article at this place
      at this web site, I have read all that, so at this time me also commenting here.

      Zack

      10 Sep 25 at 6:56 pm

    33. darknet drugs dark web market dark web market urls [url=https://darkmarketgate.com/ ]darknet drug market [/url]

      Donaldfup

      10 Sep 25 at 6:56 pm

    34. купить учебный диплом [url=http://www.educ-ua20.ru]купить учебный диплом[/url] .

      Diplomi_ufEn

      10 Sep 25 at 6:57 pm

    35. 20
      Углубиться в тему – http://vyvod-iz-zapoya-moskva11.ru/

      DavidAnita

      10 Sep 25 at 6:58 pm

    36. plane crash game money [url=http://aviator-igra-3.ru/]http://aviator-igra-3.ru/[/url] .

      aviator igra_whmi

      10 Sep 25 at 6:59 pm

    37. купить диплом специалиста [url=http://www.educ-ua17.ru]купить диплом специалиста[/url] .

      Diplomi_vfSl

      10 Sep 25 at 6:59 pm

    38. Adoro o clima explosivo de PlayUzu Casino, da uma energia de cassino que e um redemoinho. Os titulos do cassino sao um espetaculo vibrante, oferecendo sessoes de cassino ao vivo que sao um trovao. Os agentes do cassino sao rapidos como um raio, respondendo mais rapido que um estalo. Os saques no cassino sao velozes como um furacao, mesmo assim as ofertas do cassino podiam ser mais generosas. Na real, PlayUzu Casino e o point perfeito pros fas de cassino para quem curte apostar com estilo no cassino! De bonus a plataforma do cassino detona com um visual que e puro trovao, aumenta a imersao no cassino a mil.
      cupones playuzu sin depГіsito|

      nuttyparrot4zef

      10 Sep 25 at 6:59 pm

    39. как использовать бонусы 1win казино [url=https://www.1win12003.ru]https://www.1win12003.ru[/url]

      1win_onoi

      10 Sep 25 at 7:00 pm

    40. Je trouve absolument envoutant Posido Casino, on dirait une tempete sous-marine de fun. La selection du casino est une vague de plaisirs, comprenant des jeux de casino adaptes aux cryptomonnaies. Le personnel du casino offre un accompagnement digne d’un capitaine, repondant en un eclat d’ecume. Les retraits au casino sont rapides comme un courant marin, par moments des recompenses de casino supplementaires feraient nager de joie. En somme, Posido Casino promet un divertissement de casino aquatique pour ceux qui cherchent l’adrenaline fluide du casino ! En plus le site du casino est une merveille graphique fluide, facilite une experience de casino aquatique.
      posido.|

      fluffycuttlefish9zef

      10 Sep 25 at 7:01 pm

    41. *Седативные препараты применяются строго по показаниям и под мониторингом дыхания.
      Подробнее можно узнать тут – [url=https://vivod-iz-zapoya-rostov14.ru/]наркологический вывод из запоя ростов-на-дону[/url]

      Carlosjak

      10 Sep 25 at 7:02 pm

    42. Сотрудники , знают свое дело , лучше другого.
      https://yamap.com/users/4803098
      Если растворяется без подогрева – то РЅРµ РЅСѓР¶РЅРѕ. Р’ ацетоне как правило (если РїСЂРѕРґСѓРєС‚ чистый) так Рё растворяется, Рё РІ осадок РЅРµ выпадает, РЅР° спирту придется немного подогреть

      RogerCer

      10 Sep 25 at 7:03 pm

    43. авиатор 1win [url=aviator-igra-5.ru]авиатор 1win[/url] .

      aviator igra_jvKt

      10 Sep 25 at 7:05 pm

    44. Мы предлагаем документы институтов, которые находятся в любом регионе России. Заказать диплом университета:
      [url=http://topdubaijobs.ae/employer/ukrdiplom/]купить аттестат 11 классов тюмень[/url]

      Diplomi_fiPn

      10 Sep 25 at 7:07 pm

    45. Inhoud voor volwassenen is beschikbaar op verschillende adult websites voor vermaak.

      Kies altijd voor betrouwbare adult sites.

      Feel free to visit my webpage :: pill enhancement

      pill enhancement

      10 Sep 25 at 7:07 pm

    46. Hello, I believe your site could possibly be having web browser compatibility problems.

      When I look at your blog in Safari, it looks fine however, when opening in I.E., it has
      some overlapping issues. I simply wanted to give you a quick heads up!
      Apart from that, fantastic site!

      Snabb Fluxrad

      10 Sep 25 at 7:08 pm

    47. Привет всем!
      Долго ломал голову как встать в топ поисковиков и узнал от гуру в seo,
      отличных ребят, именно они разработали недорогой и главное продуктивный прогон Хрумером – https://imap33.site
      Линкбилдинг через автоматические проги стал стандартом в SEO. Он упрощает задачу создания ссылок и экономит силы. Программы работают на форумах, блогах и других ресурсах. Такой метод дает быстрые результаты. Линкбилдинг через автоматические проги – оптимальное решение.
      seo ключи сайта, что значит seo сайта, линкбилдинг отзывы
      Программы для автоматического постинга, seo сайт анализ, seo средняя цена
      !!Удачи и роста в топах!!

      JeromeNow

      10 Sep 25 at 7:11 pm

    48. I think the admin of this website is genuinely working hard for his web
      site, as here every material is quality based information.

      Feel free to surf to my site Tours from Toronto Tours Canada

    49. 20
      Углубиться в тему – [url=https://kapelnica-ot-zapoya-lyubercy11.ru/]капельница от запоя город. московская область[/url]

      Charlescerty

      10 Sep 25 at 7:12 pm

    50. играть авиатор [url=https://aviator-igra-5.ru/]играть авиатор[/url] .

      aviator igra_aaKt

      10 Sep 25 at 7:12 pm

    Leave a Reply