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 47,315 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 , , ,

    47,315 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=http://karniz-s-elektroprivodom-kupit.ru]http://karniz-s-elektroprivodom-kupit.ru[/url] .

    2. Алгоритм одинаково прозрачен в обоих форматах. Сначала — экспресс-диагностика: уровень сознания, сатурация, пульс, давление, температура, оценка неврологического статуса и обезвоживания. Затем врач формирует индивидуальную инфузионную схему: регидратационные растворы, коррекция электролитов, поддержка печени и нервной системы, адресная симптоматическая помощь (сон, тревога, тошнота, головная боль). Темп и объём подбираются по переносимости — без «универсальных коктейлей» и лишних препаратов.
      Подробнее – https://vyvod-iz-zapoya-pushkino7.ru/

      LeslieSoG

      15 Sep 25 at 10:21 pm

    3. Мы предлагаем дипломы любой профессии по приятным тарифам. Покупка диплома, который подтверждает обучение в университете, – это грамотное решение. Заказать диплом ВУЗа: [url=http://gulfstatesliving.com/author/murieldonahoe/]gulfstatesliving.com/author/murieldonahoe[/url]

      Mazrbbm

      15 Sep 25 at 10:22 pm

    4. рулонные шторы с направляющими на пластиковые окна [url=https://www.elektricheskie-rulonnye-shtory15.ru]https://www.elektricheskie-rulonnye-shtory15.ru[/url] .

    5. рулонные шторы автоматические [url=http://avtomaticheskie-rulonnye-shtory5.ru]http://avtomaticheskie-rulonnye-shtory5.ru[/url] .

    6. электрокарниз недорого [url=www.karniz-s-elektroprivodom-kupit.ru]www.karniz-s-elektroprivodom-kupit.ru[/url] .

    7. I really like your blog.. very nice colors & theme. Did you design this website yourself or did you hire someone to do it for you?
      Plz reply as I’m looking to design my own blog and would
      like to know where u got this from. cheers

    8. Have you ever thought about creating an ebook or guest authoring on other blogs?
      I have a blog centered on the same information you discuss and would
      really like to have you share some stories/information. I know my audience would
      value your work. If you are even remotely interested, feel free to shoot me an e mail.

    9. пластиковые окна рулонные шторы с электроприводом [url=www.elektricheskie-rulonnye-shtory15.ru]www.elektricheskie-rulonnye-shtory15.ru[/url] .

    10. электрокарнизы цена [url=http://www.karnizy-s-elektroprivodom-cena.ru]электрокарнизы цена[/url] .

    11. шторы в оконный проем [url=http://avtomaticheskie-rulonnye-shtory5.ru]http://avtomaticheskie-rulonnye-shtory5.ru[/url] .

    12. купить рулонные шторы в москве [url=https://elektricheskie-rulonnye-shtory15.ru/]https://elektricheskie-rulonnye-shtory15.ru/[/url] .

    13. купить аттестаты за 11 класс пермь [url=www.arus-diplom25.ru/]купить аттестаты за 11 класс пермь[/url] .

      Diplomi_ueot

      15 Sep 25 at 10:28 pm

    14. заказать рулонные шторы цена [url=https://avtomaticheskie-rulonnye-shtory5.ru/]заказать рулонные шторы цена[/url] .

    15. Thanks for your marvelous posting! I really enjoyed reading it,
      you may be a great author.I will always bookmark
      your blog and will come back very soon. I want to encourage you to continue
      your great work, have a nice evening!

      jelas777

      15 Sep 25 at 10:29 pm

    16. электрокарнизы для штор цена [url=https://karnizy-s-elektroprivodom-cena.ru/]электрокарнизы для штор цена[/url] .

    17. Thanks very interesting blog!

      Belqorix

      15 Sep 25 at 10:31 pm

    18. карнизы для штор с электроприводом [url=http://karniz-s-elektroprivodom-kupit.ru/]http://karniz-s-elektroprivodom-kupit.ru/[/url] .

    19. Мега ссылка Мега даркнет Мега сайт Мега онион Мега ссылка Mega даркнет Mega сайт Mega онион Mega ссылка Mega darknet Mega onion

      RichardPep

      15 Sep 25 at 10:32 pm

    20. Mega darknet Мега даркнет Мега сайт Мега онион Мега ссылка Mega даркнет Mega сайт Mega онион Mega ссылка Mega darknet Mega onion

      RichardPep

      15 Sep 25 at 10:34 pm

    21. карниз для штор с электроприводом [url=karnizy-s-elektroprivodom-cena.ru]карниз для штор с электроприводом[/url] .

    22. рольшторы заказать [url=http://www.elektricheskie-rulonnye-shtory15.ru]http://www.elektricheskie-rulonnye-shtory15.ru[/url] .

    23. установить рулонные шторы цена [url=http://avtomaticheskie-rulonnye-shtory5.ru]http://avtomaticheskie-rulonnye-shtory5.ru[/url] .

    24. DanielSoOni

      15 Sep 25 at 10:41 pm

    25. карнизы с электроприводом [url=http://www.karniz-s-elektroprivodom-kupit.ru]http://www.karniz-s-elektroprivodom-kupit.ru[/url] .

    26. карниз с электроприводом [url=https://www.karniz-s-elektroprivodom-kupit.ru]https://www.karniz-s-elektroprivodom-kupit.ru[/url] .

    27. карниз электро [url=https://karnizy-s-elektroprivodom-cena.ru]https://karnizy-s-elektroprivodom-cena.ru[/url] .

    28. рулонная штора автоматическая [url=www.elektricheskie-rulonnye-shtory15.ru/]www.elektricheskie-rulonnye-shtory15.ru/[/url] .

    29. Прогнозы экономики Финансы – это обширная область, охватывающая управление денежными средствами, инвестициями и другими активами. Она включает в себя планирование, организацию, контроль и анализ финансовых ресурсов для достижения экономических целей. От личных бюджетов до глобальных рынков, финансы играют ключевую роль в экономическом благополучии individuals, organizations and nations. Управление рисками, финансовое планирование, инвестиционные стратегии и понимание финансовых рынков – все это важные аспекты успешного финансового управления.

      JamesHophy

      15 Sep 25 at 10:48 pm

    30. электро жалюзи на окна [url=https://avtomaticheskie-rulonnye-shtory5.ru/]https://avtomaticheskie-rulonnye-shtory5.ru/[/url] .

    31. экстренный вывод из запоя
      vivod-iz-zapoya-smolensk016.ru
      лечение запоя

    32. рулонные шторы с электроприводом купить в москве [url=https://elektricheskie-rulonnye-shtory15.ru/]elektricheskie-rulonnye-shtory15.ru[/url] .

    33. карниз для штор с электроприводом [url=karniz-s-elektroprivodom-kupit.ru]karniz-s-elektroprivodom-kupit.ru[/url] .

    34. Мега сайт Мега даркнет Мега сайт Мега онион Мега ссылка Mega даркнет Mega сайт Mega онион Mega ссылка Mega darknet Mega onion

      RichardPep

      15 Sep 25 at 10:51 pm

    35. It’s no secret how President Donald Trump feels about sports teams turning away from Native American mascots. He’s repeatedly called for the return of the Washington Redskins and Cleveland Indians, claiming their recent rebrands were part of a “woke” agenda designed to erase history.
      [url=https://kra-38cc.org]kra39 at [/url]
      But one surprising team has really gotten the president’s attention: the Massapequa Chiefs.

      The Long Island school district has refused to change its logo and name under a mandate from New York state banning schools from using team mascots appropriating Indigenous culture. Schools were given two years to rebrand, but Massapequa is the lone holdout, having missed the June 30 deadline to debut a new logo.
      [url=https://kra-40cc.net]kra40[/url]
      The district lost an initial lawsuit it filed against the state but now has the federal government on its side. In May, Trump’s Department of Education intervened on the district’s behalf, claiming the state’s mascot ban is itself discriminatory.

      Massapequa’s Chiefs logo — an American Indian wearing a yellow feathered headdress — is expected to still be prominently displayed when the fall sports season kicks off soon, putting the quiet Long Island hamlet at the center of a political firestorm.
      [url=https://kra—40at.ru]kra39 сс[/url]
      The district is now a key “battleground,” said Oliver Roberts, a Massapequa alum and the lawyer representing the school board in its fresh lawsuit against New York claiming that the ban is unconstitutional and discriminatory.

      The Trump administration claims New York’s mascot ban violates Title VI of the Civil Rights Act of 1964, which prohibits recipients of federal funds from engaging in discriminatory behavior based on race, color or national origin — teeing up a potentially precedent-setting fight.

      The intervention on behalf of Massapequa follows a pattern for a White House that has aggressively applied civil rights protections to police “reverse discrimination” and coerced schools and universities into policy concessions by withholding federal funds.

      “Our goal is to assist nationally,” Roberts said. “It’s us putting forward our time and effort to try and assist with this national movement and push back against the woke bureaucrats trying to cancel our country’s history and tradition.”
      kra40 at
      kra38 cc

      ScottZib

      15 Sep 25 at 10:52 pm

    36. карниз с приводом [url=karnizy-s-elektroprivodom-cena.ru]karnizy-s-elektroprivodom-cena.ru[/url] .

    37. шторы на окна купить [url=http://avtomaticheskie-rulonnye-shtory5.ru/]http://avtomaticheskie-rulonnye-shtory5.ru/[/url] .

    38. https://brookspqxq424.trexgame.net/los-errores-mas-comunes-antes-de-un-examen-antidoping

      Gestionar un test antidoping puede ser un desafio. Por eso, se desarrollo un suplemento innovador creada con altos estandares.

      Su composicion unica combina vitaminas, lo que sobrecarga tu organismo y neutraliza temporalmente los trazas de THC. El resultado: una orina con parametros normales, lista para ser presentada.

      Lo mas interesante es su ventana de efectividad de 4 a 5 horas. A diferencia de metodos caseros, no promete milagros, sino una estrategia de emergencia que te respalda en situaciones criticas.

      Miles de estudiantes ya han comprobado su seguridad. Testimonios reales mencionan envios en menos de 24 horas.

      Si necesitas asegurar tu resultado, esta solucion te ofrece seguridad.

      JuniorShido

      15 Sep 25 at 10:54 pm

    39. повесить рулонные шторы цена за работу [url=www.elektricheskie-rulonnye-shtory15.ru/]www.elektricheskie-rulonnye-shtory15.ru/[/url] .

    40. электрические гардины [url=https://karnizy-s-elektroprivodom-cena.ru/]электрические гардины[/url] .

    41. согласование проекта перепланировки квартиры [url=https://fanfiction.borda.ru/?1-0-0-00030334-000-0-0]согласование проекта перепланировки квартиры [/url] .

      soglasovanie pereplanirovki kvartiri moskva _gzka

      15 Sep 25 at 10:57 pm

    42. рулонные шторы на окна на заказ [url=http://avtomaticheskie-rulonnye-shtory5.ru]http://avtomaticheskie-rulonnye-shtory5.ru[/url] .

    43. автоматические карнизы для штор [url=https://karniz-s-elektroprivodom-kupit.ru]https://karniz-s-elektroprivodom-kupit.ru[/url] .

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

      HaroldGaw

      15 Sep 25 at 11:02 pm

    45. электрические гардины [url=http://www.karnizy-s-elektroprivodom-cena.ru]электрические гардины[/url] .

    46. ritzo 20 freispiele Spinbara Casino

      RonaldDuh

      15 Sep 25 at 11:03 pm

    47. Мы можем предложить дипломы любой профессии по доступным ценам. Приобретение диплома, который подтверждает обучение в ВУЗе, – это грамотное решение. Приобрести диплом университета: [url=http://u90517ol.beget.tech/2025/08/08/kupit-diplom-vuza-s-podtverzhdeniem.html/]u90517ol.beget.tech/2025/08/08/kupit-diplom-vuza-s-podtverzhdeniem.html[/url]

      Mazrnsm

      15 Sep 25 at 11:03 pm

    Leave a Reply