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 21,872 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 , , ,

    21,872 Responses to 'PHP hook, building hooks in your application'

    Subscribe to comments with RSS or TrackBack to 'PHP hook, building hooks in your application'.

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

    2. LouisFat

      19 Aug 25 at 3:28 pm

    3. Lloydrar

      19 Aug 25 at 3:29 pm

    4. спортивные события [url=https://novosti-sporta-12.ru/]https://novosti-sporta-12.ru/[/url] .

    5. First of all I would like to say great blog! I had
      a quick question that I’d like to ask if you do not mind.
      I was interested to find out how you center yourself and clear your head
      before writing. I’ve had a tough time clearing my thoughts in getting my ideas out there.

      I truly do take pleasure in writing but it just seems like the first 10 to 15 minutes are generally lost simply just trying to figure out how to begin. Any ideas or hints?
      Kudos!

    6. Everything is very open with a precise description of the issues.
      It was truly informative. Your site is very helpful.
      Many thanks for sharing!

    7. DavidWah

      19 Aug 25 at 3:43 pm

    8. проверить провайдера по адресу
      kazan-domashnij-internet005.ru
      недорогой интернет казань

      internetelini

      19 Aug 25 at 3:45 pm

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

      Walterskips

      19 Aug 25 at 3:45 pm

    10. спортивные события [url=https://www.novosti-sporta-12.ru]https://www.novosti-sporta-12.ru[/url] .

    11. I have been surfing online more than three
      hours today, yet I never found any interesting article like
      yours. It is pretty worth enough for me. Personally, if all site owners and bloggers made good content as you
      did, the net will be a lot more useful than ever before.

    12. Outstanding post however , I was wondering if you could write a
      litte more on this subject? I’d be very grateful if you
      could elaborate a little bit further. Thank you!

    13. Lloydrar

      19 Aug 25 at 3:50 pm

    14. купить аттестат за 10 и 11 классы [url=https://www.arus-diplom24.ru]купить аттестат за 10 и 11 классы[/url] .

      Diplomi_amKn

      19 Aug 25 at 3:51 pm

    15. Boostaro is a natural male enhancement formula that’s
      designed to improve circulation, support stamina, and boost overall performance.
      It focuses on heart and blood vessel health, which can have a
      direct impact on energy and confidence. Many men like it because it offers a safe, plant-based way to
      feel stronger and more revitalized without resorting to synthetic options.

      Boostaro

      19 Aug 25 at 4:02 pm

    16. Platform TESLATOTO menghadirkan kumpulan demo slot resmi dari provider top seperti Pragmatic Play & PG Soft.
      Mainkan tanpa deposit game populer seperti Olympus,
      Bonanza Manis, dan slot naga Mahjong Ways tanpa biaya.
      Dapatkan sensasi bermain slot gacor 100% tanpa bayar.

      teslatoto daftar

      19 Aug 25 at 4:05 pm

    17. Уверен, эта информация будет для вас полезна:

      Кстати, если вас интересует obender.ru, посмотрите сюда.

      Ссылка ниже:

      [url=https://obender.ru]https://obender.ru[/url]

      Буду рад, если кому-то пригодится.

      rusPoito

      19 Aug 25 at 4:06 pm

    18. Lloydrar

      19 Aug 25 at 4:10 pm

    19. купить аттестат за 11 класс фото [url=arus-diplom24.ru]купить аттестат за 11 класс фото[/url] .

      Diplomi_ahKn

      19 Aug 25 at 4:17 pm

    20. Non-prescription ED tablets discreetly shipped [url=https://kamameds.shop/#]Fast-acting ED solution with discreet packaging[/url] Non-prescription ED tablets discreetly shipped

      RobertCat

      19 Aug 25 at 4:18 pm

    21. I needed too thank you for this great read!!
      I certainly enjoyed every bit of it. I have you bookmarked to check oout
      new things you post…

    22. Yes! Finally someone writes about WWE.

      WWE releases

      19 Aug 25 at 4:23 pm

    23. Having read this I believed it was extremely enlightening.
      I appreciate you finding the time and energy to put this informative article together.

      I once again find myself personally spending a lot of time both reading and posting comments.
      But so what, it was still worth it!

    24. DavidWah

      19 Aug 25 at 4:27 pm

    25. Lloydrar

      19 Aug 25 at 4:30 pm

    26. Hi there, I found your web site by means of Google even as
      looking for a comparable topic, your site got here up,
      it appears to be like good. I have bookmarked it in my google bookmarks.

      Hi there, simply became aware of your blog thru Google, and located that it’s really informative.
      I am gonna be careful for brussels. I will be grateful should you continue
      this in future. Numerous other folks will probably be benefited from your writing.

      Cheers!

      inatogel

      19 Aug 25 at 4:35 pm

    27. Woah! I’m really enjoying the template/theme of this site.

      It’s simple, yet effective. A lot of times it’s very difficult to get that “perfect balance” between user friendliness and visual
      appeal. I must say you have done a excellent job with this.
      Also, the blog loads very quick for me on Safari. Excellent Blog!

      Vorentlavia

      19 Aug 25 at 4:38 pm

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

      BrucePal

      19 Aug 25 at 4:41 pm

    29. AnthonyNitte

      19 Aug 25 at 4:44 pm

    30. I’ve read several good stuff here. Definitely value bookmarking for revisiting.

      I surprise how so much attempt you put to create this
      type of wonderful informative website.

    31. An outstanding share! I have just forwarded
      this onto a coworker who was doing a little research on this.
      And he in fact bought me breakfast simply because I found it for him…
      lol. So let me reword this…. Thanks for the meal!! But yeah, thanx for spending time to discuss this topic here on your site.

    32. Lloydrar

      19 Aug 25 at 4:51 pm

    33. Лечение выводится поэтапно, чтобы обеспечить безопасность и максимальную эффективность терапии. Каждый этап продуман и адаптирован под индивидуальные особенности пациента.
      Изучить вопрос глубже – [url=https://narcolog-na-dom-krasnoyarsk0.ru/]вызов нарколога на дом цена в красноярске[/url]

      Ignaciohap

      19 Aug 25 at 4:51 pm

    34. GMO Gaika Reputation – Pros, Cons, and the Truth About Withdrawal Refusals

      GMO Gaika is widely used by both beginners and experienced FX traders. Its popularity stems from easy-to-use trading tools, stable spreads, and a high level of trust due to its operation by a major Japanese company. Many users feel secure thanks to this strong domestic backing.

      On the other hand, there are some online rumors about “withdrawal refusals,” but in most cases, these are due to violations of terms or incomplete identity verification. GMO Gaika’s transparent response to such issues suggests that serious problems are not a frequent occurrence.

      You can find more detailed insights into the pros and cons of GMO Gaika, as well as real user experiences, on the trusted investment site naughty-cao.jp. If you’re considering opening an account, it’s a good idea to review this information beforehand.

      naughty-cao.jp

      19 Aug 25 at 4:53 pm

    35. Купить бетон в Иркутске стало проще – вы можете заказать нужный объем прямо с завода, без посредников и переплат. Мы производим товарный бетон на современном оборудовании, контролируя каждый этап. Наша продукция используется при строительстве частных домов, промышленных объектов, дорог и фундаментов, узнайте больше по ссылке https://proirkbeton.ru/

      StanleyJem

      19 Aug 25 at 4:53 pm

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

      vivodsmolenskNeT

      19 Aug 25 at 4:58 pm

    37. Если человек страдает от алкоголизма, запойное состояние требует незамедлительного вмешательства, особенно если признаки токсического отравления начинают угрожать жизни. Признаки запоя — это не только физическая зависимость, но и эмоциональные и психические расстройства, такие как тревога, агрессия и галлюцинации.
      Изучить вопрос глубже – https://narcolog-na-dom-novokuznetsk0.ru/

      Robertbagma

      19 Aug 25 at 5:01 pm

    38. Алкогольная и наркотическая зависимость оказывают разрушительное воздействие на организм, нарушая работу сердечно-сосудистой системы, печени, почек и головного мозга. Запои и передозировки приводят к острой интоксикации, которая без медицинской помощи может перерасти в поражение внутренних органов, психоз или даже летальный исход.
      Ознакомиться с деталями – http://

      AlfonsoBup

      19 Aug 25 at 5:01 pm

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

      RickeyEcomo

      19 Aug 25 at 5:02 pm

    40. Клиника «АнтиАлко» предлагает экстренную медицинскую помощь на дому в Новосибирске и Новосибирской области для тех, кто столкнулся с запоем. Если вы или ваш близкий оказались в состоянии длительной алкогольной интоксикации, наши специалисты готовы оперативно приехать к вам, провести комплексную детоксикацию и купировать симптомы абстинентного синдрома. Мы гарантируем высокий уровень безопасности, полную анонимность и индивидуальный подход к каждому пациенту.
      Углубиться в тему – [url=https://vyvod-iz-zapoya-novosibirsk00.ru/]вывод из запоя на дому цена в новосибирске[/url]

      DavidBrard

      19 Aug 25 at 5:02 pm

    41. Сделайте первый шаг к трезвости. Круглосуточный вывод из запоя в Москве от «Alco.Rehab» — безопасно, надёжно, профессионально.
      Узнать больше – [url=https://nazalnyj.ru/]вывод из запоя капельница[/url]

      AlbertThade

      19 Aug 25 at 5:04 pm

    42. I got this web page from my friend who told me on the topic of this web site and at the moment this time I am visiting this site and reading very informative articles here.
      https://naduvnie-lodki.com.ua/yak-pravylno-vybraty-stekla-far-dlya-vashoho-avtom.html

      Fobertsax

      19 Aug 25 at 5:10 pm

    43. Lloydrar

      19 Aug 25 at 5:12 pm

    44. DavidWah

      19 Aug 25 at 5:12 pm

    45. Drugs prescribing information. Drug Class.
      buying generic verapamil without a prescription
      Some trends of pills. Read now.

    46. What we’re covering
      • Zelensky in Washington: European leaders will join Ukrainian President Volodymyr Zelensky at the White House, as he meets with US President Donald Trump this afternoon. Trump said Zelensky must agree to some of Russia’s conditions — including that Ukraine cede Crimea and agree never to join NATO — for the war to end.
      [url=https://kra-32cc.com]kra38 cc[/url]
      • Potential security guarantees: At last week’s summit with Trump, Russian President Vladimir Putin agreed to allow security guarantees for Ukraine and made concessions on “land swaps” as part of a potential peace deal, US envoy Steve Witkoff told CNN. Zelensky suggested that such guarantees would need to be stronger than those that “didn’t work” in the past. Russia has yet to mention such agreements.
      [url=https://kra38-at.cc]kra30[/url]
      • On the ground: Zelensky condemned Russia’s latest strikes across Ukraine, which killed at least 10 people, saying the Kremlin intends to “humiliate diplomatic efforts” and underscores “why reliable security guarantees are required.”
      kra39 cc
      https://at-kra31.cc

      Jasonsodia

      19 Aug 25 at 5:20 pm

    47. gessi официальный сайт [url=www.gessi-santehnika-5.ru/]gessi официальный сайт[/url] .

    48. Процедура начинается с осмотра и сбора анамнеза. После этого специалист проводит экстренную детоксикацию, снимает симптомы абстинентного синдрома, назначает поддерживающую терапию и даёт рекомендации по дальнейшим шагам. По желанию родственников или самого пациента помощь может быть оказана и в условиях стационара клиники.
      Углубиться в тему – [url=https://narkologicheskaya-pomoshch-domodedovo6.ru/]срочная наркологическая помощь на дому[/url]

      CalvinPrath

      19 Aug 25 at 5:22 pm

    49. nmoeaa6547

      19 Aug 25 at 5:23 pm

    Leave a Reply