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!
Ich bin beeindruckt von SpinBetter Casino, es bietet einen einzigartigen Kick. Es gibt eine unglaubliche Auswahl an Spielen, mit immersiven Live-Sessions. Die Agenten sind blitzschnell, garantiert top Hilfe. Der Ablauf ist unkompliziert, gelegentlich die Offers konnten gro?zugiger ausfallen. Global gesehen, SpinBetter Casino bietet unvergessliche Momente fur Online-Wetten-Fans ! Hinzu kommt die Navigation ist kinderleicht, was jede Session noch besser macht. Besonders toll die mobilen Apps, die den Spa? verlangern.
https://spinbettercasino.de/|
SpinMasterZ7zef
1 Nov 25 at 11:57 am
купить диплом в кунгуре [url=https://rudik-diplom9.ru/]https://rudik-diplom9.ru/[/url] .
Diplomi_biei
1 Nov 25 at 11:57 am
диплом техникума торгового купить [url=www.frei-diplom12.ru]диплом техникума торгового купить[/url] .
Diplomi_qwPt
1 Nov 25 at 11:59 am
купить диплом в краснодаре [url=www.rudik-diplom7.ru/]купить диплом в краснодаре[/url] .
Diplomi_loPl
1 Nov 25 at 12:00 pm
купить диплом врача с занесением в реестр [url=https://frei-diplom3.ru/]купить диплом врача с занесением в реестр[/url] .
Diplomi_fmKt
1 Nov 25 at 12:02 pm
What’s Happening i am new to this, I stumbled upon this I’ve discovered It positively useful and it has helped me out loads.
I am hoping to give a contribution & assist different users like its aided me.
Great job.
تاثیر یازدهم در کنکور ۱۴۰۵
1 Nov 25 at 12:03 pm
купить диплом в когалыме [url=https://rudik-diplom12.ru/]https://rudik-diplom12.ru/[/url] .
Diplomi_vqPi
1 Nov 25 at 12:03 pm
BJ39 là cổng game trực tuyến hàng đầu Việt Nam,
quy tụ hàng loạt nhà cung cấp game uy tín, đa dạng thể loại
từ slot, thể thao đến casino, mang lại trải nghiệm
giải trí đỉnh cao.
BJ39
BJ39
1 Nov 25 at 12:04 pm
Great site you have here.. It’s hard to find quality writing like yours these days.
I truly appreciate people like you! Take care!!
Visit
1 Nov 25 at 12:05 pm
где купить диплом техникума всеми [url=https://www.frei-diplom12.ru]где купить диплом техникума всеми[/url] .
Diplomi_umPt
1 Nov 25 at 12:05 pm
Oi oi, Singapore folks, maths proves ⅼikely the highly crucial primary topic, encouraging creativity
tһrough challenge-tackling foг groundbreaking careers.
Aνoid take lightly lah, combine ɑ reputable Junior College alongside math
excellence tο ensure elevated A Levels scores аnd effortless transitions.
Folks, worry ɑbout thе difference hor, mathematics groundwork
proves vital ɗuring Junior College tо grasping data, vital іn current online economy.
Tampines Meridian Junior College, from a dynamic merger,
ⲟffers ingenious education іn drama and Malay language electives.
Cutting-edge centers support diverse streams,
including commerce. Skill advancement ɑnd abroad programs foster management ɑnd cultural awareness.
A caring neighborhood encourages compassion аnd durability.
Students succeed іn holistic advancement, ɡotten ready fⲟr global obstacles.
Ѕt. Andrew’s Junior College embraces Anglican values tο promote holistic growth, cultivating principled individuals ѡith robust character qualities tһrough a mix of spiritual guidance, academic pursuit, аnd community involvement іn a warm and inclusive
environment. Тhe college’s modern features, consisting of interactive
class, sports complexes, ɑnd imaginative arts studios, һelp wіtһ excellence ɑcross acadeemic disciplines, sports programs tһat stress physical fitness аnd fair play,
and creative ventures thɑt motivate ѕelf-expression аnd innovation. Social
woгk initiatives, ѕuch as volunteer partnerships ᴡith regional organizations and outreach tasks, impart compassion, social
duty, аnd a sense of function, improving students’
educational journeys. Ꭺ diverse variety of co-curricular activities,
fгom debate societies tо musical ensembles, fosters team effort, management skills, aand personal discovery, permitting evety student t᧐ shine іn thеir selected locations.
Alumni ᧐f St. Andrew’ѕ Junior College regularly Ƅecome ethical,
resistant leaders ԝho make significаnt contributions tо society, reflecting the organization’s profound еffect ᧐n establishing wеll-rounded, valսe-driven individuals.
Вesides from establishment resources, focus ᥙpon math in order
tⲟ avoid typical pitfalls ѕuch as sloppy blunders at tests.
Folks, competitive mode оn lah, robust primary maths гesults foг superior STEM
comprehension and engineering dreams.
Αvoid tɑke lightly lah, combine a reputable Junior College рlus maths excellence in ordeг to guarantee һigh Α Levels rеsults pⅼus effortless transitions.
Listen ᥙp, Singapore folks, maths is perһaps the mօst essential primary topic, fostering creativity іn problem-solving for creative professions.
Αvoid play play lah, link a reputable Junior College
alongside math superiority tߋ assure superior А Levels scores
as weⅼl as seamless сhanges.
Math trains ʏou to think critically, a must-һave іn ouur fast-paced ѡorld lah.
Wow, maths acts ⅼike the groundwork stone օf primary schooling,
aiding kids іn dimensional analysis tο design paths.
Oh dear, without robust mathematics ԁuring Junior College, no matter tоp institution kids mɑу falter іn next-levelequations, tһus develop thɑt promptly leh.
Аlso visit my blog; physics and maths tutor a level past papers
physics and maths tutor a level past papers
1 Nov 25 at 12:05 pm
Appreciate this post. Let me try it out.
explained
1 Nov 25 at 12:06 pm
Great site, I recommend it to everyone.[url=https://rolete.md/]porti rolete[/url]
PortiRoleteNic
1 Nov 25 at 12:08 pm
top seo marketing [url=https://reiting-seo-agentstv.ru/]https://reiting-seo-agentstv.ru/[/url] .
reiting seo agentstv_rzsa
1 Nov 25 at 12:09 pm
как купить легальный диплом о среднем образовании [url=http://frei-diplom3.ru/]http://frei-diplom3.ru/[/url] .
Diplomi_tkKt
1 Nov 25 at 12:09 pm
купить диплом техникума ссср в мурманске [url=https://www.frei-diplom12.ru]купить диплом техникума ссср в мурманске[/url] .
Diplomi_oyPt
1 Nov 25 at 12:09 pm
https://t.me/s/ud_GGBet/63
MichaelPione
1 Nov 25 at 12:10 pm
купить диплом в дербенте [url=http://rudik-diplom2.ru]купить диплом в дербенте[/url] .
Diplomi_xzpi
1 Nov 25 at 12:10 pm
przeszlosc tysiace Norwegow spotkalo z nieczysta przygoda, [url=https://base.visualpublinet.com/odkryj-bonus-100-z-bez-depozytu-graj-i-wygrywaj/]https://base.visualpublinet.com/odkryj-bonus-100-z-bez-depozytu-graj-i-wygrywaj/[/url] kto kupil kupiony bilet dzieki systemu eurojackpot.
Philipadulp
1 Nov 25 at 12:12 pm
I am extremely impressed with your writing skills and also
with the layout on your blog. Is this a paid theme or did you modify it yourself?
Either way keep up the nice quality writing, it is rare to see a great blog like
this one today.
ddos attack online free
1 Nov 25 at 12:12 pm
https://t.me/s/ud_Fresh/62
MichaelPione
1 Nov 25 at 12:13 pm
диплом купить с внесением в реестр [url=frei-diplom3.ru]диплом купить с внесением в реестр[/url] .
Diplomi_sgKt
1 Nov 25 at 12:13 pm
J’ai un veritable coup de c?ur pour Sugar Casino, on y trouve une vibe envoutante. Le catalogue est un paradis pour les joueurs, avec des slots aux graphismes modernes. Avec des transactions rapides. Disponible a toute heure via chat ou email. Les transactions sont toujours securisees, quelquefois des bonus diversifies seraient un atout. En fin de compte, Sugar Casino est une plateforme qui pulse. En complement le design est moderne et attrayant, ce qui rend chaque moment plus vibrant. Particulierement cool les competitions regulieres pour plus de fun, offre des recompenses regulieres.
Trouver les dГ©tails|
Starcrafter1zef
1 Nov 25 at 12:14 pm
купить диплом в астрахани [url=www.rudik-diplom7.ru/]купить диплом в астрахани[/url] .
Diplomi_tnPl
1 Nov 25 at 12:14 pm
https://ukmedsguide.com/# trusted online pharmacy UK
Haroldovaph
1 Nov 25 at 12:15 pm
I for all time emailed this weblog post page to
all my friends, because if like to read it
then my friends will too.
Đăng ký u88
1 Nov 25 at 12:16 pm
mostbet.com казино скачать [url=mostbet12034.ru]mostbet12034.ru[/url]
mostbet_kg_ziPr
1 Nov 25 at 12:17 pm
РедМетСплав предлагает широкий ассортимент качественных изделий из редких материалов. Не важно, какие объемы вам необходимы – от мелких партий до крупных поставок, мы гарантируем своевременную реализацию вашего заказа.
Каждая единица изделия подтверждена соответствующими документами, подтверждающими их качество. Превосходное обслуживание – наш стандарт – мы на связи, чтобы разрешать ваши вопросы а также адаптировать решения под особенности вашего бизнеса.
Доверьте ваш запрос специалистам РедМетСплав и убедитесь в множестве наших преимуществ
поставляемая продукция:
Порошок висмутовый Darcet alloy Порошок висмутовый Darcet alloy – это уникальный продукт, обладающий высокой чистотой и отличными физико-химическими свойствами. Он широко используется в металлургии, химической промышленности и для создания различных сплавов. Благодаря своей низкой токсичности, данный порошок идеально подходит для использования в медицинских и фармацевтических направлениях. Если вы ищете надежный и качественный материал, не упустите возможность купить Порошок висмутовый Darcet alloy прямо сейчас. Он обеспечит вам необходимую производительность и долговечность в любых проектах.
SheilaAlemn
1 Nov 25 at 12:18 pm
Pretty section of content. I just stumbled upon your blog and in accession capital to assert that I acquire actually enjoyed account your blog posts.
Any way I’ll be subscribing to your augment and even I achievement
you access consistently quickly.
Spot +4X Viar
1 Nov 25 at 12:18 pm
мостбет андроид [url=https://mostbet12034.ru]https://mostbet12034.ru[/url]
mostbet_kg_wtPr
1 Nov 25 at 12:18 pm
Цены на выведение тараканов выросли? Обсудим.
обработка от клопов стоимость
Wernermog
1 Nov 25 at 12:19 pm
Эта информационная статья содержит полезные факты, советы и рекомендации, которые помогут вам быть в курсе последних тенденций и изменений в выбранной области. Материал составлен так, чтобы быть полезным и понятным каждому.
Неизвестные факты о… – https://startupstories.in/stories/inspirational-stories/articles/carlos-ghosn-the-rise-of-a-titan-of-automobile-industry
AnthonyAgoge
1 Nov 25 at 12:22 pm
Публикация предлагает уникальную подборку информации, которая будет интересна как специалистам, так и широкому кругу читателей. Здесь вы найдете ответы на часто задаваемые вопросы и полезные инсайты для дальнейшего применения.
Жми сюда — получишь ответ – https://www.israelbusinessclass.com/previsions-2020-la-resilience-economique-disrael-va-se-poursuivre
CharlieTop
1 Nov 25 at 12:22 pm
купить диплом медбрата [url=https://rudik-diplom2.ru]купить диплом медбрата[/url] .
Diplomi_ojpi
1 Nov 25 at 12:23 pm
affordable medication Ireland
Edmundexpon
1 Nov 25 at 12:23 pm
трансы екатеринбург
BrianMap
1 Nov 25 at 12:24 pm
Нордман – это не просто ёлка, это символ Рождества, воплощение его волшебства и уюта. Эти величественные деревья, родом из горных районов Европы, завоевали сердца многих благодаря своей пышной кроне, густой хвое и, что немаловажно, практически полному отсутствию осыпаемости.
Выбор ёлки Нордмана – это инвестиция в праздничное настроение. Её роскошный вид создает атмосферу торжественности и элегантности. Мягкие, темно-зеленые иголки приятно трогать, и они долго сохраняют свой свежий вид, не требуя постоянной уборки. Подкажите ваши критерии выбора на [url=https://obovsem.myqip.ru/?1-5-0-00000833-000-0-0-1757659560]елки новогодние[/url]
Ralphneave
1 Nov 25 at 12:25 pm
safe place to order meds UK: affordable medications UK – Uk Meds Guide
HaroldSHems
1 Nov 25 at 12:26 pm
купить диплом техникума в иркутске lr 63 [url=www.frei-diplom12.ru/]купить диплом техникума в иркутске lr 63[/url] .
Diplomi_nvPt
1 Nov 25 at 12:26 pm
https://t.me/s/ud_Gama/49
MichaelPione
1 Nov 25 at 12:27 pm
mostbet казино скачать [url=www.mostbet12033.ru]www.mostbet12033.ru[/url]
mostbet_kg_wbpa
1 Nov 25 at 12:27 pm
https://t.me/s/ud_Vulkan/63
MichaelPione
1 Nov 25 at 12:28 pm
купить диплом в коврове [url=http://www.rudik-diplom7.ru]купить диплом в коврове[/url] .
Diplomi_wbPl
1 Nov 25 at 12:29 pm
купить диплом в новомосковске [url=https://rudik-diplom2.ru/]купить диплом в новомосковске[/url] .
Diplomi_xfpi
1 Nov 25 at 12:30 pm
купить диплом медсестры [url=https://rudik-diplom12.ru]купить диплом медсестры[/url] .
Diplomi_pnPi
1 Nov 25 at 12:30 pm
Awesome blog! Is your theme custom made or did you download it from somewhere?
A design like yours with a few simple tweeks would really make my blog
jump out. Please let me know where you got your design. With thanks
manufacturing medical equipment
1 Nov 25 at 12:30 pm
легально купить диплом о [url=http://frei-diplom3.ru/]легально купить диплом о[/url] .
Diplomi_wsKt
1 Nov 25 at 12:34 pm
купить диплом в сургуте [url=http://rudik-diplom7.ru]купить диплом в сургуте[/url] .
Diplomi_myPl
1 Nov 25 at 12:35 pm
promo codes for online drugstores: trusted online pharmacy USA – trusted online pharmacy USA
HaroldSHems
1 Nov 25 at 12:36 pm
promo codes for online drugstores: online pharmacy reviews and ratings – online pharmacy
Johnnyfuede
1 Nov 25 at 12:38 pm