Zend Framework 1.5.1 and my Models code
Someone asked how I get a db connection in my models using ZF1.5.1
Basically I have a ConfigDB singleton pattern that gets one db connection, then sets the default adapter so when I extend the Zend_DB_Table_Abstract class, the default connection gets carried around.
class ConfigDB {
static private $instance;
private function __construct() {
}
public static function getInstance() {
if (!ConfigDB::$instance) {
$params = array(
/* redacted */
);
ConfigDB::$instance = Zend_Db::factory('Mysqli', $params);
Zend_Db_Table_Abstract::setDefaultAdapter(ConfigDB::$instance);
}
return ConfigDB::$instance;
}
public static function selectDb($db) {
return ConfigDB::$instance->getConnection()->select_db($db);
}
}
ConfigDB::getInstance();
That grabs the connection and sets the default adapter. So in my model class I can do:
class Country extends Zend_Db_Table_Abstract {
protected $_name = 'countries';
protected $_primary = 'country_id';
function __construct($country = 1, $abbr = '')
{
parent::__construct();
}
}
That’s it
April 1st, 2008 at 3:02 pm
Hey thanks for helping me through this. Heres what I ended up with:
[ Config file: ]
[development]
db.adapter = “Mysqli”
db.params.host = “localhost”
db.params.username = “user”
db.params.password = “password”
db.params.dbname = “dbname”
[ Bootstrap: ]
# config
$config = new Zend_Config_Ini(APP_PATH.’/config/settings.ini’, ‘development’);
# database
$db = Zend_Db::factory($config->db);
Zend_Db_Table::setDefaultAdapter($db);
[ Then the model: ]
class SomeModelName extends Zend_Db_Table
{
protected $_name = ‘db_table_name’;
public function findByPermalink($permalink = ”)
{
return $this->fetchRow($this->select()->where(’permalink = ?’, $permalink));
}
}
And viola! thats it. Minimal amount of code and all the DB functionality I need