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!
старые дипломы купить [url=https://rudik-diplom15.ru/]старые дипломы купить[/url] .
Diplomi_ayPi
31 Oct 25 at 1:15 pm
автоматические карнизы [url=https://elektrokarniz777.ru/]автоматические карнизы[/url] .
elektrokarniz _aysr
31 Oct 25 at 1:15 pm
Ich liebe das Flair von Cat Spins Casino, es ist ein Ort, der begeistert. Die Auswahl ist einfach unschlagbar, mit packenden Live-Casino-Optionen. Er macht den Einstieg unvergesslich. Die Mitarbeiter antworten prazise. Auszahlungen sind einfach und schnell, jedoch zusatzliche Freispiele waren ein Bonus. In Summe, Cat Spins Casino ist ein Ort fur pure Unterhaltung. Au?erdem die Benutzeroberflache ist klar und flussig, einen Hauch von Eleganz hinzufugt. Besonders erwahnenswert die dynamischen Community-Events, kontinuierliche Belohnungen bieten.
Informationen erhalten|
nightfireus1zef
31 Oct 25 at 1:16 pm
карнизы для штор с электроприводом [url=http://elektrokarniz-kupit.ru]карнизы для штор с электроприводом[/url] .
elektrokarniz kypit_hcea
31 Oct 25 at 1:16 pm
SafeMedsGuide: top rated online pharmacies – trusted online pharmacy USA
HaroldSHems
31 Oct 25 at 1:17 pm
OMT’s emphasis on metacognition ѕhows students to delight
іn thinking օf math, fostering love ɑnd drive for exceptional examination outcomes.
Dive іnto seⅼf-paced math proficiency wіth OMT’ѕ 12-month e-learning courses, t᧐tal
with practice worksheets ɑnd recorded sessions fоr extensive revision.
Ꭺs mathematics underpins Singapore’ѕ track record fօr excellence
in global criteria ⅼike PISA, math tuition is key to ߋpening a kid’s p᧐ssible and protecting
scholastric advantages іn thіs core subject.
Ϝоr PSLE achievers, tuition pгovides mock examinations and feedback, assisting
refine answers fοr optimum marks іn both multiple-choice ɑnd open-endеd aгeas.
Linking mathematics concepts to real-wоrld circumstances ᴡith tuition growѕ understanding,
making Ⲟ Level application-based concerns mߋre approachable.
Tuition іn junior college mathematics furnishes trainees ԝith statistical apρroaches ɑnd chance models impоrtant for interpreting
data-driven inquiries іn Ꭺ Level papers.
OMT’s customized math curriculum attracts attention Ьy bridging MOE ⅽontent with sophisticated theoretical ⅼinks, assisting pupils attach concepts аcross dіfferent math
topics.
Visual aids lіke layouts aid picture troubles lor, boosting understanding ɑnd examination efficiency.
Singapore’ѕ affordable streaming аt үoung ages mаkes very earⅼy math tuition essential fⲟr safeguarding helpful
paths t᧐ examination success.
mу web site :: singapore primary 3 math tuition
singapore primary 3 math tuition
31 Oct 25 at 1:18 pm
Мы стремимся к тому, чтобы каждый наш пациент в Ростове-на-Дону почувствовал заботу и внимание, получая качественную медицинскую помощь.
Детальнее – [url=https://vyvod-iz-zapoya-rostov112.ru/]врач вывод из запоя в ростове-на-дону[/url]
DarrenBrupe
31 Oct 25 at 1:18 pm
электрокарнизы для штор цена [url=https://elektrokarniz-kupit.ru/]электрокарнизы для штор цена[/url] .
elektrokarniz kypit_bzea
31 Oct 25 at 1:18 pm
рулонные шторы с электроприводом [url=https://rulonnye-shtory-s-elektroprivodom7.ru]рулонные шторы с электроприводом[/url] .
rylonnie shtori s elektroprivodom_jqMl
31 Oct 25 at 1:18 pm
Fantastic beat ! I wish to apprentice even as you amend your web site,
how can i subscribe for a weblog site? The account helped me a appropriate deal.
I have been a little bit familiar of this your broadcast
offered vibrant transparent idea
dewascatter link alternatif
31 Oct 25 at 1:19 pm
электрические гардины [url=https://elektrokarniz797.ru/]электрические гардины[/url] .
elektrokarniz_tmEi
31 Oct 25 at 1:19 pm
ролет штора [url=www.avtomaticheskie-rulonnye-shtory1.ru/]ролет штора[/url] .
avtomaticheskie rylonnie shtori_lzMr
31 Oct 25 at 1:20 pm
trusted online pharmacy Australia: cheap medicines online Australia – Aussie Meds Hub Australia
Johnnyfuede
31 Oct 25 at 1:21 pm
compare online pharmacy prices [url=https://safemedsguide.com/#]compare online pharmacy prices[/url] trusted online pharmacy USA
Hermanengam
31 Oct 25 at 1:21 pm
After looking at a number of the articles on your
site, I seriously like your technique of blogging.
I book-marked it to my bookmark webpage list and will be checking back in the near future.
Please visit my website as well and tell me your opinion.
dewascatter login
31 Oct 25 at 1:21 pm
потол [url=www.natyazhnye-potolki-nizhniy-novgorod-1.ru/]www.natyazhnye-potolki-nizhniy-novgorod-1.ru/[/url] .
natyajnie potolki nijnii novgorod_inma
31 Oct 25 at 1:21 pm
рулонные шторы на электроприводе [url=www.rulonnye-shtory-s-elektroprivodom7.ru]рулонные шторы на электроприводе[/url] .
rylonnie shtori s elektroprivodom_exMl
31 Oct 25 at 1:22 pm
карнизы для штор купить в москве [url=http://elektrokarniz797.ru/]карнизы для штор купить в москве[/url] .
elektrokarniz_cgEi
31 Oct 25 at 1:23 pm
рулонные шторки на окна [url=https://avtomaticheskie-rulonnye-shtory77.ru/]рулонные шторки на окна[/url] .
avtomaticheskie rylonnie shtori_bbPa
31 Oct 25 at 1:23 pm
РедМетСплав предлагает широкий ассортимент качественных изделий из ценных материалов. Не важно, какие объемы вам необходимы – от небольших закупок до обширных поставок, мы гарантируем быстрое выполнение вашего заказа.
Каждая единица продукции подтверждена требуемыми документами, подтверждающими их соответствие стандартам. Превосходное обслуживание – наш стандарт – мы на связи, чтобы разрешать ваши вопросы по мере того как предоставлять решения под требования вашего бизнеса.
Доверьте ваш запрос профессионалам РедМетСплав и убедитесь в широком спектре предлагаемых возможностей
поставляемая продукция:
Фольга магниевая 4635 Труба магниевая 4635 – это высококачественный металлический профиль, предназначенный для широкого спектра применения в строительстве и промышленности. Изготавливается из магниевых сплавов, что обеспечивает отличные механические свойства и легкость. Отличается высокой коррозийной стойкостью, что увеличивает срок службы. Идеально подходит для изготовления конструкций, требующих высокой прочности и надежности. Если вы хотите купить Труба магниевая 4635, обратите внимание на ее превосходные характеристики и конкурентоспособную цену. Этот продукт станет отличным решением для ваших проектов.
SheilaAlemn
31 Oct 25 at 1:24 pm
электрокарнизы купить в москве [url=http://elektrokarniz-kupit.ru]электрокарнизы купить в москве[/url] .
elektrokarniz kypit_axea
31 Oct 25 at 1:25 pm
организация онлайн трансляций под ключ [url=www.zakazat-onlayn-translyaciyu5.ru]организация онлайн трансляций под ключ[/url] .
zakazat onlain translyaciu_yzmr
31 Oct 25 at 1:26 pm
Мы предлагаем гибкую систему оплаты и прозрачные цены в Ростове-на-Дону, без скрытых платежей и переплат. Обратившись в нашу клинику в Ростове-на-Дону, вы делаете первый шаг к здоровой и трезвой жизни.
Детальнее – [url=https://vyvod-iz-zapoya-rostov111.ru/]вывод из запоя капельница на дому[/url]
CharlesHox
31 Oct 25 at 1:26 pm
купить диплом зубного техника [url=http://rudik-diplom12.ru/]купить диплом зубного техника[/url] .
Diplomi_wlPi
31 Oct 25 at 1:27 pm
производители рулонных штор [url=https://avtomaticheskie-rulonnye-shtory1.ru/]avtomaticheskie-rulonnye-shtory1.ru[/url] .
avtomaticheskie rylonnie shtori_bcMr
31 Oct 25 at 1:27 pm
электрокарниз двухрядный [url=elektrokarniz797.ru]elektrokarniz797.ru[/url] .
elektrokarniz_oyEi
31 Oct 25 at 1:29 pm
online pharmacy reviews and ratings: SafeMedsGuide – cheapest pharmacies in the USA
HaroldSHems
31 Oct 25 at 1:29 pm
электрокарниз двухрядный цена [url=elektrokarniz-kupit.ru]elektrokarniz-kupit.ru[/url] .
elektrokarniz kypit_mjea
31 Oct 25 at 1:30 pm
Admiring the time and effort you put into your blog and
detailed information you provide. It’s nice to come
across a blog every once in a while that isn’t the same old rehashed material.
Wonderful read! I’ve saved your site and I’m adding your RSS feeds
to my Google account.
dewascatter login
31 Oct 25 at 1:31 pm
электрические карнизы купить [url=https://elektrokarniz797.ru/]elektrokarniz797.ru[/url] .
elektrokarniz_spEi
31 Oct 25 at 1:33 pm
электрические рулонные шторы на окна [url=https://avtomaticheskie-rulonnye-shtory1.ru]электрические рулонные шторы на окна[/url] .
avtomaticheskie rylonnie shtori_yaMr
31 Oct 25 at 1:34 pm
электрокарниз купить в москве [url=elektrokarniz777.ru]электрокарниз купить в москве[/url] .
elektrokarniz _lusr
31 Oct 25 at 1:34 pm
top rated online pharmacies: Safe Meds Guide – promo codes for online drugstores
Johnnyfuede
31 Oct 25 at 1:34 pm
https://t.me/ud_Stake/63
MichaelPione
31 Oct 25 at 1:34 pm
автоматические рулонные шторы на створку [url=https://rulonnye-shtory-s-elektroprivodom7.ru]https://rulonnye-shtory-s-elektroprivodom7.ru[/url] .
rylonnie shtori s elektroprivodom_rfMl
31 Oct 25 at 1:35 pm
Hello friends, how is everything, and what you wish for to say regarding
this piece of writing, in my view its in fact awesome designed for me.
udintogel
31 Oct 25 at 1:35 pm
карниз электроприводом штор купить [url=https://www.elektrokarniz797.ru]https://www.elektrokarniz797.ru[/url] .
elektrokarniz_rfEi
31 Oct 25 at 1:35 pm
электронный карниз для штор [url=www.elektrokarniz-kupit.ru]электронный карниз для штор[/url] .
elektrokarniz kypit_qrea
31 Oct 25 at 1:36 pm
[url=https://www.xn—–clcbled0c6ce0b1dxce.xn--p1ai/]Шары на день рождения[/url] — это идеальный способ украсить любое торжество. Познакомьтесь с коллекцией праздничных украшений и идей, где каждая деталь имеет значение. Красочные латексные шары создают атмосферу праздника в любом месте. Мы предлагаем широкий выбор дизайнов, которые можно заказать с доставкой. Любая комбинация цветов создаются профессиональными декораторами, чтобы всё выглядело стильно и празднично. У нас можно заказать оформление для романтического сюрприза или корпоративного события. Цветы и подарки идеально сочетаются между собой. Каждый клиент для нас важен, поэтому вы получаете готовый к празднику результат. Позвоните нашему менеджеру, чтобы добавить праздник в каждый день. Гелиевые шары — это яркое дополнение к любому подарку. Украсьте свой праздник красиво, ведь каждый подарок у нас — это кусочек радости.
https://www.xn—–clcbled0c6ce0b1dxce.xn--p1ai/
Rolandnup
31 Oct 25 at 1:37 pm
https://t.me/ud_Booi/52
MichaelPione
31 Oct 25 at 1:38 pm
рулонные шторы автоматические купить [url=http://www.avtomaticheskie-rulonnye-shtory1.ru]http://www.avtomaticheskie-rulonnye-shtory1.ru[/url] .
avtomaticheskie rylonnie shtori_jwMr
31 Oct 25 at 1:38 pm
Good day! I know this is kind of off topic but
I was wondering which blog platform are you using for this site?
I’m getting fed up of WordPress because I’ve had problems with hackers and I’m looking at options for another platform.
I would be great if you could point me in the direction of
a good platform.
call girl underage
31 Oct 25 at 1:39 pm
электрокарниз [url=https://www.elektrokarniz-kupit.ru]электрокарниз[/url] .
elektrokarniz kypit_loea
31 Oct 25 at 1:39 pm
non-prescription medicines UK: online pharmacy – legitimate pharmacy sites UK
Johnnyfuede
31 Oct 25 at 1:40 pm
пластиковые окна рулонные шторы с электроприводом [url=http://rulonnye-shtory-s-elektroprivodom7.ru/]http://rulonnye-shtory-s-elektroprivodom7.ru/[/url] .
rylonnie shtori s elektroprivodom_dlMl
31 Oct 25 at 1:41 pm
Whoa! This blog looks just like my old one! It’s on a entirely different
topic but it has pretty much the same page layout and design. Superb choice of colors!
Have a look at my blog качественный сход развал
качественный сход развал
31 Oct 25 at 1:41 pm
купить диплом в севастополе [url=https://rudik-diplom15.ru/]купить диплом в севастополе[/url] .
Diplomi_soPi
31 Oct 25 at 1:41 pm
https://hackmd.io/@1xbetcodespromo/r1P9RAJ1We
JerryChoky
31 Oct 25 at 1:42 pm
Great site, I recommend it to everyone.[url=https://rolete.md/]rolete[/url]
RoleteMd1Nic
31 Oct 25 at 1:43 pm
электрокарниз купить в москве [url=elektrokarniz797.ru]электрокарниз купить в москве[/url] .
elektrokarniz_ifEi
31 Oct 25 at 1:43 pm