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 3,858 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 , , ,

    3,858 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://vyvod-iz-zapoya-noginsk5.ru/]анонимный вывод из запоя[/url]

      StevenBlada

      23 Jul 25 at 6:55 am

    2. Сразу после поступления вызова специалист прибывает на дом для проведения первичного осмотра. На данном этапе нарколог:
      Разобраться лучше – [url=https://narcolog-na-dom-ryazan00.ru/]нарколог на дом в рязани[/url]

      Williedicky

      23 Jul 25 at 6:57 am

    3. Алкогольная зависимость требует быстрого и квалифицированного вмешательства, поскольку она может привести к тяжелым последствиям для здоровья. Капельница от запоя — один из наиболее эффективных методов, помогающих вывести организм из состояния алкогольной интоксикации и восстановить нормальное самочувствие. В Екатеринбурге эта процедура доступна как в медицинских учреждениях, так и на дому, что позволяет пациентам выбрать наиболее удобный и комфортный способ лечения.
      Разобраться лучше – [url=https://kapelnica-ot-zapoya-ektb55.ru/]врача капельницу от запоя екатеринбург[/url]

      FrankAbove

      23 Jul 25 at 6:58 am

    4. Эта процедура доступна как в условиях клиники, так и на дому, что делает ее универсальным решением для различных жизненных ситуаций. При этом важно доверять свое здоровье только профессиональным врачам, которые могут обеспечить безопасное и качественное лечение.
      Узнать больше – [url=https://kapelnica-ot-zapoya-krasnoyarsk55.ru/]капельница от запоя на дому красноярск[/url]

      StephenWaw

      23 Jul 25 at 7:00 am

    5. This info is priceless. How can I find out more?

      Feel free to visit my webpage – zborakul01

      zborakul01

      23 Jul 25 at 7:02 am

    6. игра plinko отзывы [url=https://www.1win3067.ru]https://www.1win3067.ru[/url]

      1win_ujoa

      23 Jul 25 at 7:05 am

    7. Процедура детоксикации занимает от 40 минут до 2 часов. После её завершения врач консультирует пациента и родственников, даёт рекомендации по дальнейшему лечению и профилактике повторных запоев.
      Узнать больше – https://narcolog-na-dom-sankt-peterburg00.ru/narkolog-na-dom-czena-spb

      DavidHaw

      23 Jul 25 at 7:07 am

    8. Следующий этап — реабилитация: индивидуальная и групповая психотерапия, восстановление эмоционального фона, обучение навыкам самоконтроля и профилактики рецидивов. При необходимости привлекаются дополнительные специалисты — психологи, психиатры, кардиологи. Важно, что в клинике «ВитаРеабилит» в Подольске большое внимание уделяется не только медицинской, но и психологической поддержке пациента и его семьи.
      Подробнее можно узнать тут – [url=https://narkologicheskaya-klinika-podolsk5.ru/]наркологическая клиника подольск[/url]

      Chrisses

      23 Jul 25 at 7:12 am

    9. промокод winline на сегодня на фрибеты бесплатно [url=www.winlayne-fribet.ru]www.winlayne-fribet.ru[/url] .

    10. Mental Health [url=http://www.mental-health25.com]Mental Health[/url] .

    11. These are actually wonderful ideas in about blogging. You have touched some fastidious factors here.
      Any way keep up wrinting.

      slot dapur toto

      23 Jul 25 at 7:27 am

    12. buy Cialis online cheap [url=http://tadalafilfromindia.com/#]tadalafil online paypal[/url] cheap Cialis Canada

      BurtonCix

      23 Jul 25 at 7:29 am

    13. Этот метод направлен на выявление и замену негативных мыслей и стереотипов поведения, связанных с потреблением алкоголя. Пациент учится отслеживать свои эмоциональные реакции и заменять деструктивные установки конструктивными стратегиями противостояния стрессу.
      Выяснить больше – http://lechenie-alkogolizma-sochi0.ru

      Jerryquien

      23 Jul 25 at 7:31 am

    14. В подобных случаях самостоятельное лечение может привести к тяжёлым осложнениям, а промедление — стоить здоровья или даже жизни. Срочная наркологическая помощь — это шаг к безопасности и началу выздоровления.
      Получить дополнительную информацию – https://narkologicheskaya-pomoshch-lyubercy5.ru/kruglosutochnaya-narkologicheskaya-pomoshch-v-lyubercah/

      Randyfob

      23 Jul 25 at 7:33 am

    15. Excellent blog here! Also your website loads up very fast!
      What web host are you using? Can I get your affiliate link to your
      host? I wish my site loaded up as fast as yours lol

    16. Наркологическая клиника в Ростове-на-Дону предоставляет полный спектр услуг по диагностике, лечению и реабилитации пациентов с алкогольной и наркотической зависимостью. Применение современных медицинских протоколов и индивидуальный подход к каждому пациенту обеспечивают высокую эффективность терапии и снижение риска рецидивов.
      Выяснить больше – [url=https://narkologicheskaya-klinika-rostov-na-donu13.ru/]chastnaya narkologicheskaya klinika rostov-na-donu[/url]

      Dannyvox

      23 Jul 25 at 7:36 am

    17. Попытки “перетерпеть” запой или самолечение часто заканчиваются тяжёлыми осложнениями, включая инсульты, инфаркты, алкогольные психозы. Чем быстрее начнётся профессиональная помощь, тем выше шансы избежать опасных последствий.
      Подробнее тут – [url=https://vyvod-iz-zapoya-himki5.ru/]www.domen.ru[/url]

      Tracyhoott

      23 Jul 25 at 7:39 am

    18. thewomansway-654

      23 Jul 25 at 7:45 am

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

      Diplomi_mvot

      23 Jul 25 at 7:48 am

    20. votnews-635

      23 Jul 25 at 7:48 am

    21. http://tadalafilfromindia.com/# Cialis without prescription

      TheronSnipt

      23 Jul 25 at 7:49 am

    22. womaniyas-829

      23 Jul 25 at 7:50 am

    23. winline промокод на фрибет 2025 [url=www.winlayne-fribet.ru/]www.winlayne-fribet.ru/[/url] .

    24. подключить интернет тарифы санкт-петербург
      domashij-internet-spb006.ru
      интернет тарифы санкт-петербург

      internetelini

      23 Jul 25 at 7:54 am

    25. womanpoll-429

      23 Jul 25 at 7:56 am

    26. whoah this weblog is great i love studying your posts.
      Stay up the good work! You already know, many people are searching around for this information, you can aid them
      greatly.

      digi 995 book

      23 Jul 25 at 8:01 am

    27. mental health ai chatbot [url=http://mental-health23.com/]http://mental-health23.com/[/url] .

    28. как поставить бесплатную ставку на винлайн [url=https://winlayne-fribet1.ru/]https://winlayne-fribet1.ru/[/url] .

    29. купить аттестат за 11 классов и егэ [url=http://www.arus-diplom25.ru]http://www.arus-diplom25.ru[/url] .

      Diplomi_drot

      23 Jul 25 at 8:16 am

    30. Zoloft Company: generic sertraline – cheap Zoloft

      KelvinHoosy

      23 Jul 25 at 8:17 am

    31. thewomansway-682

      23 Jul 25 at 8:19 am

    32. womaniyas-168

      23 Jul 25 at 8:19 am

    33. thewomansway-864

      23 Jul 25 at 8:20 am

    34. womaniyas-187

      23 Jul 25 at 8:20 am

    35. votnews-587

      23 Jul 25 at 8:22 am

    36. votnews-988

      23 Jul 25 at 8:23 am

    37. https://lexapro.pro/# lexapro brand name in india

      TheronSnipt

      23 Jul 25 at 8:24 am

    38. womanpoll-693

      23 Jul 25 at 8:26 am

    39. tadalafil: Tadalafil From India – Tadalafil From India

      KelvinHoosy

      23 Jul 25 at 8:26 am

    40. womanpoll-912

      23 Jul 25 at 8:27 am

    41. Hurrah! At last I got a website from where I can truly get valuable information regarding my study and
      knowledge.

    42. 1win գրանցում [url=https://www.1win3074.ru]https://www.1win3074.ru[/url]

      1win_fbet

      23 Jul 25 at 8:39 am

    43. Мегаполис после заката не спит, а наша команда тоже всегда на страже: эксклюзивная центр лечения алкоголизма и наркомании клиника https://mcnl.ru/ работает 24/7. Без очередей и лишних вопросов — вызов врача по вашему звонку, безопасный детокс под контролем, сверхскоростная капельница, психотерапия на месте, долговечное сопровождение. Тайно, конфиденциально, результативно — вернем вам трезвость без страха.

      IsmaelNek

      23 Jul 25 at 8:39 am

    44. бот для игры лаки джет [url=http://1win3069.ru]http://1win3069.ru[/url]

      1win_qakn

      23 Jul 25 at 8:50 am

    45. 1win [url=1win3073.ru]1win3073.ru[/url]

      1win_ydPi

      23 Jul 25 at 8:53 am

    46. Вывод из запоя в Ростове-на-Дону представляет собой комплекс медицинских мероприятий, направленных на безопасное и эффективное прерывание острой стадии алкогольной интоксикации. Процедуры проводятся с целью устранения симптомов интоксикации, восстановления нормального функционирования органов и предупреждения осложнений, характерных для алкогольного отравления.
      Ознакомиться с деталями – [url=https://vyvod-iz-zapoya-rostov-na-donu13.ru/]вывод из запоя клиника ростов-на-дону[/url]

      WilliamLob

      23 Jul 25 at 8:56 am

    47. купить аттестат об окончании 11 классов настоящий [url=www.arus-diplom25.ru]купить аттестат об окончании 11 классов настоящий[/url] .

      Diplomi_weot

      23 Jul 25 at 8:57 am

    48. Lexapro for depression online: buy lexapro brand name online – Lexapro for depression online

      KelvinHoosy

      23 Jul 25 at 9:00 am

    49. thewomansway-636

      23 Jul 25 at 9:02 am

    Leave a Reply