API/Di

From aMember Pro Documentation
Jump to: navigation, search

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().

Contents

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 accessed later than in 2 hours, it will be destroyed and null returned

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

Example 4: send custom e-mail message

$mail = Am_Di::getInstance()->mail; // create copy of Zend_Mail object, preconfigured by aMember
$mail->addTo('xxx@sample.com', 'John Doe');
$mail->setSubject('A Plugin Custom E-Mail');
$mail->setBodyText('my message text');
try {
   $mail->send();
} catch (Exception $e) {
   echo "Error sending e-mail: " . $e->getMessage() . "\n";
}