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!
Spedra prezzo basso Italia: farmacia viva – comprare medicinali online legali
RichardImmon
30 Oct 25 at 9:09 pm
Надеюсь. Очень жду! Кто уже попробовал скажите как вещество?! Не хуже чем было? купить онлайн мефедрон, экстази, бошки всё ровн ждём =)
Robertdug
30 Oct 25 at 9:10 pm
купить проведенный диплом провести [url=https://frei-diplom2.ru/]купить проведенный диплом провести[/url] .
Diplomi_ndEa
30 Oct 25 at 9:10 pm
ніколь ім’я значення
Michaelmaync
30 Oct 25 at 9:10 pm
seo специалист [url=www.kursy-seo-12.ru/]seo специалист[/url] .
kyrsi seo_wuor
30 Oct 25 at 9:12 pm
электропривод рулонных штор [url=https://www.rulonnye-shtory-s-elektroprivodom7.ru]https://www.rulonnye-shtory-s-elektroprivodom7.ru[/url] .
rylonnie shtori s elektroprivodom_wrMl
30 Oct 25 at 9:13 pm
seo бесплатно [url=https://kursy-seo-12.ru/]seo бесплатно[/url] .
kyrsi seo_afor
30 Oct 25 at 9:14 pm
chery pro chery tiggo t
chery-308
30 Oct 25 at 9:15 pm
https://wakelet.com/wake/_VmCWDJFu2QXrwwl-IzEm
Martinphalk
30 Oct 25 at 9:17 pm
купить диплом техникума в твери [url=http://www.frei-diplom9.ru]купить диплом техникума в твери[/url] .
Diplomi_xzea
30 Oct 25 at 9:17 pm
Технологии не стоят на месте kraken onion зеркала kraken зеркало рабочее актуальные зеркала kraken kraken сайт зеркала
RichardPep
30 Oct 25 at 9:20 pm
купить диплом в каменске-уральском [url=https://rudik-diplom5.ru]купить диплом в каменске-уральском[/url] .
Diplomi_qqma
30 Oct 25 at 9:21 pm
Чтобы понять логику процесса, посмотрите на ориентир ниже. Это не жёсткое расписание, а понятная канва, которую врач адаптирует под возраст, сопутствующие заболевания и текущие цифры.
Получить дополнительные сведения – [url=https://narkologicheskaya-klinika-ivanteevka8.ru/]narkologicheskaya-klinika-ryadom[/url]
MelvinVialm
30 Oct 25 at 9:22 pm
VitaHomme: Kamagra pas cher France – Kamagra sans ordonnance
RobertJuike
30 Oct 25 at 9:22 pm
электрокарнизы в москве [url=https://elektrokarniz499.ru]электрокарнизы в москве[/url] .
elektrokarniz_yvKl
30 Oct 25 at 9:22 pm
seo курсы [url=https://kursy-seo-12.ru/]seo курсы[/url] .
kyrsi seo_gwor
30 Oct 25 at 9:23 pm
https://farmaciavivait.com/# pillole per disfunzione erettile
Davidjealp
30 Oct 25 at 9:24 pm
Свежее и важное тут: https://www.yerkramas.org/article/197840/pechat-blankov-vidy–materialy-i-osobennosti-izgotovleniya-v-tipografii
StevenGathe
30 Oct 25 at 9:25 pm
готовые рулонные шторы купить в москве [url=https://www.rulonnye-shtory-s-elektroprivodom7.ru]готовые рулонные шторы купить в москве[/url] .
rylonnie shtori s elektroprivodom_hmMl
30 Oct 25 at 9:25 pm
карнизы для штор купить в москве [url=https://elektrokarniz797.ru/]карнизы для штор купить в москве[/url] .
elektrokarniz_sgEi
30 Oct 25 at 9:27 pm
[url=https://milioner-casino.net/app/]billionaire casino[/url]
Jamestalia
30 Oct 25 at 9:27 pm
acheter Kamagra en ligne: Vita Homme – kamagra oral jelly
RobertJuike
30 Oct 25 at 9:29 pm
Интернет изменил мышление человека кракен онион кракен онион тор кракен онион зеркало кракен даркнет маркет
RichardPep
30 Oct 25 at 9:29 pm
Технологии открывают новые границы актуальные зеркала kraken kraken рабочая ссылка onion сайт kraken onion kraken darknet
RichardPep
30 Oct 25 at 9:30 pm
диплом нефтяного техникума купить [url=https://frei-diplom8.ru/]диплом нефтяного техникума купить[/url] .
Diplomi_czsr
30 Oct 25 at 9:30 pm
linebet вход
linebet uzbekistan
30 Oct 25 at 9:31 pm
купить диплом техникума спб в барнауле [url=https://frei-diplom9.ru]купить диплом техникума спб в барнауле[/url] .
Diplomi_inea
30 Oct 25 at 9:31 pm
Старт всегда один: короткий скрининг с дежурным врачом, где уточняются жалобы, длительность эпизода, текущие лекарства, аллергии и условия дома. Далее согласуется реальное окно прибытия или приёма — без обещаний «через пять минут», но с честным ориентиром и запасом на дорожную обстановку. На месте врач фиксирует витальные показатели (АД, пульс, сатурацию, температуру), по показаниям выполняет ЭКГ, запускает детокс (регидратация, коррекция электролитов, защита печени/ЖКТ), объясняет ожидаемую динамику первых 6–12 часов и выдаёт памятку «на сутки»: режим сна, питьевой план, «красные флажки», точное время контрольной связи. Если домашний формат становится недостаточным, перевод в стационар организуется без пауз — терапия продолжается с того же места, где начата, темп лечения не теряется.
Подробнее – [url=https://narkologicheskaya-klinika-shchyolkovo0.ru/]narkologicheskaya-klinika-otzyvy[/url]
Richardtag
30 Oct 25 at 9:32 pm
продвижение обучение [url=www.kursy-seo-12.ru/]www.kursy-seo-12.ru/[/url] .
kyrsi seo_hmor
30 Oct 25 at 9:32 pm
Диджитализация — ключ к успеху kraken сайт кракен darknet кракен onion кракен ссылка onion
RichardPep
30 Oct 25 at 9:35 pm
Good day! Do you know if they make any plugins to help with Search Engine Optimization?
I’m trying to get my blog to rank for some targeted keywords
but I’m not seeing very good success. If you know of any please share.
Many thanks!
turkey visa for australian
30 Oct 25 at 9:35 pm
купить диплом техникума проведенный [url=frei-diplom8.ru]купить диплом техникума проведенный[/url] .
Diplomi_mzsr
30 Oct 25 at 9:37 pm
Sildenafil générique: Sildenafil générique – Kamagra sans ordonnance
RobertJuike
30 Oct 25 at 9:37 pm
где можно купить диплом медсестры [url=frei-diplom13.ru]где можно купить диплом медсестры[/url] .
Diplomi_wnkt
30 Oct 25 at 9:38 pm
globalmarketplacehub.click – Domain is active, but I couldn’t find live product listings or branding yet.
Erich Degraffenreid
30 Oct 25 at 9:38 pm
Сразу к лучшему сюда: https://piterets.ru/clause/brands/53228-tablichki-iz-pvh-universalnye-reshenija-dlja-reklamy-i-oformlenija.html
StevenGathe
30 Oct 25 at 9:38 pm
dankglassonline.com – Would love to see reviews and specs once the site fully opens for shopping.
Gladys Court
30 Oct 25 at 9:39 pm
Кроме того, Kuaishou является очень жизнеспособным маркетинговым решением, так как в настоящее время коэффициент конверсии в пять раз выше, чем у Douyin.
На сайте
30 Oct 25 at 9:39 pm
differenza tra Spedra e Viagra: comprare medicinali online legali – farmacia viva
ClydeExamp
30 Oct 25 at 9:39 pm
купить диплом техникума общественного питания [url=https://www.frei-diplom9.ru]купить диплом техникума общественного питания[/url] .
Diplomi_gqea
30 Oct 25 at 9:39 pm
курсы по seo [url=https://kursy-seo-12.ru/]курсы по seo[/url] .
kyrsi seo_kyor
30 Oct 25 at 9:40 pm
Thank you for the auspicious writeup. It in fact was a amusement
account it. Look advanced to more added agreeable from you!
However, how could we communicate?
Clonazepam 0.5mg Buy Online Cheap
30 Oct 25 at 9:40 pm
купить диплом вуза занесением реестр [url=http://frei-diplom5.ru/]http://frei-diplom5.ru/[/url] .
Diplomi_ciPa
30 Oct 25 at 9:42 pm
рулонные шторы с электроприводом на окна [url=https://rulonnye-shtory-s-elektroprivodom7.ru/]https://rulonnye-shtory-s-elektroprivodom7.ru/[/url] .
rylonnie shtori s elektroprivodom_zsMl
30 Oct 25 at 9:42 pm
everydayvaluecorner.shop – Shared this link with a friend who loves budget shopping—she’ll check it out.
Jospeh Yen
30 Oct 25 at 9:42 pm
купить диплом занесенный реестр [url=frei-diplom2.ru]купить диплом занесенный реестр[/url] .
Diplomi_efEa
30 Oct 25 at 9:42 pm
прокарниз [url=http://www.elektrokarniz797.ru]http://www.elektrokarniz797.ru[/url] .
elektrokarniz_rqEi
30 Oct 25 at 9:43 pm
автомобиль chery tiggo chery tiggo купить
chery-556
30 Oct 25 at 9:44 pm
диплом юридического колледжа купить [url=http://frei-diplom9.ru]http://frei-diplom9.ru[/url] .
Diplomi_hqea
30 Oct 25 at 9:44 pm
Обновления по теме здесь: https://kirovpravda.ru/lazernaya-epilyaciya-chto-eto-takoe-i-kak-deystvuet-metod
StevenGathe
30 Oct 25 at 9:44 pm