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!
http://sobaka.lv/index.php?page=Objavlenija/Otdajut
Nathanhip
16 Oct 25 at 12:17 pm
купить диплом в брянске [url=https://rudik-diplom3.ru/]купить диплом в брянске[/url] .
Diplomi_xqei
16 Oct 25 at 12:18 pm
Parents, secondary school maath tuition is vital inn Singapore’ѕ system to motivate your
child ɑnd tսrn math intо an enjoyable subject.
Can already, Singapore students dominate tһe global math scene, steady pom рі pi!
Parents, empower understanding tһrough Singapore math tuition’ѕ analysis.
Secondary math tuition builds prowess. Enlist іn secondary 1 math
tuition f᧐r conversions.
Secondary 2 math tuition commemorates variety tһrough inclusive examples.
Secondary 2 math tuition represents ԁifferent
cultures. Equitable secondary 2 math tuition promotes
belonging. Secondary 2 math tuition unites students.
Carrying օut remarkably in secondary 3 math exams іs key,
wіtһ Ο-Levels approaching. Ηigh achievement mаkes іt рossible for innovative promotions.
Success fosters passionate development.
Ƭhe critical function of secondary 4 exams іn Sinngapore motivates aspiration. Secondary 4 math tuition shares alumni legacies.
Τhese stories encourage Օ-Level pursuits. Secondary 4 math tuition perpetuates excellence.
Mathematics extends Ьeyond exams; it’s a cornerstone skill in the AI surge,powering archaeological data
analysis.
Love tһe subject of math and apply іts principles іn daily real-life t᧐
excel іn mathematics.
To prepare robustly, practicing ρast math exam papers fгom diverse secondary schools іn Singapore sharpens calculation precision.
Singapore learners elevate math exam гesults ᴡith online tuition e-learning
featuring augmented reality f᧐r 3D modeling.
Wah lao lor, chill ɑһ, kids adapt to secondary school
fɑst, support withoսt tension.
OMT’s emphasis оn error analysis transforms blunders іnto learning experiences, aiding trainees love math’ѕ forgiving nature ɑnd
purpose high in examinations.
Join oսr small-group on-site classes іn Singapore fоr personalized guidance іn a nurturing environment tһat
builds strong fundamental mathematics skills.
Ӏn Singapore’s extensive education ѕystem, whеre
mathematics is compulsory and takes іn around 1600 hours οf curriculum time
in primary and secondary schools, math tuition Ьecomes
important to assist students develop ɑ strong structure for
ⅼong-lasting success.
Improving primary education ԝith math tuition prepares students fօr PSLE by cultivating ɑ growth
mindset tⲟwards difficult topics ⅼike proportion and transformations.
Customized math tuition іn senior hіgh school addresses
private finding οut gaps in subjects like
calculus аnd data, stopping tһem from impeding Ο Level success.
Ultimately, junior college math tuition іs vital to protecting toρ
Α Level гesults, oрening uρ doors to respected scholarships ɑnd college chances.
OMT’s special curriculum, crafted tߋ sustain the MOE syllabus, іncludes individualized components tһat adjust to private knowing designs f᧐r more reliable math proficiency.
Tape-recorded webinars ᥙse deep dives lah, outfitting yоu with innovative abilities foг exceptional math marks.
Ԝith minimаl class tіme in colleges, math tuition expands
discovering һours, vital fߋr mastering thе extensive
Singapore math curriculum.
Ꭺlso visit my webpage; primary math tuition singapore
primary math tuition singapore
16 Oct 25 at 12:18 pm
https://t.me/Online_1_xbet/2963
CharlesCic
16 Oct 25 at 12:19 pm
купить жд диплом техникума [url=www.educ-ua7.ru/]www.educ-ua7.ru/[/url] .
Diplomi_gsea
16 Oct 25 at 12:19 pm
TadaLife Pharmacy [url=https://tadalifepharmacy.com/#]trusted online pharmacy for ED meds[/url] discreet ED pills delivery in the US
CareyMag
16 Oct 25 at 12:19 pm
https://t.me/Online_1_xbet/3359
CharlesCic
16 Oct 25 at 12:19 pm
купить диплом провизора [url=https://www.rudik-diplom11.ru]купить диплом провизора[/url] .
Diplomi_nqMi
16 Oct 25 at 12:20 pm
https://t.me/Online_1_xbet/2868
CharlesCic
16 Oct 25 at 12:23 pm
https://t.me/Online_1_xbet/3525
CharlesCic
16 Oct 25 at 12:23 pm
купить диплом в туймазы [url=www.rudik-diplom4.ru/]купить диплом в туймазы[/url] .
Diplomi_kvOr
16 Oct 25 at 12:23 pm
mostbet apk download
войти в мостбет
16 Oct 25 at 12:24 pm
Nice blog here! Also your site rather a lot up fast! What host are you the use of?
Can I get your associate link in your host?
I want my site loaded up as fast as yours lol
Axiventro Erfahrungen
16 Oct 25 at 12:25 pm
купить диплом украина с занесением в реестр [url=www.frei-diplom4.ru]www.frei-diplom4.ru[/url] .
Diplomi_iqOl
16 Oct 25 at 12:25 pm
купить диплом москва с занесением в реестр [url=frei-diplom5.ru]купить диплом москва с занесением в реестр[/url] .
Diplomi_qwPa
16 Oct 25 at 12:27 pm
mostbet uz [url=https://mostbet4185.ru]https://mostbet4185.ru[/url]
mostbet_uz_vver
16 Oct 25 at 12:27 pm
купить диплом для иностранцев [url=rudik-diplom5.ru]купить диплом для иностранцев[/url] .
Diplomi_numa
16 Oct 25 at 12:28 pm
купить официальный диплом [url=https://educ-ua7.ru]https://educ-ua7.ru[/url] .
Diplomi_jtea
16 Oct 25 at 12:29 pm
After checking out a few of the blog articles on your
website, I really like your way of writing a blog. I bookmarked it to
my bookmark webpage list and will be checking back in the near future.
Take a look at my website too and let me know how you feel.
U888
16 Oct 25 at 12:29 pm
купить диплом в екатеринбурге [url=rudik-diplom4.ru]купить диплом в екатеринбурге[/url] .
Diplomi_gyOr
16 Oct 25 at 12:30 pm
Woah! I’m really enjoying the template/theme of this website.
It’s simple, yet effective. A lot of times it’s hard to get
that “perfect balance” between usability and visual appearance.
I must say you have done a great job with this. In addition, the blog loads extremely fast
for me on Chrome. Superb Blog!
togel 4d
16 Oct 25 at 12:31 pm
img width: 750px; iframe.movie width: 750px; height: 450px;
Sushiswap sushi swap Exchange Features and Overview Analysis Guide
Sushiswap Exchange Features and Overview Analysis
To maximize your trading experience, leveraging intuitive
liquidity pools and yield farming options is essential.
Understand how to effectively utilize the DEX to enhance your asset management strategy,
ensuring optimal returns. Familiarize yourself with the tokenomics and governance model,
which allows you to participate in decision-making processes and earn rewards through staking.
Explore the unique characteristics of customizing trading
pairs and accessing robust charting tools. The ability to analyze market trends in real time
can significantly impact your trading decisions. Analyze historical
data to identify potential price movements, providing an edge in competitive environments.
Utilizing cross-platform integrations, such as wallets and analytics
tools, can further streamline your trading activities. Assess your choices
carefully, as this will directly influence your efficiency and profit margins.
Engaging with community-driven improvements can also
foster a sense of involvement, enhancing your overall experience within the platform.
Understanding Sushiswap’s Unique Liquidity Pool Mechanics
Maximize returns by utilizing the dynamic liquidity provisioning system.
Users can provide liquidity in pairs, receiving rewards through
trading fees. The percentage of fees earned correlates with the amount of liquidity
supplied to the pool.
Engage with concentrated liquidity, a mechanism that allows liquidity providers to concentrate their assets in specific price ranges.
This approach enhances capital efficiency, as funds are utilized more effectively within chosen price bands.
Participate in the incentive structures like yield
farming, where additional tokens are earned for supplying
liquidity. By staking LP tokens, users can receive governance tokens that grant voting power on protocol decisions.
Utilize the concept of impermanent loss awareness.
Calculate potential losses in volatile markets when providing liquidity.
Regularly assess the price movements of assets in the pool
to make informed decisions about holding or withdrawing liquidity.
Explore multiple strategies for different market conditions.
Consider setting up automated strategies utilizing bots that can react to price changes or market dynamics, ensuring optimal
earnings without constant manual monitoring.
Stay informed about community proposals and updates.
Engaging with governance enables active participation in the evolution of the platform, influencing future developments and functionalities.
Utilize the analytics tools available to monitor pool performance and individual returns.
Examine metrics such as total value locked, liquidity depth, and historical trading volumes for informed decision-making.
Integrating DeFi Tools for Enhanced Trading
Utilize analytics platforms to gain insights
into price movement and liquidity trends. Tools like Dune Analytics or Nansen provide crucial
data that can guide your trading strategy, including historical price charts and on-chain transaction metrics.
Incorporate automated trading bots to execute trades based on pre-defined criteria.
Solutions such as Zignaly or 3Commas can help optimize
entry and exit points, ensuring trades align with market fluctuations without the need for constant monitoring.
Implement yield farming and staking to maximize assets.
Engaging with protocols offering high yield on liquidity provision can enhance returns and counterbalance transaction costs incurred during trading activities.
Utilize cross-chain bridges to access diverse liquidity pools across different blockchains.
This interoperability allows for more flexible trading options and can help mitigate slippage in volatile markets.
Engage in community forums and social media channels
to stay updated on sentiment and potential market movements.
Platforms like Discord or Telegram often host discussions that can provide actionable insights from experienced traders.
Leverage wallet integrations with decentralized applications for seamless transactions.
Using a wallet like MetaMask can streamline interactions
and ensure quicker access to liquidity pools,
improving overall trading experience.
Lastly, use risk management tools to limit exposure.
Setting stop-loss orders or employing portfolio diversification strategies can protect against market downturns, allowing for
more sustained trading presence. This structured approach aids in navigating market volatility
effectively.
sushi swap Exchange
16 Oct 25 at 12:31 pm
The $MTAUR token presale is a steal at current rates. Audited contracts and vesting smart. Minotaur adventures await.
minotaurus presale
WilliamPargy
16 Oct 25 at 12:31 pm
mostbet. com [url=https://www.mostbet4185.ru]mostbet. com[/url]
mostbet_uz_dzer
16 Oct 25 at 12:34 pm
Excited for Minotaurus presale’s deals. $MTAUR’s zones special. Engagement high.
minotaurus coin
WilliamPargy
16 Oct 25 at 12:35 pm
купить диплом в ишиме [url=https://www.rudik-diplom1.ru]https://www.rudik-diplom1.ru[/url] .
Diplomi_ller
16 Oct 25 at 12:35 pm
диплом юридического колледжа купить [url=https://www.frei-diplom10.ru]https://www.frei-diplom10.ru[/url] .
Diplomi_tqEa
16 Oct 25 at 12:36 pm
Hi, i feel that i noticed you visited my website so i
came to return the prefer?.I’m trying to find things to enhance
my site!I assume its ok to use a few of your ideas!!
Éclat Gainetra Legit Or Not
16 Oct 25 at 12:36 pm
купить диплом с реестром спб [url=https://frei-diplom4.ru/]купить диплом с реестром спб[/url] .
Diplomi_ngOl
16 Oct 25 at 12:37 pm
диплом высшего образования проведенный купить [url=https://frei-diplom5.ru/]диплом высшего образования проведенный купить[/url] .
Diplomi_gsPa
16 Oct 25 at 12:38 pm
купить диплом в тюмени [url=https://rudik-diplom5.ru]купить диплом в тюмени[/url] .
Diplomi_vpma
16 Oct 25 at 12:38 pm
https://t.me/Online_1_xbet/3449
CharlesCic
16 Oct 25 at 12:39 pm
потолки натяжные в нижнем новгороде [url=http://natyazhnye-potolki-nizhniy-novgorod-1.ru]http://natyazhnye-potolki-nizhniy-novgorod-1.ru[/url] .
natyajnie potolki nijnii novgorod_qjma
16 Oct 25 at 12:39 pm
https://t.me/Online_1_xbet/2648
CharlesCic
16 Oct 25 at 12:40 pm
натяжные потолки ру [url=http://stretch-ceilings-nizhniy-novgorod-1.ru/]натяжные потолки ру[/url] .
natyajnie potolki nijnii novgorod_lnOn
16 Oct 25 at 12:40 pm
купить диплом в благовещенске [url=https://rudik-diplom11.ru/]купить диплом в благовещенске[/url] .
Diplomi_xgMi
16 Oct 25 at 12:41 pm
Inspiring quest there. What happened after? Good luck!
singapore 82200219
16 Oct 25 at 12:42 pm
натяжной потолок нижний новгород [url=http://www.stretch-ceilings-nizhniy-novgorod-1.ru]натяжной потолок нижний новгород[/url] .
natyajnie potolki nijnii novgorod_kcOn
16 Oct 25 at 12:43 pm
https://t.me/Online_1_xbet/2716
CharlesCic
16 Oct 25 at 12:43 pm
https://t.me/Online_1_xbet/1946
CharlesCic
16 Oct 25 at 12:43 pm
купить легально диплом [url=frei-diplom5.ru]купить легально диплом[/url] .
Diplomi_ltPa
16 Oct 25 at 12:44 pm
мостбет промокод 2025 уз [url=http://mostbet4182.ru/]http://mostbet4182.ru/[/url]
mostbet_uz_oqkt
16 Oct 25 at 12:47 pm
ایمپلنت دندان – لمینت دندان – ترمیم
و پالش دندان
خوش سیما دیباج
16 Oct 25 at 12:51 pm
купить диплом в троицке [url=www.rudik-diplom3.ru]www.rudik-diplom3.ru[/url] .
Diplomi_pxei
16 Oct 25 at 12:52 pm
StopKor — портал журналистских расследований о коррупции, бизнесе и обществе: авторские материалы, досье и аналитика, обновления по резонансным делам. Проекты выходят на украинском и русском языках, с источниками, датами и контекстом. Удобная навигация по рубрикам «Розслідування», «Економіка», «Злочинність» ускоряет поиск. Изучите публикации на https://stopkor.info/ — следите за новыми выпусками и архивом материалов. Портал создан для тех, кто ценит факты, доказательность и прозрачность.
xikebhApade
16 Oct 25 at 12:53 pm
купить диплом судоводителя [url=https://rudik-diplom8.ru]купить диплом судоводителя[/url] .
Diplomi_iuMt
16 Oct 25 at 12:53 pm
как легально купить диплом о [url=https://frei-diplom6.ru]как легально купить диплом о[/url] .
Diplomi_slOl
16 Oct 25 at 12:54 pm
buy clomid [url=http://zencaremeds.com/#]trusted online pharmacy USA[/url] ZenCare Meds
CareyMag
16 Oct 25 at 12:55 pm
купить диплом в димитровграде [url=rudik-diplom11.ru]купить диплом в димитровграде[/url] .
Diplomi_vdMi
16 Oct 25 at 12:55 pm
натяжной потолок дешево [url=https://natyazhnye-potolki-nizhniy-novgorod-1.ru/]натяжной потолок дешево[/url] .
natyajnie potolki nijnii novgorod_uqma
16 Oct 25 at 12:55 pm