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!
togetherwerise – The site looks clean and promising, but I couldn’t find detailed team bios or track record.
Delpha Alier
31 Oct 25 at 4:18 am
billig Viagra Norge: billig Viagra Norge – generisk Viagra 50mg / 100mg
RichardImmon
31 Oct 25 at 4:19 am
Без обновлений программ жить опасно кракен онион тор кракен onion сайт kra ссылка kraken сайт
RichardPep
31 Oct 25 at 4:19 am
автоматические карнизы [url=https://elektrokarniz499.ru/]автоматические карнизы[/url] .
elektrokarniz_ryKl
31 Oct 25 at 4:21 am
купить диплом в муроме [url=www.rudik-diplom3.ru/]купить диплом в муроме[/url] .
Diplomi_noei
31 Oct 25 at 4:21 am
Very nice post. I just stumbled upon your weblog and wanted to say that I have really enjoyed browsing your
blog posts. In any case I’ll be subscribing to your
feed and I hope you write again soon!
Also visit my webpage led screen visuals
led screen visuals
31 Oct 25 at 4:21 am
электрокарнизы купить в москве [url=https://elektrokarniz797.ru]электрокарнизы купить в москве[/url] .
elektrokarniz_sfEi
31 Oct 25 at 4:22 am
Spot on with this write-up, I absolutely believe that this web site needs a lot more attention. I’ll
probably be back again to see more, thanks for the information!
fire damage restoration Franklin Park IL
31 Oct 25 at 4:22 am
купить диплом в калининграде [url=https://rudik-diplom8.ru/]купить диплом в калининграде[/url] .
Diplomi_yiMt
31 Oct 25 at 4:22 am
рулонные жалюзи москва [url=www.rulonnye-shtory-s-elektroprivodom7.ru/]рулонные жалюзи москва[/url] .
rylonnie shtori s elektroprivodom_nxMl
31 Oct 25 at 4:22 am
кракен маркетплейс
kraken сайт
JamesDaync
31 Oct 25 at 4:22 am
Heya i am for the primary time here. I found this board and I find It really helpful & it helped
me out a lot. I am hoping to give something back and
help others like you aided me.
kra36 cc
31 Oct 25 at 4:24 am
рулонные шторы с электроприводом цена [url=www.rulonnye-shtory-s-elektroprivodom7.ru]рулонные шторы с электроприводом цена[/url] .
rylonnie shtori s elektroprivodom_qnMl
31 Oct 25 at 4:26 am
карниз для штор электрический [url=https://elektrokarniz797.ru/]карниз для штор электрический[/url] .
elektrokarniz_vlEi
31 Oct 25 at 4:27 am
рулонные шторы жалюзи на окна [url=http://www.rulonnye-shtory-s-elektroprivodom7.ru]http://www.rulonnye-shtory-s-elektroprivodom7.ru[/url] .
rylonnie shtori s elektroprivodom_jfMl
31 Oct 25 at 4:27 am
электронный карниз для штор [url=http://elektrokarniz499.ru]электронный карниз для штор[/url] .
elektrokarniz_vjKl
31 Oct 25 at 4:28 am
купить виртуальный номер телефона навсегда
купить виртуальный номер телефона навсегда
31 Oct 25 at 4:30 am
Вызвать уничтожение моли
уничтожение блох
Wernermog
31 Oct 25 at 4:30 am
kraken СПб
kraken СПб
JamesDaync
31 Oct 25 at 4:32 am
Вызывали уничтожение тараканов в мебели ночью, приехали быстро!
санэпидемстанция цены
KennethceM
31 Oct 25 at 4:33 am
We’re a bunch of volunteers and opening a brand new scheme in our
community. Your web site provided us with helpful info to work on. You’ve done an impressive activity and our whole group might
be grateful to you.
ساخت سایت آرایشگاه با امکان نوبت دهی
31 Oct 25 at 4:34 am
Запой представляет собой состояние, при котором организм находится под постоянным воздействием этанола. Это вызывает интоксикацию, нарушение обменных процессов и дестабилизацию психики. При обращении за помощью врач-нарколог оценивает состояние пациента и подбирает индивидуальную схему терапии, чтобы безопасно вывести человека из запоя и предотвратить развитие синдрома отмены. Вмешательство проводится как в стационаре, так и на дому, в зависимости от состояния пациента.
Разобраться лучше – https://vyvod-iz-zapoya-v-krasnoyarske17.ru/czentr-kodirovaniya-vyvod-iz-zapoya-krasnoyarsk/
Ronaldseict
31 Oct 25 at 4:34 am
электро рулонные шторы [url=www.rulonnye-shtory-s-elektroprivodom7.ru/]www.rulonnye-shtory-s-elektroprivodom7.ru/[/url] .
rylonnie shtori s elektroprivodom_xvMl
31 Oct 25 at 4:35 am
ИТ формирует мышление нового поколения kraken зеркало кракен онион тор кракен онион зеркало кракен даркнет маркет
RichardPep
31 Oct 25 at 4:35 am
https://t.me/ud_Gama/45
MichaelPione
31 Oct 25 at 4:35 am
диплом медсестры с аккредитацией купить [url=http://www.frei-diplom13.ru]диплом медсестры с аккредитацией купить[/url] .
Diplomi_pykt
31 Oct 25 at 4:36 am
Результат после травля тараканов потрясающий!
обработка участков от клещей
KennethceM
31 Oct 25 at 4:37 am
Howdy! I know this is kinda off topic but I was wondering if you
knew where I could find a captcha plugin for my comment form?
I’m using the same blog platform as yours and I’m having trouble finding one?
Thanks a lot!
Your Quality Pressure Washing Houston
31 Oct 25 at 4:37 am
натяжные потолки город нижний новгород [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru/]https://natyazhnye-potolki-nizhniy-novgorod-1.ru/[/url] .
natyajnie potolki nijnii novgorod_ggma
31 Oct 25 at 4:38 am
https://t.me/ud_JoyCasino/47
MichaelPione
31 Oct 25 at 4:38 am
Kamagra Wirkung und Nebenwirkungen: Potenzmittel ohne ärztliches Rezept – Kamagra Oral Jelly Deutschland
ThomasCep
31 Oct 25 at 4:40 am
рулонные шторы на кухню купить [url=https://rulonnye-shtory-s-elektroprivodom7.ru/]рулонные шторы на кухню купить[/url] .
rylonnie shtori s elektroprivodom_xoMl
31 Oct 25 at 4:41 am
куплю диплом младшей медсестры [url=www.frei-diplom13.ru/]www.frei-diplom13.ru/[/url] .
Diplomi_vvkt
31 Oct 25 at 4:43 am
[url=https://umnye-shtory-s-elektroprivodom.ru/]управляемые шторы прокарниз[/url] – управляемые шторы, которые позволят вам легко контролировать свет и атмосферу в вашем доме.
Раздел 3: Установка управляемых штор
умные шторы
31 Oct 25 at 4:44 am
Борьба с профессиональная дезинфекция удалась, фирма молодцы.
обработка квартиры от клопов
KennethceM
31 Oct 25 at 4:44 am
ehe258.com – Color palette felt calming, nothing distracting, just focused, thoughtful design.
Juliann Evelyn
31 Oct 25 at 4:44 am
кракен обмен
kraken зеркало
JamesDaync
31 Oct 25 at 4:44 am
Eh eh, steady pom pi pi, maths iѕ ߋne of the top subjects ɑt Junior College, building base fоr A-Level
advanced math.
In adԁition from school facilities, emphasize оn maths to st᧐p typical pitfalls ѕuch as inattentive blunders at
assessments.
Dunman Higһ School Junior College stands оut in multilingual
education, blending Eastern аnd Western point ߋf views to cuultivate
culturally astute аnd ingenious thinkers. Thе integrated
program ߋffers seamless progression ԝith enriched curricula іn STEM and liberal arts, supported ƅy sophisticated centers
like reseɑrch laboratories. Students flourish іn a harmonious environment tһat emphasizes creativity, leadership,
ɑnd community involvement tһrough diverse activities.
Global immersion programs boost cross-cultural understanding ɑnd prepare trainees fߋr international
success. Graduates regularly accomplish leading outcomes,
reflecting tһе school’s dedication tо scholastic rigor ɑnd personal quality.
Victoria Junior College sparks imagination and fosters visionary management, empowering
students tօ produce favorable change tһrough a curriculum tһat stimulates passions and
encourages vibrant thinking іn a stunning coastal campus setting.
The school’s detailed centers, including humanities discussion spaces, science гesearch study suites,
aand arts efficiency locations, assistance enriched programs іn arts, liberal arts, ɑnd sciences that promote interdisciplinary insights ɑnd academic proficiency.
Strategic alliances ѡith secondary schools thrⲟugh incorporated programs guarantee а smooth educational
journey, uѕing accelerated learning paths аnd specialized electives tһat
accommodate individual strengths аnd intеrests. Service-learning
initiatives ɑnd international outreach tasks,
ѕuch ɑs worldwide volunteer explorations аnd leadership forums, build caring personalities, strength, аnd a commitment to community welfare.
Graduates lead ᴡith undeviating conviction ɑnd attain extraordinary success
іn universities and careers, embodying Victoria
Junior College’ѕ tradition оf nurturing imaginative,
principled, ɑnd transformative people.
Listen սp, composed pom рi рі, mathematics іѕ among
of tһe top topics at Junior College, laying base fоr A-Level advanced math.
Ιn adԁition to institution amenities, concentrate ᧐n maths in ordeг
to stop frequent mistakes lіke inattentive errors ɗuring assessments.
Οһ dear, lacking solid math ԁuring Junior College, еven prestigious institution kids mаү stumble ɑt hіgh school calculations, ѕо cultivate it noᴡ leh.
Mums ɑnd Dads, competitive approach engaged lah,robust primary math leads
іn superior scientific understanding аnd engineering aspirations.
Wow, mathematics serves ɑs the base block іn primary schooling, helping children іn dimensional reasoning tⲟ building routes.
Ɗⲟn’t underestimate Ꭺ-levels; tһey’re the foundation ᧐f youг academic journey in Singapore.
Alas, primary mathematics educates everyday implementations ѕuch as budgeting, so guarantee your child ցets
it properly starting young.
my blog post: physics and maths tutor chemistry edexcel as level
physics and maths tutor chemistry edexcel as level
31 Oct 25 at 4:44 am
электрические рулонные шторы купить москва [url=https://rulonnye-shtory-s-elektroprivodom7.ru/]rulonnye-shtory-s-elektroprivodom7.ru[/url] .
rylonnie shtori s elektroprivodom_pxMl
31 Oct 25 at 4:45 am
Thank you for some other informative web site.
The place else could I am getting that kind of info written in such an ideal manner?
I’ve a venture that I’m simply now working on, and I have been at the glance out for such info.
построить монолитный дом в подмосковье
31 Oct 25 at 4:45 am
kraken tor
kraken darknet
JamesDaync
31 Oct 25 at 4:46 am
Вызов обработка от клопов стоимость на выходные возможен?
уничтожение тараканов в кафе
KennethceM
31 Oct 25 at 4:47 am
электрокарниз москва [url=https://elektrokarniz797.ru/]https://elektrokarniz797.ru/[/url] .
elektrokarniz_ceEi
31 Oct 25 at 4:47 am
Kamagra online kaufen: Kamagra Wirkung und Nebenwirkungen – Kamagra online kaufen
ThomasCep
31 Oct 25 at 4:47 am
карнизы для штор с электроприводом [url=www.elektrokarniz499.ru/]карнизы для штор с электроприводом[/url] .
elektrokarniz_tlKl
31 Oct 25 at 4:49 am
автоматические рулонные шторы [url=https://rulonnye-shtory-s-elektroprivodom7.ru/]автоматические рулонные шторы[/url] .
rylonnie shtori s elektroprivodom_smMl
31 Oct 25 at 4:50 am
Интернет изменил мышление человека kraken onion зеркала kraken онион kraken онион тор кракен онион
RichardPep
31 Oct 25 at 4:51 am
https://t.me/ud_Kent/64
MichaelPione
31 Oct 25 at 4:52 am
kraken 2025
кракен клиент
JamesDaync
31 Oct 25 at 4:52 am
натяж потолки [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru/]натяж потолки[/url] .
natyajnie potolki nijnii novgorod_wsma
31 Oct 25 at 4:53 am