开发者

Zend: How to Access the DB directly in a model

My db details in my Zend config file are as follows:

resources.db.adapter = PDO_MYSQL
r开发者_运维百科esources.db.params.host = localhost
resources.db.params.username = root
resources.db.params.password = bar
resources.db.params.dbname = foo

These are being used to set up the default db adapter whenever I use a Zend_DB_Table class, and that's fine.

Now I am writing a model class that does not extend Zend_DB_Table or any other class, and I'm going to need access to the DB object. What's the best way to go about this? I was thinking of instantiating it in bootstrap and putting it in registry, so that it would be available elsewhere also. Is this good practice?

How can I instantiate it based on the config options without duplicating them in the code? Am I doubling up on things because it is listed as a resource? Should I just be trying to tap into the resource from within my new model class?

Thanks..!


To get it into your models, I'd simply make it a property, settable in the model's constructor, eg

class MyModel
{
    private $db;

    public function __construct(Zend_Db $db)
    {
        $this->db = $db;
    }

You can retrieve the db resource in your controllers using this

$db = $this->getInvokeArg('bootstrap')->getResource('db');

You'll also find the resource already registered in Zend_Registry as well

$db = Zend_Registry::get('db');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜