2010-05-28 66 views
3

如何获取控制器操作中的资源? 资源数据库已在application.ini中初始化。如何获取控制器操作中的资源?

class IndexController extends Zend_Controller_Action 
{ 

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

    public function indexAction() 
    { 
     // I want db resource here 
    } 
} 

回答

4

尝试,看看,如果这个工程:

$this->getFrontController()->getParam('bootstrap')->getResource('db') 
+2

所以是正确: $ DB = $这个 - > getInvokeArg( '引导') - >的getResource( 'DB'); – 2010-05-28 14:30:11

1

UPDATE:虽然这种解决方案的工作原理,它是推荐 做法。请阅读评论 @Brian M.以下。

您可以使用Zend_Registry。在初始化引导数据库连接,并将其存储在注册表中:

// set up the database handler 
// (...) 
Zend_Registry::set('dbh', $dbh); 

然后你可以从其他地方retireve它:

$dbh = Zend_Registry::get('dbh'); 
+2

我不认为像这样使用注册表是一个聪明的想法。 ZF为您提供了一种访问资源的方式,依靠全局注册表可能会产生问题。如果你想更容易地访问资源,请尝试在这里使用注入方法:http://weierophinney.net/matthew/archives/235-A-Simple-Resource-Injector-for-ZF-Action-Controllers.html – 2010-05-28 14:59:25

+0

这是一个更优雅的方法,感谢提示:) – nuqqsa 2010-05-28 15:36:27

0

在回答a similar question on Nabble,马修·威尔O'Phinney(Zend的先生框架1)建议使用这种形式:

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

因此,在这种q的上下文题目了,这将是这样的:

class IndexController extends Zend_Controller_Action 
{ 

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

    public function indexAction() 
    { 
     // db resource here 
     $db = $this->getInvokeArg('bootstrap')->getResource('db'); 
    } 
} 
相关问题