Difference between revisions of "API/Di"

From aMember Pro Documentation
Jump to: navigation, search
(Created page with "Am_Di class in aMember implements dependency injection pattern. Instead of using '''singletons'' in each class, we are using Am_Di instance that stores references to necessary ob...")
 
Line 4: Line 4:
  
 
From other parts of program, including site-custom file '''application/configs/site.php'', the same ''Am_Di'' instance is available as ''Am_Di::getInstance()''.
 
From other parts of program, including site-custom file '''application/configs/site.php'', the same ''Am_Di'' instance is available as ''Am_Di::getInstance()''.
 +
 +
=== Example 1: get config value ===
 +
<source lang="php">
 +
echo Am_Di::getInstance()->config->get('my-config-key', 'default value to return if my-config-key not set');
 +
</source>
 +
 +
=== Example 2: check if paypal plugin is enabled and if it is enabled, return reference to plugin object ===
 +
<source lang="php">
 +
if (Am_Di::getInstance()->plugins_payment->isEnabled('paypal'))
 +
    return Am_Di::getInstance()->plugins_payment->loadGet('paypal');
 +
</source>
 +
 +
=== Example 3: store value in database for 2 hours. If value access later than in 2 hours, it will be destroyed ===
 +
<source lang="php">
 +
Am_Di::getInstance()->store->set('mykey', 'Some Value', '+2 hours');
 +
echo Am_Di::getInstance()->store->get('mykey');
 +
</source>

Revision as of 07:23, 17 November 2011

Am_Di class in aMember implements dependency injection pattern. Instead of using 'singletons in each class, we are using Am_Di instance that stores references to necessary objects, and creates objects by demand.

From controllers (Am_Controller), tables (Am_Table), records (Am_Record) and plugins (Am_Plugin), module bootstraps (Bootstrap_xx), Am_Di instance is accessible with method call $this->getDi();

From other parts of program, including site-custom file 'application/configs/site.php, the same Am_Di instance is available as Am_Di::getInstance().

Example 1: get config value

echo Am_Di::getInstance()->config->get('my-config-key', 'default value to return if my-config-key not set');

Example 2: check if paypal plugin is enabled and if it is enabled, return reference to plugin object

if (Am_Di::getInstance()->plugins_payment->isEnabled('paypal'))
    return Am_Di::getInstance()->plugins_payment->loadGet('paypal');

Example 3: store value in database for 2 hours. If value access later than in 2 hours, it will be destroyed

Am_Di::getInstance()->store->set('mykey', 'Some Value', '+2 hours');
echo Am_Di::getInstance()->store->get('mykey');