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 81,227 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 , , ,

    81,227 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.kuhni-spb-4.ru]кухни на заказ спб[/url] .

      kyhni spb_bqer

      7 Oct 25 at 2:54 pm

    2. My coder is trying to convince me to move to .net from PHP.

      I have always disliked the idea because of the costs. But he’s tryiong none the less.
      I’ve been using WordPress on various websites for about a year and
      am worried about switching to another platform. I have heard very good things about blogengine.net.
      Is there a way I can import all my wordpress posts
      into it? Any help would be greatly appreciated!

    3. sportbets [url=https://sportivnye-novosti-1.ru]sportbets[/url] .

    4. Mediverm Online: Stromectol ivermectin tablets for humans USA – Stromectol ivermectin tablets for humans USA

      Morrisluh

      7 Oct 25 at 2:56 pm

    5. новости киберспорта [url=www.sportivnye-novosti-1.ru]новости киберспорта[/url] .

    6. двигатель дымит Проблемы с двигателем – общий запрос на поиск информации о возможных неисправностях двигателя и способах их устранения. Важно предоставить полезные статьи и советы по диагностике и ремонту двигателя.

      JamesMig

      7 Oct 25 at 2:58 pm

    7. клиника наркология [url=http://narkologicheskaya-klinika-20.ru/]http://narkologicheskaya-klinika-20.ru/[/url] .

    8. где купить диплом мед колледжа [url=http://frei-diplom8.ru/]http://frei-diplom8.ru/[/url] .

      Diplomi_njsr

      7 Oct 25 at 3:00 pm

    9. DonaldtiEls

      7 Oct 25 at 3:00 pm

    10. новости футбола [url=http://sportivnye-novosti-1.ru]новости футбола[/url] .

    11. спорт онлайн [url=novosti-sporta-8.ru]спорт онлайн[/url] .

    12. новости хоккея [url=https://sport-novosti-2.ru/]новости хоккея[/url] .

    13. глория мебель [url=https://kuhni-spb-4.ru/]kuhni-spb-4.ru[/url] .

      kyhni spb_imer

      7 Oct 25 at 3:06 pm

    14. Everyone loves it when folks get together and share views.
      Great blog, continue the good work!

      go99

      7 Oct 25 at 3:07 pm

    15. купить диплом в северске [url=http://rudik-diplom6.ru]http://rudik-diplom6.ru[/url] .

      Diplomi_haKr

      7 Oct 25 at 3:07 pm

    16. Стационар «Частного Медика?24» обеспечивает комфорт и безопасность при лечении запоя.
      Подробнее тут – https://vyvod-iz-zapoya-v-stacionare-voronezh22.ru

      Stevennom

      7 Oct 25 at 3:07 pm

    17. спортивные аналитики [url=www.novosti-sporta-7.ru]www.novosti-sporta-7.ru[/url] .

    18. Стационар «Частного Медика 24» — это круглосуточная помощь при запое, современные капельницы и заботливый уход.
      Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-v-stacionare22.ru/]наркология вывод из запоя в стационаре[/url]

      GordonGok

      7 Oct 25 at 3:08 pm

    19. You could definitely see your enthusiasm in the article you write.

      The sector hopes for more passionate writers like you who
      aren’t afraid to mention how they believe. Always go after your heart.

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

      https://jilliankaulpeterson.com/

    21. последние новости спорта [url=www.novosti-sporta-8.ru/]последние новости спорта[/url] .

    22. стационар на дому нарколог [url=http://narkolog-na-dom-1.ru/]http://narkolog-na-dom-1.ru/[/url] .

    23. частные наркологические клиники в москве [url=www.narkologicheskaya-klinika-20.ru]www.narkologicheskaya-klinika-20.ru[/url] .

    24. Buy marijuana online in Europe from a reliable Holland weed shop.

      Experience top-grade weed, THC vapes, cannabis edibles, and others.

      The online weed delivery across Europe offers speedy,
      safe, and private shipping. Enjoy top-grade weed products with guaranteed satisfaction and professional
      service throughout EU nations.

    25. Программы вывода из запоя в Самаре включают детоксикацию, медикаментозную поддержку и работу с психотерапевтом.
      Исследовать вопрос подробнее – [url=https://vyvod-iz-zapoya-v-stacionare-samara25.ru/]наркология вывод из запоя в стационаре самара[/url]

      Davidcar

      7 Oct 25 at 3:12 pm

    26. кухни на заказ спб каталог [url=www.kuhni-spb-4.ru/]кухни на заказ спб каталог[/url] .

      kyhni spb_dker

      7 Oct 25 at 3:12 pm

    27. Just desire to say your article is as amazing. The clearness in your post is simply cool and i can assume
      you are an expert on this subject. Fine with your permission let me to
      grab your RSS feed to keep up to date with forthcoming
      post. Thanks a million and please keep up the gratifying
      work.

      Alpha Wearable

      7 Oct 25 at 3:12 pm

    28. Hi, I do think this is a great site. I stumbledupon it 😉 I may come back once again since i have book-marked it.
      Money and freedom is the best way to change, may you be rich and continue to
      guide others.

    29. I think that is among the such a lot important information for me.
      And i’m glad studying your article. But want to commentary
      on few common things, The website taste is great, the articles is in point of fact nice :
      D. Excellent task, cheers

    30. Ich finde es unglaublich Snatch Casino, es bietet einen einzigartigen Thrill. Der Katalog ist einfach gigantisch, mit Tausenden von Crypto-freundlichen Spielen. Der Kundenservice ist erstklassig, mit tadellosem Follow-up. Der Prozess ist einfach und reibungslos, trotzdem mehr Freispiele waren ein Plus. Kurz gesagt Snatch Casino garantiert eine top Spielerfahrung fur Online-Wetten-Enthusiasten ! Au?erdem die Plattform ist visuell top, fugt Komfort zum Spiel hinzu.
      snatch casino gutscheincode|

      Hichititan8H8zef

      7 Oct 25 at 3:13 pm

    31. новости киберспорта [url=sportivnye-novosti-1.ru]новости киберспорта[/url] .

    32. новости хоккея [url=http://novosti-sporta-7.ru/]новости хоккея[/url] .

    33. прогноз на сегодня на спорт [url=https://www.prognozy-ot-professionalov4.ru]https://www.prognozy-ot-professionalov4.ru[/url] .

    34. В Сочи клиника «Детокс» предлагает полный курс вывода из запоя в стационаре. Круглосуточный медицинский контроль гарантирует безопасность и эффективность лечения.
      Получить дополнительную информацию – [url=https://vyvod-iz-zapoya-sochi24.ru/]вывод из запоя цена в сочи[/url]

      RobertoToott

      7 Oct 25 at 3:16 pm

    35. свежие новости спорта [url=https://sportivnye-novosti-1.ru]свежие новости спорта[/url] .

    36. новости тенниса [url=http://novosti-sporta-7.ru]новости тенниса[/url] .

    37. домашний нарколог помощь [url=http://narkolog-na-dom-1.ru]http://narkolog-na-dom-1.ru[/url] .

    38. В больничных условиях «Частного Медика 24» врачи контролируют давление, сердце и функции жизненно важных органов при выводе из запоя.
      Подробнее – [url=https://vyvod-iz-zapoya-v-stacionare-samara23.ru/]наркология вывод из запоя в стационаре самара[/url]

      Carlosquold

      7 Oct 25 at 3:18 pm

    39. кухни под заказ спб [url=kuhni-spb-4.ru]кухни под заказ спб[/url] .

      kyhni spb_irer

      7 Oct 25 at 3:18 pm

    40. Discover Singapore’ѕ top deals at Kaizenaire.ϲom,
      the leading curator of shopping promotions.

      Singapore’ѕ shopping paradise standing іs a magnet for citizens whօ love discovering hidden promotions ɑnd racking uр wonderful deals.

      Organizing chess tournaments challenges tactical minds ɑmong
      Singaporeans, and remember tⲟ гemain updated оn Singapore’s
      moѕt recent promotions ɑnd shopping deals.

      Strip and Browhyaus provide beauty treatments ⅼike waxing аnd eyebrow pet grooming, appreciated
      ƅy brushing enthusiasts іn Singapore for their specialist solutions.

      SK Jewellery crafts ɡreat gold ɑnd diamond pieces mah, valued ƅy Singaporeans
      for their stunning designs ⅾuring joyful events sia.

      Lot Seng Leong protects vintage kopitiam feelings ԝith
      butter kopi, favored Ьy nostalgics fоr tһe
      same practices.

      Auntie love leh, Kaizenaire.сom’ѕ shopping discount rates оne.

      Feel free to surf tߋ my web pаge clinique promotions

    41. Продажа велосипедов через интернет-магазин kra 40 at кракен darknet кракен onion кракен ссылка onion

      RichardPep

      7 Oct 25 at 3:20 pm

    42. Круглосуточная выездная служба клиники «Медлайн Надежда» — это возможность получить профессиональную наркологическую помощь дома, без поездок и без огласки. Мы работаем по всему Красногорску и ближайшим локациям, приезжаем оперативно, соблюдаем полную конфиденциальность и не ставим на учёт. Выезд осуществляют врачи-наркологи с клиническим опытом, укомплектованные инфузионными системами, пульсоксиметром, тонометром, средствами для ЭКГ по показаниям и набором сертифицированных препаратов. Наша задача — быстро стабилизировать состояние, снять интоксикацию и тревогу, вернуть сон и предложить понятный план дальнейшей терапии.
      Получить дополнительные сведения – [url=https://narkolog-na-dom-krasnogorsk6.ru/]вызов врача нарколога на дом[/url]

      MichaelBef

      7 Oct 25 at 3:21 pm

    43. прогнозы на спорт бесплатно от профессионалов на сегодня [url=https://www.prognozy-ot-professionalov4.ru]https://www.prognozy-ot-professionalov4.ru[/url] .

    44. клиника наркологическая платная [url=https://narkologicheskaya-klinika-20.ru/]narkologicheskaya-klinika-20.ru[/url] .

    45. Капельница от запоя в Нижнем Новгороде — процедура, направленная на детоксикацию организма и восстановление нормального самочувствия. Она включает в себя введение препаратов, способствующих выведению токсинов и восстановлению функций органов.
      Узнать больше – [url=https://vyvod-iz-zapoya-nizhnij-novgorod11.ru/]вывод из запоя капельница на дому[/url]

      Georgefaw

      7 Oct 25 at 3:23 pm

    46. DonaldtiEls

      7 Oct 25 at 3:27 pm

    47. Hey there! I just would like to offer you a big thumbs up for
      the excellent info you have right here on this post. I am
      coming back to your web site for more soon.

      app kkwin

      7 Oct 25 at 3:28 pm

    48. please click the following webpage

      PHP hook, building hooks in your application – Sjoerd Maessen blog at Sjoerd Maessen blog

    49. наркологический частный центр [url=https://narkologicheskaya-klinika-20.ru]https://narkologicheskaya-klinika-20.ru[/url] .

    50. Hi there! I just wanted to ask if you ever have any problems with hackers?
      My last blog (wordpress) was hacked and I ended up losing months of hard
      work due to no backup. Do you have any solutions to stop
      hackers?

      LucroX AI

      7 Oct 25 at 3:30 pm

    Leave a Reply