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 46,924 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 , , ,

    46,924 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=www.avtomaticheskie-karnizy-dlya-shtor.ru/]карниз для штор электрический[/url] .

    2. электрические гардины [url=www.avtomaticheskie-karnizy-dlya-shtor.ru]электрические гардины[/url] .

    3. Hello, i think that i saw you visited my website so i came
      to “return the favor”.I am trying to find
      things to improve my website!I suppose its ok to use a few of your ideas!!

    4. Электролаборатория №494 в Перми – испытания
      и измерения электрооборудования

    5. I was able to find good information from your articles.

      LimoFamoPro

      15 Sep 25 at 2:41 pm

    6. электрокарниз двухрядный цена [url=https://avtomaticheskie-karnizy-dlya-shtor.ru/]avtomaticheskie-karnizy-dlya-shtor.ru[/url] .

    7. +905516067299 fetoden dolayi ulkeyi terk etti

      AHMET ENGİN

      15 Sep 25 at 2:42 pm

    8. изготовление металлоконструкций цена

    9. карниз для штор электрический [url=www.karniz-s-elektroprivodom.ru/]карниз для штор электрический[/url] .

    10. wirkung und dauer von tadalafil: schnelle lieferung tadalafil tabletten – medikament ohne rezept notfall

      Donaldanype

      15 Sep 25 at 2:49 pm

    11. электрокарнизы цена [url=https://karniz-s-elektroprivodom.ru/]электрокарнизы цена[/url] .

    12. Unleash shopping excitement ɑt Kaizenaire.com, curating Singapore’ѕ leading promotions.

      The thrill of promotions in Singapore’ѕ shopping paradise keeps Singaporeans returning for more deals.

      Singaporeans delight іn daydreaming at remote areas
      awaү from city lights, and ҝeep in mind to remain upgraded ⲟn Singapore’s most гecent promotions ɑnd shopping deals.

      Matter Prints produces moral fabrics ɑnd clothing,
      treasured by lasting consumers іn Singapore fоr tһeir hand-block printed materials.

      Klarra develops modern ladies’ѕ clothes with tidy lines one,
      treasured ƅy minimɑl Singaporeans for thеir functional,
      toρ quality pieces mah.

      Kayamila seasonings іmmediate mixes f᧐r local dishes,
      chsrished fоr hassle-free, savory һome cooking.

      Do not be dated leh, Kaizenaire.com updates wіth newеst
      discount rates օne.

      Αlso visit mʏ webpage :: recruitment agency names singapore

    13. купить проведенный диплом отзывы [url=https://www.airlines-inform.ru/personal/user/?UID=77339]купить проведенный диплом отзывы[/url] .

      Priobresti diplom o visshem obrazovanii!_nmkt

      15 Sep 25 at 2:50 pm

    14. You’re so cool! I do not suppose I have read a
      single thing like this before. So nice to discover another person with a few unique
      thoughts on this issue. Really.. thanks for starting this up.
      This web site is something that is needed on the web, someone with a little originality!

    15. Узнайте всю информацию о автосалоне Restyle — современный автоцентр, разнообразие машин, лояльная ценовая политика и надежные сделки! Зайдите на [url=https://restyle-avto.ru]https://restyle-avto.ru[/url] и изучите варианты в наличии. Подбираете машину или лучшее предложение — дилерский центр предлагает легковые машины, выкуп авто и удобную доставку. Нужен авто быстро — здесь найдёте лучшие условия покупки и официальные документы.

      Spravkiawv

      15 Sep 25 at 2:51 pm

    16. карниз с приводом [url=https://www.karniz-s-elektroprivodom.ru]карниз с приводом[/url] .

    17. Мы можем предложить документы институтов, которые находятся на территории всей РФ. Купить диплом о высшем образовании:
      [url=http://merkelistan.com/index.php?title=Benutzer:MarionHarford2/]купить аттестат 11 класса 2016[/url]

      Diplomi_qpPn

      15 Sep 25 at 2:52 pm

    18. Thanks for some other informative web site. Where else could I get
      that kind of info written in such a perfect approach?
      I have a venture that I am just now working on, and I have been at the look out for such info.

      Fintrex Prime 2.9

      15 Sep 25 at 2:54 pm

    19. DanielSoOni

      15 Sep 25 at 2:54 pm

    20. Королева Чиана Королева Чиана – автор, чьи произведения оставляют неизгладимый след в душе читателя. Её рассказы и повести заставляют задуматься о вечных ценностях, о смысле жизни и о том, что действительно важно. Если вы цените качественную литературу, которая заставляет думать и чувствовать, то творчество Королевы Чианы – это именно то, что вам нужно.

      AllanCef

      15 Sep 25 at 3:00 pm

    21. Nice post. I learn something totally new and challenging on websites I stumbleupon every day.
      It will always be exciting to read through articles from other authors
      and practice something from their websites.

    22. Приобрести диплом любого ВУЗа!
      Наша компания предлагаетбыстро и выгодно заказать диплом, который выполняется на бланке ГОЗНАКа и заверен мокрыми печатями, штампами, подписями. Документ способен пройти лубую проверку, даже с применением специального оборудования. Решите свои задачи быстро и просто с нашей компанией- [url=http://northland.forumex.ru/viewtopic.php?f=3&t=1639/]northland.forumex.ru/viewtopic.php?f=3&t=1639[/url]

      Jariordhk

      15 Sep 25 at 3:08 pm

    23. Kaizenaire.com iѕ Singapore’s favorite manager of promotions, providing fresh deals аnd events daily.

      Singapore’ѕ condition ɑѕ a shopping mecca reverberates
      with Singaporeans, that always focus on promotions in their
      mission fⲟr lots.

      Checking оut night safaris at the zoo amazes animal-loving Singaporeans, аnd ҝeep іn mind to гemain upgraded ߋn Singapore’s mⲟst recent promotions ɑnd shopping deals.

      Ginlee crafts classic ladies’ѕ wear wіth quality fabrics, prefered Ьy advanced Singaporeans fоr theiг enduring style.

      Fraser and Neave generates beverages ⅼike 100PLUS and F&N cordials lor, valued Ƅy Singaporeans for their rejuvenating drinks Ԁuring hot weather condition leh.

      Itacho Sushi serves premium sashimi аnd rolls, loved for
      higһ-quality fish аnd elegant presentations.

      Better be kiasu leh, visit Kaizenaire.ⅽom οften for unequalled
      promotions ⲟne.

      Feel free tо visit my web-site; recruitment agency singapore

    24. Fantastic beat ! I would like to apprentice whilst you amend
      your website, how could i subscribe for a weblog website?

      The account helped me a applicable deal. I had been tiny bit acquainted of this your broadcast provided
      shiny clear concept

      rajagacor

      15 Sep 25 at 3:10 pm

    25. купить легальный диплом колледжа [url=http://itbestsellers.ru/forum/user/111645]купить легальный диплом колледжа[/url] .

      Priobresti diplom ob obrazovanii!_oqkt

      15 Sep 25 at 3:12 pm

    26. https://postheaven.net/maixentedd/habitos-que-pueden-afectar-tu-resultado-en-un-test-de-orina

      Superar un test antidoping puede ser complicado. Por eso, se ha creado una solucion cientifica desarrollada en Canada.

      Su mezcla unica combina creatina, lo que ajusta tu organismo y disimula temporalmente los marcadores de alcaloides. El resultado: una prueba sin riesgos, lista para ser presentada.

      Lo mas destacado es su ventana de efectividad de 4 a 5 horas. A diferencia de otros productos, no promete resultados permanentes, sino una herramienta puntual que responde en el momento justo.

      Miles de trabajadores ya han experimentado su seguridad. Testimonios reales mencionan envios en menos de 24 horas.

      Si quieres proteger tu futuro, esta formula te ofrece respaldo.

      JuniorShido

      15 Sep 25 at 3:13 pm

    27. Мы предлагаем документы любых учебных заведений, расположенных в любом регионе России. Заказать диплом любого ВУЗа:
      [url=http://t67747az.beget.tech/2025/07/09/uslugi-po-oformleniyu-diplomov.html/]купить аттестаты за 11 отзывы[/url]

      Diplomi_kyPn

      15 Sep 25 at 3:17 pm

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

    29. купить диплом в краматорске [url=https://educ-ua2.ru]https://educ-ua2.ru[/url] .

      Diplomi_lgOt

      15 Sep 25 at 3:25 pm

    30. Heya! I just wanted to ask if you ever have any issues with hackers?
      My last blog (wordpress) was hacked and I ended up losing months of hard work due to no data backup.
      Do you have any methods to protect against hackers?

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

      JamesHophy

      15 Sep 25 at 3:27 pm

    32. I have been surfing online greater than 3 hours as of late, but I never discovered any interesting article like yours.
      It is lovely value enough for me. In my view, if all website owners and bloggers made good content
      as you probably did, the net will be a lot more useful than ever before.

      Helder Flowdex

      15 Sep 25 at 3:29 pm

    33. Discover curated financial savings ɑt Kaizenaire.cοm,
      Singapore’ѕ elite system for promotions аnd occasion deals.

      Constantⅼy looking for bargains, Singaporeans tɑke advantage of Singapore’ѕ
      online reputation aѕ a worldwide shopping paradise.

      Singaporeans tɑke pleasure іn binge-watching the lаtest
      dramatization оn streaming platforms tһroughout rainy days, and bear іn mind to stay upgraded оn Singapore’s latest promotions and shopping deals.

      Тhe Missing Piece οffers unique jewelry аnd accessories, appreciated
      Ƅy individualistic Singaporeans fοr thеir customized touches.

      Ling Wu designs exotic natural leather bags lah, loved Ьy luxury candidates in Singapore for tһeir artisanal hіgh quality ɑnd exotic products lor.

      Mondelēz International crunches ԝith Oreo and Cadbury, preferred
      fоr sweet, global snacks іn shops.

      Singaporeans, stay ahead mah, examine Kaizenaire.ϲom
      everyday lah.

      Feel free tо surf tⲟ my web blog; hire offshore employees

    34. Having read this I thought it was very enlightening.
      I appreciate you spending some time and energy to put this information together.
      I once again find myself personally spending way too much time both reading and commenting.
      But so what, it was still worth it!

    35. В Краснодаре решение есть — наркологическая клиника. Здесь помогают людям выйти из запоя без страха и осуждения. Всё анонимно, грамотно и с заботой о каждом пациенте.
      Узнать больше – [url=https://vyvod-iz-zapoya-krasnodar17.ru/]нарколог на дом недорого[/url]

      Keithbut

      15 Sep 25 at 3:32 pm

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

    37. bookmarked!!, I like your website!

    38. Heya i am for the first time here. I came across this board and I
      find It truly helpful & it helped me out a lot. I am
      hoping to provide one thing back and aid others such as you aided me.

      dewascatter

      15 Sep 25 at 3:36 pm

    39. купить диплом в ужгороде [url=https://www.educ-ua5.ru]https://www.educ-ua5.ru[/url] .

      Diplomi_jyKl

      15 Sep 25 at 3:37 pm

    40. электрокарниз двухрядный [url=https://karniz-s-elektroprivodom.ru]электрокарниз двухрядный[/url] .

    41. купить дипломы техникума цена [url=www.educ-ua8.ru]купить дипломы техникума цена[/url] .

      Diplomi_brpt

      15 Sep 25 at 3:43 pm

    42. cg 100 fs ohne einzahlung Spinbara Casino

      RonaldDuh

      15 Sep 25 at 3:44 pm

    43. электрокарниз москва [url=http://karniz-s-elektroprivodom.ru]электрокарниз москва[/url] .

    44. Hey I know this is off topic but I was wondering if you knew of any widgets I could add to my blog that automatically tweet my newest twitter updates.
      I’ve been looking for a plug-in like this for quite some time and was hoping maybe
      you would have some experience with something like this.
      Please let me know if you run into anything. I truly enjoy reading
      your blog and I look forward to your new updates.

    45. купить диплом о высшем образовании ссср [url=educ-ua2.ru]купить диплом о высшем образовании ссср[/url] .

      Diplomi_oiOt

      15 Sep 25 at 3:49 pm

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

    Leave a Reply