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

    PHP hook, building hooks in your application

    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!

    12,134 thoughts on “PHP hook, building hooks in your application”

    1. Мы можем предложить документы учебных заведений, расположенных на территории всей Российской Федерации. Приобрести диплом университета:
      rorp.4admins.ru/viewforum.php?f=33

    2. Мы изготавливаем дипломы любых профессий по приятным ценам. Дипломы изготавливаются на настоящих бланках Приобрести диплом о высшем образовании freediplom.com

    3. Мы предлагаем дипломы любой профессии по выгодным ценам. Мы готовы предложить документы техникумов, расположенных в любом регионе России. Дипломы и аттестаты выпускаются на бумаге самого высшего качества. Это позволяет делать государственные дипломы, не отличимые от оригиналов. [url=http://orikdok-2v-gorode-nizhniy-novgorod-52.online/]orikdok-2v-gorode-nizhniy-novgorod-52.online[/url]

    4. Где заказать диплом специалиста?
      Заказать диплом университета по невысокой стоимости вы сможете, обращаясь к проверенной специализированной фирме.: institute-diplom.ru

    5. Howdy are using WordPress for your site platform?

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

    6. Особое внимание в клинике уделяется предотвращению рецидивов. Мы обучаем пациентов навыкам управления стрессом и эмоциональной стабильности, помогая формировать здоровые привычки. Это способствует долгосрочному восстановлению и снижает вероятность возвращения к зависимости.
      Узнать больше – https://медицинский-вывод-из-запоя.рф/vyvod-iz-zapoya-na-domu-v-rostove-na-donu.xn--p1ai

    7. Заказать диплом любого университета!
      Приобретение диплома ВУЗа через качественную и надежную фирму дарит множество преимуществ. Приобрести диплом института у надежной компании: doks-v-gorode-irkutsk-38.ru

    8. Мы можем предложить документы институтов, расположенных в любом регионе России. Купить диплом о высшем образовании:
      [url=http://ivoryjob.com/employer/diplomirovans/]ivoryjob.com/employer/diplomirovans[/url]

    9. AntiNarcoForum — это онлайн-форум, созданный для тех, кто столкнулся с проблемой алкоголизма или наркомании. Анонимность, индивидуальный подход к каждому пользователю и квалифицированная поддержка делают форум эффективным инструментом в борьбе с зависимостью.
      Узнать больше – лечится ли женский алкоголизм

    10. Мы изготавливаем дипломы психологов, юристов, экономистов и любых других профессий по приятным ценам. Важно, чтобы дипломы были доступны для большинства граждан. Быстро приобрести диплом об образовании obairseurope.com/employer/premialnie-diplom-24

    11. Приобрести диплом института по выгодной цене возможно, обращаясь к проверенной специализированной фирме. Приобрести документ института вы имеете возможность у нас в Москве. orikdok-2v-gorode-smolensk-67.ru

    12. В нашей клинике работают врачи-наркологи, психологи и психиатры с многолетним опытом в лечении зависимостей. Все специалисты регулярно повышают свою квалификацию, участвуя в семинарах и конференциях, чтобы обеспечивать своим пациентам наиболее современное и качественное лечение.
      Получить дополнительную информацию – http://быстро-вывод-из-запоя.рф/vyvod-iz-zapoya-anonimno-v-volgograde.xn--p1ai/

    13. Купить диплом ВУЗа по выгодной стоимости возможно, обращаясь к проверенной специализированной фирме. Заказать документ о получении высшего образования можно у нас. orikdok-4v-gorode-kurgan-45.ru

    14. Наркологическая клиника “Чистый Путь” — это специализированное медицинское учреждение, предоставляющее помощь людям, страдающим от алкогольной и наркотической зависимости. Наша цель — помочь пациентам справиться с зависимостью, вернуться к здоровой и полноценной жизни, используя эффективные методы лечения и всестороннюю поддержку.
      Подробнее – https://срочно-вывод-из-запоя.рф/vyvod-iz-zapoya-cena-v-chelyabinske.xn--p1ai

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

    16. Fantastic beat ! I wish to apprentice while you amend your
      web site, how could i subscribe for a blog website?

      The account aided me a acceptable deal. I had been tiny bit acquainted
      of this your broadcast offered bright clear concept

    17. Купить диплом ВУЗа по доступной цене возможно, обратившись к надежной специализированной компании. Купить документ о получении высшего образования вы можете у нас. [url=http://orikdok-3v-gorode-voronezh-36.online/]orikdok-3v-gorode-voronezh-36.online[/url]

    18. Мы также уделяем большое внимание социальной адаптации. Пациенты учатся восстанавливать навыки общения и обретать уверенность в себе, что помогает в будущем избежать рецидивов и успешно вернуться к полноценной жизни, будь то работа или учеба.
      Изучить вопрос глубже – http://быстро-вывод-из-запоя.рф/vyvod-iz-zapoya-na-domu-v-volgograde.xn--p1ai/

    19. Где приобрести диплом специалиста?
      Приобрести диплом университета по доступной цене вы можете, обращаясь к надежной специализированной фирме.: okdiplom.com

    20. Мы изготавливаем дипломы любой профессии по выгодным тарифам. Дипломы производятся на фирменных бланках государственного образца Приобрести диплом любого института diplom-ryssia.com

    21. Заказать диплом института по доступной стоимости вы сможете, обращаясь к надежной специализированной фирме. Мы предлагаем документы об окончании любых университетов РФ. Приобрести диплом о высшем образовании– lizwhitney85.copiny.com/question/details/id/1111929

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

    23. Приобрести диплом любого университета!
      Покупка диплома через проверенную и надежную фирму дарит ряд плюсов. Приобрести диплом об образовании у проверенной фирмы: doks-v-gorode-voronezh-36.online

    24. Мы можем предложить дипломы любой профессии по приятным тарифам. Для нас очень важно, чтобы документы были доступными для большого количества граждан. Приобрести диплом института forum.drustvogil-galad.si/index.php/topic,180836.0.html

    25. купить шторы Шторы на окнах – это не просто защита от солнца, это возможность создать свой собственный мир, оградить себя от посторонних взглядов и насладиться уединением. Купить шторы

    26. Definitely consider that which you stated. Your favorite justification seemed
      to be on the web the easiest thing to be aware of. I say to you, I definitely get irked whilst other people consider concerns that they just don’t recognise about.
      You controlled to hit the nail upon the top and outlined out the entire thing with no need
      side effect , other folks can take a signal. Will
      likely be back to get more. Thanks

    27. Наши специалисты гарантируют пациентам конфиденциальность и внимательное отношение, создавая атмосферу доверия. Врач сопровождает пациента на каждом этапе лечения, отслеживая его состояние и корректируя терапию по мере необходимости. Профессионализм и забота наших специалистов являются основой успешной реабилитации.
      Изучить вопрос глубже – http://

    28. Капельница от запоя — это комплексная процедура, направленная на быстрое выведение токсинов, нормализацию обменных процессов и восстановление жизненно важных функций организма. Врачи-наркологи подбирают индивидуальный состав капельницы, исходя из состояния пациента. В стандартный набор препаратов обычно входят:
      Выяснить больше – http://kapelnica-ot-zapoya-sochi00.ru

    29. Купить диплом университета по выгодной стоимости возможно, обращаясь к надежной специализированной фирме. Мы предлагаем документы университетов, которые находятся в любом регионе Российской Федерации. msk-diploms.ru/skolko-stoit-kupit-diplom-s-reestrom-2/

    30. Can I just say what a comfort to uncover somebody that truly knows what they are
      discussing on the net. You certainly understand how to
      bring a problem to light and make it important. More and more people
      ought to check this out and understand this side of your story.
      I was surprised that you aren’t more popular because you definitely have the gift.

      Here is my website – look at this website

    Leave a Comment

    Your email address will not be published. Required fields are marked *

    Scroll to Top