Zend Db连接和配置

时间:2011-05-13 21:47:34

标签: database zend-framework pdo adapter

我正在开发一个zend应用程序。我有“config.ini”:

resources.db.adapter = "PDO_MYSQL"
resources.db.isDefaultAdapter = true
resources.db.params.host = "localhost"
resources.db.params.username = "root"
resources.db.params.password = "root"
resources.db.params.dbname = "test"

要与我的Db建立连接并查询它我还应该设置什么?

由于

卢卡

2 个答案:

答案 0 :(得分:7)

您需要在引导程序中初始化连接:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap {
    protected function _initDatabase(){
        // get config from config/application.ini
        $config = $this->getOptions();

        $db = Zend_Db::factory($config['resources']['db']['adapter'], $config['resources']['db']['params']);

        //set default adapter
        Zend_Db_Table::setDefaultAdapter($db);

        //save Db in registry for later use
        Zend_Registry::set("db", $db);
    }
}

您不必在注册表中保存连接。

答案 1 :(得分:2)

application/models/Data.php

中创建数据库模型文件
class Model_Data extends Zend_Db_Table_Abstract{

    protected $_name='myDatabse'; //the database name
    /**
     * Create new entry
     *     
     */
    public function create($title,$author,$authorUrl,$category){
        $row=$this->createRow();
        $row->title=$title;
        $row->author=$author;
        $row->site=$authorUrl;
        $row->category=$category;
        $row->save();
        return $this->_db->lastInsertId();
    }
}

bootstrap.php文件中声明模型,如下所示:

class Bootstrap extends Zend_Application_Bootstrap_Bootstrap
{
    protected function _initAutoload()
    {
        $autoLoader=Zend_Loader_Autoloader::getInstance();
        $resourceLoader=new Zend_Loader_Autoloader_Resource(array(
            'basePath'=>APPLICATION_PATH,
            'namespace'=>'',
            'resourceTypes'=>array(                
                'models'=>array(
                    'path'=>'models/',
                    'namespace'=>'Model_'
                ),                
            )
            ));


        $autoLoader->pushAutoloader($resourceLoader);       
    }
}

然后通过控制器操作进行查询:

class SearchController extends Zend_Controller_Action
{

    public function init()
    {
        /* Initialize action controller here */
    }

    public function indexAction()
    {        
       $dataModel=new Model_Data();
       $dataModel->create("title","author","url","category");       

    }


}