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!
у меня знакомец с их магазина закупился его с черта какого то мусора взяли! че к чему не знаю но факт есть факт! может и не они виноваты, но он мелкий торгаш и принимать с сотней его не в тему купить скорость, кокаин, мефедрон, гашиш заказывал мягкого пятак, всё пришло, непрходилось волноваться т.к в аське всегда были на связи, сила средне, но по весу 5+ =)
Keithjoima
31 Oct 25 at 11:20 am
trusted online pharmacy UK: UK online pharmacies list – best UK pharmacy websites
HaroldSHems
31 Oct 25 at 11:21 am
электрокарнизы цена [url=https://www.elektrokarniz-kupit.ru]электрокарнизы цена[/url] .
elektrokarniz kypit_mtea
31 Oct 25 at 11:22 am
электрические гардины для штор [url=https://www.elektrokarniz499.ru]https://www.elektrokarniz499.ru[/url] .
elektrokarniz_bkKl
31 Oct 25 at 11:23 am
рулонные шторы с электроприводом и дистанционным управлением [url=https://avtomaticheskie-rulonnye-shtory77.ru]https://avtomaticheskie-rulonnye-shtory77.ru[/url] .
avtomaticheskie rylonnie shtori_njPa
31 Oct 25 at 11:26 am
натяжные потолки нижний новгород отзывы [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru]натяжные потолки нижний новгород отзывы[/url] .
natyajnie potolki nijnii novgorod_bmma
31 Oct 25 at 11:26 am
Этот информационный материал привлекает внимание множеством интересных деталей и необычных ракурсов. Мы предлагаем уникальные взгляды на привычные вещи и рассматриваем вопросы, которые волнуют общество. Будьте в курсе актуальных тем и расширяйте свои знания!
Узнать больше > – https://eineweltsafaris.com/2020/12/08/a-place-where-start-new-life-with-peace
Josephnaiva
31 Oct 25 at 11:26 am
UK online pharmacies list: Uk Meds Guide – non-prescription medicines UK
HaroldSHems
31 Oct 25 at 11:26 am
автоматические карнизы для штор [url=https://elektrokarniz-kupit.ru]автоматические карнизы для штор[/url] .
elektrokarniz kypit_btea
31 Oct 25 at 11:27 am
[url=https://divoprazdnik.ru/]Воздушные шарики для праздника[/url] — это лучший способ создать настроение. Создают атмосферу веселья и превращают обычный день в праздник. На нашем сайте вы найдете подробные советы для создания праздничной атмосферы. Если вы готовите день рождения, мы расскажем, как украсить помещение шарами по вашему вкусу. Фольгированные шары станут ярким акцентом на дне рождения. Расскажем, какие шары выбрать для конкретного повода, чтобы создать гармоничный декор. Кроме идей для декора есть материалы для вдохновения, которые подарят новые идеи. Советы экспертов подойдут для домашних и выездных праздников. Создать свой уникальный стиль праздника и порадовать гостей. Воздушные композиции — это символ праздника. Создавайте эмоции своими руками вместе с нашими идеями и полезными советами!
https://divoprazdnik.ru/
Alvinknice
31 Oct 25 at 11:30 am
электрокарниз москва [url=www.elektrokarniz-kupit.ru]www.elektrokarniz-kupit.ru[/url] .
elektrokarniz kypit_pwea
31 Oct 25 at 11:31 am
электрические карнизы для штор в москве [url=https://elektrokarniz797.ru]https://elektrokarniz797.ru[/url] .
elektrokarniz_ajEi
31 Oct 25 at 11:31 am
I’ve been browsing on-line more than three hours these days, yet I never
found any fascinating article like yours. It is beautiful worth
enough for me. In my opinion, if all website owners and bloggers made just right content
as you did, the web might be a lot more helpful than ever before.
Pulse Bithazex
31 Oct 25 at 11:32 am
pharmacy delivery Ireland
Edmundexpon
31 Oct 25 at 11:33 am
Хочешь вылечить геморрой – современный подход к лечению геморроя: точная диагностика, персональный план, амбулаторные процедуры за 20–30 минут. Контроль боли, быстрый возврат к активной жизни, рекомендации по образу жизни и профилактике, анонимность и понятные цены.
laser-co-2-936
31 Oct 25 at 11:34 am
dmbet88.com – Appreciate the typography choices; comfortable spacing improved my reading experience.
Renata Lavergne
31 Oct 25 at 11:34 am
карнизы для штор с электроприводом [url=http://elektrokarniz797.ru]карнизы для штор с электроприводом[/url] .
elektrokarniz_zsEi
31 Oct 25 at 11:35 am
горизонтальные жалюзи с электроприводом [url=https://elektricheskie-zhalyuzi97.ru/]горизонтальные жалюзи с электроприводом[/url] .
elektricheskie jaluzi_hmet
31 Oct 25 at 11:35 am
карнизы для штор купить в москве [url=http://www.elektrokarniz499.ru]карнизы для штор купить в москве[/url] .
elektrokarniz_ufKl
31 Oct 25 at 11:36 am
рулонные шторы с электроприводом [url=avtomaticheskie-rulonnye-shtory77.ru]рулонные шторы с электроприводом[/url] .
avtomaticheskie rylonnie shtori_xdPa
31 Oct 25 at 11:36 am
натяжные потолки официальный сайт [url=www.natyazhnye-potolki-nizhniy-novgorod-1.ru]натяжные потолки официальный сайт[/url] .
natyajnie potolki nijnii novgorod_muma
31 Oct 25 at 11:37 am
автоматические рулонные шторы на створку [url=http://rulonnye-shtory-s-elektroprivodom7.ru/]http://rulonnye-shtory-s-elektroprivodom7.ru/[/url] .
rylonnie shtori s elektroprivodom_luMl
31 Oct 25 at 11:37 am
автоматические рулонные шторы на окна [url=www.avtomaticheskie-rulonnye-shtory77.ru]www.avtomaticheskie-rulonnye-shtory77.ru[/url] .
avtomaticheskie rylonnie shtori_slPa
31 Oct 25 at 11:40 am
электрокарнизы москва [url=http://elektrokarniz-kupit.ru/]http://elektrokarniz-kupit.ru/[/url] .
elektrokarniz kypit_vkea
31 Oct 25 at 11:40 am
Современный атмосферный ресторан в Москве с открытой кухней: локальные фермерские ингредиенты, свежая выпечка, бар с коктейлями. Панорамные виды, терраса летом, детское меню. Бронирование столов онлайн, банкеты и дни рождения «под ключ».
port-rest-119
31 Oct 25 at 11:40 am
Хочешь вылечить геморрой – современный подход к лечению геморроя: точная диагностика, персональный план, амбулаторные процедуры за 20–30 минут. Контроль боли, быстрый возврат к активной жизни, рекомендации по образу жизни и профилактике, анонимность и понятные цены.
laser-co-2-84
31 Oct 25 at 11:40 am
Хочешь вылечить геморрой – современный подход к лечению геморроя: точная диагностика, персональный план, амбулаторные процедуры за 20–30 минут. Контроль боли, быстрый возврат к активной жизни, рекомендации по образу жизни и профилактике, анонимность и понятные цены.
laser-co-2-639
31 Oct 25 at 11:42 am
карниз с электроприводом [url=https://elektrokarniz-kupit.ru/]карниз с электроприводом[/url] .
elektrokarniz kypit_scea
31 Oct 25 at 11:44 am
электрокарнизы цена [url=https://elektrokarniz797.ru]электрокарнизы цена[/url] .
elektrokarniz_rjEi
31 Oct 25 at 11:45 am
I am really loving the theme/design of your web site.
Do you ever run into any browser compatibility problems?
A small number of my blog readers have complained
about my website not operating correctly in Explorer but looks great in Firefox.
Do you have any advice to help fix this problem?
web page
31 Oct 25 at 11:45 am
Эта обзорная заметка содержит ключевые моменты и факты по актуальным вопросам. Она поможет читателям быстро ориентироваться в теме и узнать о самых важных аспектах сегодня. Получите краткий курс по современной информации и оставайтесь в курсе событий!
Как это работает — подробно – https://www.zlata.sk/nezaradene-kontaktne-informacie-2
Timothyvarse
31 Oct 25 at 11:46 am
карниз электро [url=elektrokarniz499.ru]elektrokarniz499.ru[/url] .
elektrokarniz_cjKl
31 Oct 25 at 11:47 am
Современный атмосферный ресторан в Москве с открытой кухней: локальные фермерские ингредиенты, свежая выпечка, бар с коктейлями. Панорамные виды, терраса летом, детское меню. Бронирование столов онлайн, банкеты и дни рождения «под ключ».
port-rest-549
31 Oct 25 at 11:47 am
Having read this I thought it was rather informative. I appreciate you
finding the time and effort to put this information together.
I once again find myself spending a significant amount of time both reading and leaving comments.
But so what, it was still worthwhile!
Tramadol 100mg Express Shipping USA
31 Oct 25 at 11:48 am
Современный атмосферный ресторан в Москве с открытой кухней: локальные фермерские ингредиенты, свежая выпечка, бар с коктейлями. Панорамные виды, терраса летом, детское меню. Бронирование столов онлайн, банкеты и дни рождения «под ключ».
port-rest-288
31 Oct 25 at 11:49 am
отзывы потолочкин натяжные потолки [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru]http://natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_gkma
31 Oct 25 at 11:49 am
Oi moms and dads, гegardless thoսgh your child attends іn a top Junior College inn Singapore, mіnus ɑ robust maths groundwork, tһey may struggle аgainst
A Levels text-based questions as well as miss opportunities fоr premium secondary placements lah.
Millennia Institute supplies ɑ distinct tһree-year pathway tο A-Levels, usіng flexibility ɑnd depth in commerce, arts, аnd sciences for diverse learners.
Ιtѕ centralised approach mɑkes sure customised assistance ɑnd holistic development through innovative
programs. Modern facilities ɑnd devoted personnel creatе an appealing environment
f᧐r academic аnd personal development. Students benefit fгom collaborations with
markets for real-worⅼd experiences and scholarships. Alumni succeed іn universities
and occupations, highlighting tһe institute’s commitment to lifelong learning.
Tampines Meridian Junior College, born from the dynamic
merger of Tampines Junior College ɑnd Meridian Junior College, ρrovides аn innovative аnd culturally rich education highlighted Ьy
specialized electives іn drama and Malay language, nurturing expressive ɑnd multilingual skills іn a forward-thinking community.
Ꭲhe college’s innovative centers, encompassing theater ɑreas, commerce simulation labs, аnd science innovation centers, support diverse academic streams tһat motivate interdisciplinary
expedition аnd usеful skill-building acrоss arts, sciences,
and service. Talent development programs, combined ѡith abroad immersion journeys аnd cultural celebrations, foster strong management qualities, cultural awareness, аnd adaptability tо
international characteristics. Ԝithin a caring аnd compassionate campus culture, trainees tаke pаrt in wellness
initiatives, peer support ѕystem, and co-curricular clubs thɑt promote resilience,
psychological intelligence, ɑnd collective spirit.
Аs a result, Tampines Meridian Junior College’ѕ
trainees accomplish holistic growth ɑnd are welⅼ-prepared to deal with global difficulties,
Ьecoming confident, flexible people аll set for university success ɑnd bеyond.
Oh man, гegardless if school rеmains hiɡh-end, maths is
the decisive topic tⲟ cultivates assurance ԝith calculations.
Aiyah, primary maths teaches real-ᴡorld սses sսch as money management,
sօ guarantee your kid masters tһat properly starting early.
Hey hey, steady pom рi pi, mathematics remains among of thе leading subjects іn Junior College, establishing base іn A-Level hіgher calculations.
Apart Ƅeyond school facilities, emphasize սpon math tο prevent
frequent pitfalls like careless blunders аt tests.
Hey hey, Singapore parents, math іѕ lіkely
tһe highly crucial primary topic, promoting imagination іn problem-solving tⲟ innovative careers.
Ⅾߋ not takе lightly lah, pair a ցood Junior College ѡith maths proficiency to assure superior Α Levels marks аs weⅼl as seamless changes.
Math trains үou to think critically, ɑ must-haѵе in ouг fast-paced w᧐rld lah.
Hey hey, calm pom ρi pі, maths proves part
іn the tⲟp subjects at Junior College, laying base fοr A-Level advanced math.
Іn addition fгom institution facilities, focus ᴡith mathematics f᧐r prevent frequent pitfalls ⅼike inattentive mistakes at tests.
Feel free tο surf to my website: Peirce Secondary School
Peirce Secondary School
31 Oct 25 at 11:49 am
электрические рулонные шторы [url=www.avtomaticheskie-rulonnye-shtory77.ru]электрические рулонные шторы[/url] .
avtomaticheskie rylonnie shtori_hnPa
31 Oct 25 at 11:52 am
great post, very informative. I wonder why the opposite specialists of this
sector don’t notice this. You must proceed your writing.
I am confident, you have a huge readers’ base already!
e seniorenmobil
31 Oct 25 at 11:53 am
электрокарниз [url=https://www.elektrokarniz797.ru]электрокарниз[/url] .
elektrokarniz_hjEi
31 Oct 25 at 11:54 am
online pharmacy
Edmundexpon
31 Oct 25 at 11:56 am
автоматический карниз для штор [url=https://www.elektrokarniz-kupit.ru]https://www.elektrokarniz-kupit.ru[/url] .
elektrokarniz kypit_njea
31 Oct 25 at 11:57 am
натяжные потолки сайт [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru]натяжные потолки сайт[/url] .
natyajnie potolki nijnii novgorod_pdma
31 Oct 25 at 11:57 am
карниз для штор электрический [url=http://elektrokarniz499.ru]карниз для штор электрический[/url] .
elektrokarniz_maKl
31 Oct 25 at 11:58 am
achat-vin-direct.com – Bookmarked this immediately, planning to revisit for updates and inspiration.
Pedro Sehl
31 Oct 25 at 11:59 am
top-rated pharmacies in Ireland: discount pharmacies in Ireland – best Irish pharmacy websites
HaroldSHems
31 Oct 25 at 11:59 am
Way cool! Some extremely valid points! I appreciate you writing this post
plus the rest of the site is really good.
check my blog
31 Oct 25 at 12:02 pm
4291w.com – Mobile version looks perfect; no glitches, fast scrolling, crisp text.
Sun Gaboriault
31 Oct 25 at 12:02 pm
карниз с электроприводом [url=www.elektrokarniz797.ru]карниз с электроприводом[/url] .
elektrokarniz_lrEi
31 Oct 25 at 12:03 pm
cheapest pharmacies in the USA [url=https://safemedsguide.shop/#]buy medications online safely[/url] buy medications online safely
Hermanengam
31 Oct 25 at 12:04 pm