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 19,704 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 , , ,

    19,704 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. Williamthimi

      16 Aug 25 at 10:07 am

    2. Willardken

      16 Aug 25 at 10:08 am

    3. По ссылке https://vc.ru/crypto/2132102-obmen-usdt-v-nizhnem-novgorode-podrobnyi-gid-v-2025-godu почитайте информацию про то, как обменять USDT в городе Нижнем Новгороде. Перед вами самый полный гид, из которого вы в подробностях узнаете о том, как максимально безопасно, быстро произвести обмен USDT и остальных популярных криптовалют. Есть информация и о том, почему выгодней сотрудничать с профессиональным офисом, и почему это считается безопасно. Статья расскажет вам и о том, какие еще криптовалюты являются популярными в Нижнем Новгороде.

      KawamAntep

      16 Aug 25 at 10:10 am

    4. MichaelNox

      16 Aug 25 at 10:14 am

    5. LemuelJaido

      16 Aug 25 at 10:25 am

    6. Link exchange is nothing else except it is only placing the
      other person’s weblog link on your page at
      appropriate place and other person will also do similar
      in support of you.

    7. Современная наркология предлагает два основных формата вывода из запоя:
      Получить дополнительную информацию – [url=https://nadezhnyj-vyvod-iz-zapoya.ru/]срочный вывод из запоя санкт-петербруг[/url]

      MichaelMes

      16 Aug 25 at 10:29 am

    8. По ссылке https://tartugi.net/111268-kak-priruchit-drakona.html вы сможете посмотреть увлекательный, добрый и интересный мультфильм «Как приручить дракона». Он сочетает в себе сразу несколько жанров, в том числе, приключения, комедию, семейный, фэнтези. На этом портале он представлен в отличном качестве, с хорошим звуком, а посмотреть его получится на любом устройстве, в том числе, планшете, телефоне, ПК, в командировке, во время длительной поездки или в выходной день. Мультик обязательно понравится вам, ведь в нем сочетается юмор, доброта и красивая музыка.

      DalanoHof

      16 Aug 25 at 10:31 am

    9. Lonnienam

      16 Aug 25 at 10:33 am

    10. generic sildenafil from india: can you buy viagra in mexico over the counter – female version of viagra

      PeterTEEFS

      16 Aug 25 at 10:34 am

    11. RichardPep

      16 Aug 25 at 10:36 am

    12. What’s up, for all time i used to check website posts here in the early
      hours in the morning, for the reason that i
      enjoy to gain knowledge of more and more.

      ibobet

      16 Aug 25 at 10:45 am

    13. Скорая наркологическая помощь в Москве — Narcology Clinic выезжает круглосуточно напрямую к пациенту. Срочные капельницы, детокс, контроль состояния и экстренная поддержка. Анонимно, профессионально, оперативно.
      Узнать больше – [url=https://skoraya-narkologicheskaya-pomoshch-moskva11.ru/]экстренная наркологическая помощь москве[/url]

      TerryPROOT

      16 Aug 25 at 10:47 am

    14. When some one searches for his required
      thing, so he/she wishes to be available that in detail, so
      that thing is maintained over here.

    15. Lonnienam

      16 Aug 25 at 10:53 am

    16. https://nature75185.full-design.com/selecci%C3%B3n-de-personal-para-tontos-78786806

      La contratación de talento es fundamental para el desempeño de cualquier organización.
      Tener el equipo correcto en los puestos correctos potencia los resultados en productividad.

      1. Identificar el puesto ideal
      Antes de comenzar el proceso de reclutamiento, es vital definir con claridad el perfil profesional que la empresa requiere. Esto incluye habilidades técnicas, trayectoria y valores que se alineen con la cultura de la organización.

      2. Fuentes de talento
      Hoy en día, las organizaciones pueden usar bolsas de empleo como Indeed, además de programas de recomendación para conseguir al mejor talento.
      Diversificar fuentes aumenta la posibilidad de reclutar candidatos de calidad.

      3. Preselección y entrevistas
      Una vez recibidas las solicitudes, se debe filtrar a los perfiles que más se acercan a los requisitos.
      Después, las entrevistas sirven para evaluar no solo la experiencia del candidato, sino también su encaje cultural con la empresa.

      4. Pruebas y evaluaciones
      Para asegurar que el candidato ideal cumple con lo esperado, se pueden realizar tests de competencias, análisis de personalidad o dinámicas de grupo.
      Esto reduce el margen de equivocación al contratar.

      5. Selección definitiva
      Tras el proceso de evaluación, se procede de seleccionar al candidato que mejor cumple con los requisitos.
      La comunicación clara y un buen onboarding son cruciales para garantizar que el nuevo empleado se integre fácilmente.

      6. Seguimiento y mejora continua
      Un proceso de reclutamiento nunca se queda fijo.
      Medir indicadores como rotación de personal permite optimizar la estrategia y mejorar los resultados.

      En definitiva, el proceso de contratación es mucho más que cubrir puestos.
      Es una apuesta en el futuro de la empresa, donde atraer al equipo adecuado define su éxito.

      JuniorShido

      16 Aug 25 at 10:54 am

    17. Raymondtew

      16 Aug 25 at 10:56 am

    18. hi!,I love your writing very much! proportion we keep in touch extra
      about your post on AOL? I require an expert
      on this area to solve my problem. Maybe that’s you! Looking
      forward to look you. https://redebuck.com.br/read-blog/55056_kupit-diplom-ob-okonchanii-11-klassov.html

    19. Greetings! I’ve been reading your web site for
      some time now and finally got the courage to go ahead and give you a shout out from New Caney Texas!
      Just wanted to tell you keep up the fantastic job!

      Sentrip 구매

      16 Aug 25 at 11:04 am

    20. ламинирование бровей севастополь Салон красоты Севастополь: Место, где рождается красота. Полный спектр услуг для создания неповторимого образа.

      RickyNut

      16 Aug 25 at 11:04 am

    21. JessieSic

      16 Aug 25 at 11:08 am

    22. Does your website have a contact page? I’m having trouble locating it but, I’d like to send you an email.
      I’ve got some creative ideas for your blog you
      might be interested in hearing. Either way, great blog and I look forward to seeing
      it grow over time.

    23. Lonnienam

      16 Aug 25 at 11:13 am

    24. what possible side effect should a patient taking tadalafil report to a physician quizlet: Tadalify – cialis or levitra

      PeterTEEFS

      16 Aug 25 at 11:14 am

    25. Основные показания для обращения в нашу клинику включают.
      Выяснить больше – https://alko-konsultaciya.ru/vivod-iz-zapoya-cena-v-smolenske

      CharlesDinly

      16 Aug 25 at 11:17 am

    26. Экстренная помощь при алкоголизме от Narcology Clinic в Москве — выезд врачей в любую точку города, купирование острых состояний, поддержка пациента до стабильного состояния, профессионально и в конфиденциальности.
      Разобраться лучше – [url=https://skoraya-narkologicheskaya-pomoshch-moskva.ru/]частная скорая наркологическая помощь[/url]

      Robertkix

      16 Aug 25 at 11:18 am

    27. Для максимальной эффективности и безопасности «Красмед» использует комбинированные подходы:
      Подробнее – [url=https://medicinskij-vyvod-iz-zapoya.ru/]вывод из запоя на дому[/url]

      RobertExevy

      16 Aug 25 at 11:19 am

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

      Elmerlar

      16 Aug 25 at 11:20 am

    29. купить диплом с занесением реестра [url=https://arus-diplom34.ru]купить диплом с занесением реестра[/url] .

    30. Состав инфузии подбирается врачом индивидуально, с учётом состояния пациента, длительности запоя, возраста и хронических заболеваний.
      Подробнее можно узнать тут – [url=https://kapelnica-ot-zapoya-krasnoyarsk6.ru/]поставить капельницу от запоя на дому[/url]

      Bobbyunfig

      16 Aug 25 at 11:23 am

    31. LarryIdons

      16 Aug 25 at 11:23 am

    32. привод somfy [url=https://avtomatika-somfy.ru]https://avtomatika-somfy.ru[/url] .

    33. Hi just wanted to give you a quick heads up and let you know a few of the
      pictures aren’t loading properly. I’m not sure why but I think its a linking issue.
      I’ve tried it in two different internet browsers and both
      show the same results.

      idm full version

      16 Aug 25 at 11:30 am

    34. Lonnienam

      16 Aug 25 at 11:32 am

    35. Refresh Renovation Southwest Charlotte
      1251 Arrow Pine Ꭰr c121,
      Charlotte, NC 28273, United Ꮪtates
      +19803517882
      Services condo renovation

    36. Оптимально для пациентов в стабильном состоянии. Процедура начинается с приезда врача, осмотра и постановки капельницы с индивидуально подобранными растворами.
      Ознакомиться с деталями – https://narko-zakodirovan2.ru/vyvod-iz-zapoya-kruglosutochno-novosibirsk/

      MarvinGon

      16 Aug 25 at 11:42 am

    37. I think the admin of this web page is in fact working hard
      for his web page, since here every data is quality
      based material.

      koitoto

      16 Aug 25 at 11:47 am

    38. see more

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

      see more

      16 Aug 25 at 11:50 am

    39. JessieSic

      16 Aug 25 at 11:50 am

    40. Lonnienam

      16 Aug 25 at 11:52 am

    41. Портал о строительстве https://juglans.com.ua свежие новости, статьи и советы. Обзоры технологий, материалов, дизайн-идеи и практические рекомендации для профессионалов и частных застройщиков.

      DavidHauch

      16 Aug 25 at 11:55 am

    42. Строительный портал https://dki.org.ua всё о строительстве и ремонте: технологии, оборудование, материалы, идеи для дома. Новости отрасли и экспертные рекомендации.

      Douglasgok

      16 Aug 25 at 11:57 am

    43. взлом телеграмм Мы помогаем взломать: Социальные сети. Узнайте, что скрывается за закрытыми профилями, раскройте тайны личной переписки, получите доступ к скрытым фотографиям и видео. Мы поможем вам получить полную картину интересующего вас человека.

      Charlesroary

      16 Aug 25 at 11:57 am

    44. Hey there would you mind stating which blog platform
      you’re working with? I’m looking to start my own blog soon but I’m having a hard time deciding
      between BlogEngine/Wordpress/B2evolution and Drupal. The reason I ask is because your design seems different then most
      blogs and I’m looking for something unique. P.S My apologies for getting off-topic but I had to ask!

    45. Оказывать медуслуги можно только при наличии [url=https://licenz.pro/med-litsenziya/]лицензия на осуществление медицинской деятельности[/url]. Мы подготовим документы, пройдём проверки и оформим всё по закону. Процесс займёт минимум времени с вашей стороны. Начните работать официально и привлекать клиентов, не опасаясь проверок или приостановки бизнеса.

    46. Онлайн строительный https://texha.com.ua портал о материалах, проектах и технологиях. Всё о ремонте, строительстве и обустройстве дома. Поддержка специалистов и вдохновение для новых идей.

      RobertPrany

      16 Aug 25 at 11:58 am

    47. Всё о стройке https://mramor.net.ua полезные статьи, советы, обзоры материалов и технологий. Ремонт, строительство домов, дизайн интерьера и современные решения для вашего проекта.

      PeterDog

      16 Aug 25 at 12:01 pm

    48. Портал о строительстве https://juglans.com.ua свежие новости, статьи и советы. Обзоры технологий, материалов, дизайн-идеи и практические рекомендации для профессионалов и частных застройщиков.

      DavidHauch

      16 Aug 25 at 12:01 pm

    49. Сайт «Всё о стройке» https://sushico.com.ua подробные инструкции, советы экспертов, новости рынка. Всё о строительстве, ремонте и обустройстве жилья в одном месте.

      AlbertJEOTS

      16 Aug 25 at 12:03 pm

    50. SildenaPeak: viagra pill where to buy – SildenaPeak

      ElijahKic

      16 Aug 25 at 12:03 pm

    Leave a Reply