PHP hook, building hooks in your application
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!
seo бесплатно [url=www.kursy-seo-12.ru]seo бесплатно[/url] .
kyrsi seo_tgor
30 Oct 25 at 10:54 pm
купить диплом института с реестром [url=www.frei-diplom6.ru]купить диплом института с реестром[/url] .
Diplomi_dkOl
30 Oct 25 at 10:54 pm
CIR Legal Lexington
201 Ꮤ Short Ѕt #500,
Lexington, KY 40507, United Տtates
+18596366803
lawyers ρro bono – Kristina,
Kristina
30 Oct 25 at 10:55 pm
диплом внесенный в реестр купить [url=https://frei-diplom2.ru/]диплом внесенный в реестр купить[/url] .
Diplomi_otEa
30 Oct 25 at 10:55 pm
Легко создает картинки и анимацию по запросам, а также генерирует видео на основе изображений (пока тестируется).
Смотреть подробнее
30 Oct 25 at 10:55 pm
надо испробывать…много хороших отзывов купить онлайн мефедрон, экстази, бошки Заказываю 2c-I для начала 1 г!!
Keithjoima
30 Oct 25 at 10:56 pm
купить диплом в астрахани [url=https://www.rudik-diplom11.ru]купить диплом в астрахани[/url] .
Diplomi_chMi
30 Oct 25 at 10:56 pm
Каждая компания — ИТ-компания сайт kraken onion kraken зеркало рабочее актуальные зеркала kraken kraken сайт зеркала
RichardPep
30 Oct 25 at 10:57 pm
seo интенсив [url=www.kursy-seo-12.ru]www.kursy-seo-12.ru[/url] .
kyrsi seo_tvor
30 Oct 25 at 10:57 pm
купить диплом в камышине [url=www.rudik-diplom5.ru]купить диплом в камышине[/url] .
Diplomi_spma
30 Oct 25 at 10:58 pm
купить диплом техникума украина [url=https://frei-diplom9.ru]купить диплом техникума украина[/url] .
Diplomi_wyea
30 Oct 25 at 10:59 pm
seo с нуля [url=https://kursy-seo-12.ru/]https://kursy-seo-12.ru/[/url] .
kyrsi seo_txor
30 Oct 25 at 10:59 pm
автоматические гардины для штор [url=www.elektrokarniz797.ru/]www.elektrokarniz797.ru/[/url] .
elektrokarniz_jtEi
30 Oct 25 at 11:00 pm
Profitez d’un code promo unique sur 1xBet permettant a chaque nouveau joueur de beneficier jusqu’a 100€ de bonus sportif a hauteur de 100% en 2026. Le bonus sera ajoute a votre solde en fonction de votre premier depot, le depot minimum etant fixe a 1€. Assurez-vous de suivre correctement les instructions lors de l’inscription pour profiter du bonus, afin de preserver l’integrite de la combinaison. Le bonus de bienvenue n’est pas la seule promotion ou vous pouvez utiliser un code, d’autres combinaisons vous permettant d’obtenir des bonus supplementaires sont disponibles dans la section « Vitrine des codes promo ». Vous pouvez trouver le code promo 1xbet sur ce lien — https://www.atrium-patrimoine.com/wp-content/artcls/?code_promo_196.html.
Robertinjus
30 Oct 25 at 11:01 pm
где купить диплом среднем [url=www.educ-ua7.ru]www.educ-ua7.ru[/url] .
Diplomi_xnea
30 Oct 25 at 11:01 pm
This includes rigorous testing of raw materials, adherence to standardized manufacturing processes, and thorough quality checks on the ultimate product.
While the product itself might not have an “FDA approval” stamp,
the adherence to those regulatory requirements and the high-high quality manufacturing processes
assure its safety and efficacy. Where to purchase Biogenix Relief Glycogen Support Extreme?
Biogenix Relief Glycogen Support Extreme could
be purchased straight from the official Biogenix webpage.
This ensures that you get the real product and
may make the most of unique provides and discounts out there solely
via the official site. Additionally, shopping for straight from the producer guarantees entry to customer
support and a 30-day money-back guarantee. Explore Best Blood Sugar Support Supplement.
Biogenix Relief Glycogen Support Extreme is a complete and efficient complement
for managing blood sugar levels, bettering metabolic well being, and supporting general nicely-being.
With a potent blend of scientifically validated substances like Berberine Extract, Cinnamon Bark
Powder, and White Mulberry Leaf, the product provides multi-faceted advantages that address
varied aspects of well being.
my homepage … improve healthy circulation
improve healthy circulation
30 Oct 25 at 11:02 pm
Полная версия материала тут: https://www.smolnews.ru/news/798119
StevenGathe
30 Oct 25 at 11:02 pm
Здравствуйте!
купить постоянный виртуальный номер — это удобный шаг к безопасности. Наш сервис позволяет купить постоянный виртуальный номер за секунды. Надёжная платформа, чтобы купить постоянный виртуальный номер. Мы гарантируем анонимность, если вы решите купить постоянный виртуальный номер. покупайте постоянный виртуальный номер легко и уверенно.
Полная информация по ссылке – [url=https://7sp.ru/virtualnye-nomera-dlya-biznesa-kak-vybrat-luchshiy-variant-dlya-vashey-kompanii/]купить номер виртуальный навсегда[/url]
виртуальный номер навсегда, постоянный виртуальный номер, купить виртуальный номер навсегда
купить постоянный виртуальный номер, купить виртуальный номер телефона навсегда, купить постоянный виртуальный номер
Удачи и комфорта в общении!!
Nomerpl
30 Oct 25 at 11:02 pm
купить диплом врача с занесением в реестр [url=http://frei-diplom2.ru]купить диплом врача с занесением в реестр[/url] .
Diplomi_beEa
30 Oct 25 at 11:02 pm
электрические рулонные шторы [url=http://rulonnye-shtory-s-elektroprivodom7.ru/]электрические рулонные шторы[/url] .
rylonnie shtori s elektroprivodom_prMl
30 Oct 25 at 11:04 pm
электронный карниз для штор [url=http://elektrokarniz499.ru]электронный карниз для штор[/url] .
elektrokarniz_uwKl
30 Oct 25 at 11:04 pm
I constantly emailed this web site post page to all my associates, since if like to read it next my links will too.
lengkap777
30 Oct 25 at 11:05 pm
купить аттестат за 11 класс [url=http://rudik-diplom10.ru/]купить аттестат за 11 класс[/url] .
Diplomi_kjSa
30 Oct 25 at 11:05 pm
купить диплом техникума с занесением пять плюс [url=http://frei-diplom9.ru/]купить диплом техникума с занесением пять плюс[/url] .
Diplomi_jqea
30 Oct 25 at 11:05 pm
skachat linebet
linebet promo code
30 Oct 25 at 11:06 pm
купить диплом о высшем с занесением в реестр [url=www.frei-diplom4.ru/]купить диплом о высшем с занесением в реестр[/url] .
Diplomi_hqOl
30 Oct 25 at 11:06 pm
купить диплом с занесением в реестр москва [url=https://www.frei-diplom6.ru]купить диплом с занесением в реестр москва[/url] .
Diplomi_viOl
30 Oct 25 at 11:06 pm
seo курсы [url=https://kursy-seo-12.ru/]seo курсы[/url] .
kyrsi seo_bcor
30 Oct 25 at 11:07 pm
Ресторан чистый после уничтожение клопов.
уничтожение вредителей
KennethceM
30 Oct 25 at 11:08 pm
Купить диплом техникума в Полтава [url=http://educ-ua7.ru]http://educ-ua7.ru[/url] .
Diplomi_snea
30 Oct 25 at 11:08 pm
купить диплом электрика [url=www.rudik-diplom1.ru]купить диплом электрика[/url] .
Diplomi_qver
30 Oct 25 at 11:08 pm
кракен vk5
кракен даркнет
JamesDaync
30 Oct 25 at 11:08 pm
купить диплом в нижним тагиле [url=www.rudik-diplom5.ru]купить диплом в нижним тагиле[/url] .
Diplomi_qlma
30 Oct 25 at 11:09 pm
заказать рулонные шторы в москве [url=https://www.rulonnye-shtory-s-elektroprivodom7.ru]заказать рулонные шторы в москве[/url] .
rylonnie shtori s elektroprivodom_zzMl
30 Oct 25 at 11:09 pm
купить диплом с проводкой меня [url=www.frei-diplom2.ru/]купить диплом с проводкой меня[/url] .
Diplomi_xqEa
30 Oct 25 at 11:10 pm
купить диплом электрика техникум [url=https://frei-diplom9.ru]купить диплом электрика техникум[/url] .
Diplomi_hgea
30 Oct 25 at 11:10 pm
купить диплом в ханты-мансийске [url=https://rudik-diplom10.ru]купить диплом в ханты-мансийске[/url] .
Diplomi_otSa
30 Oct 25 at 11:11 pm
Ресторан чистый после уничтожение тараканов в общежитии.
уничтожение клещей на даче
Wernermog
30 Oct 25 at 11:12 pm
chery 7 pro max chery tiggo 7 pro
chery-604
30 Oct 25 at 11:12 pm
купить диплом с занесением в реестр в архангельске [url=http://www.frei-diplom4.ru]купить диплом с занесением в реестр в архангельске[/url] .
Diplomi_woOl
30 Oct 25 at 11:12 pm
Срочно нужна санобработка, тараканы достали!
санобработка
KennethceM
30 Oct 25 at 11:13 pm
https://t.me/s/Beefcasino_rus/57
LuckyBandit
30 Oct 25 at 11:13 pm
де бере початок річка дністер
Michaelmaync
30 Oct 25 at 11:13 pm
кракен тор
кракен тор
JamesDaync
30 Oct 25 at 11:13 pm
Программирование — язык нового поколения кракен даркнет маркет кракен онион тор кракен онион зеркало кракен даркнет маркет
RichardPep
30 Oct 25 at 11:14 pm
курсы по seo [url=www.kursy-seo-12.ru]курсы по seo[/url] .
kyrsi seo_hxor
30 Oct 25 at 11:15 pm
Hey are using WordPress for your site platform?
I’m new to the blog world but I’m trying to get started and set up my own.
Do you need any coding knowledge to make your own blog?
Any help would be really appreciated!
Power Washing Company
30 Oct 25 at 11:16 pm
Цены на обработка от тараканов выросли? Обсудим.
уничтожение тараканов с гарантией
KennethceM
30 Oct 25 at 11:17 pm
купить диплом в кирове [url=https://rudik-diplom11.ru/]купить диплом в кирове[/url] .
Diplomi_uuMi
30 Oct 25 at 11:17 pm
Наркологическая клиника в Воронеже — это специализированное медицинское учреждение, предоставляющее помощь людям, столкнувшимся с зависимостью от алкоголя, наркотиков и других психоактивных веществ. Лечение проводится под контролем квалифицированных врачей, с использованием современных методик детоксикации, психотерапии и реабилитации. Цель работы специалистов — не только устранить физическую зависимость, но и помочь пациенту восстановить эмоциональное равновесие, вернуть контроль над поведением и мотивацию к трезвости.
Выяснить больше – [url=https://narkologicheskaya-clinica-v-voronezhe17.ru/]наркологическая клиника цены в воронеже[/url]
Marioscene
30 Oct 25 at 11:17 pm