控制器中的 Zend 2 适配器工作正常,但在模型中无法正常工作


Zend 2 adapter in Controller works fine but not in Model

我是Zend 2的新手。我做了一个控制器和模型。

我收到以下错误:

致命错误:在第 25 行的 C:''websites''zend2''module''Pages''src''Pages''Model''PagesTable.php 中的非对象上调用成员函数 get((

我做错了什么?!?!

溶液:

控制器:

namespace Pages'Controller;
use Zend'Mvc'Controller'AbstractActionController;
use Zend'View'Model'ViewModel;
class IndexController extends AbstractActionController {
protected $pagesTable;
function indexAction() {
    return new ViewModel(array(
        'pages' => $this->getPagesTable()->fetchAll(),
    ));
}
public function getPagesTable()
{
    if (!$this->pagesTable) {
        $sm = $this->getServiceLocator();
        $this->pagesTable = $sm->get('Pages'Model'PagesTable');
    }
    return $this->pagesTable;
}
}

型:

namespace Pages'Model;
use Zend'Db'TableGateway'TableGateway;
class PagesTable  {
protected $tableGateway;
public function __construct(TableGateway $tableGateway)
{
    $this->tableGateway = $tableGateway;
}
public function fetchAll()
{
    $resultSet = $this->tableGateway->select();
    return $resultSet;
}
}

加模块.php

public function getServiceConfig()
{
    return array(
        'factories' => array(
            'Pages'Model'PagesTable' =>  function($sm) {
                $tableGateway = $sm->get('PagesTableGateway');
                $table = new PagesTable($tableGateway);
                return $table;
            },
            'PagesTableGateway' => function ($sm) {
                $dbAdapter = $sm->get('Zend'Db'Adapter'Adapter');
                $resultSetPrototype = new ResultSet();
                return new TableGateway('pages', $dbAdapter, null, $resultSetPrototype);
            },
        ),
    );
}

这是因为 functin getServiceLocator() 是一个在AbstractActionController扩展的AbstractController中实现的函数,然后您再次从中扩展控制器。

ServiceLocator本身由服务管理器注入。

你想要做事的方式是这样的:

// SomeController#someAction
$table = $this->getServiceLocator()->get('MyTableGateway');
$pages = $table->pages();

一个非常干净和苗条的控制器。然后,设置服务MyTableGateway

// Module#getServiceConfig
'factories' => array(
    'MyTableGateway' => function($serviceLocator) {
        $dbAdapter = $serviceLocator()->get('Zend'Db'Adapter'Adapter');
        $gateway   = new MyTableGateway($dbAdapter);
        return $gateway;
    }
)

此工厂将调用您的类MyTableGateway,然后使用构造函数注入来注入依赖项,在本例中为 Zend'Db'Adapter'Adapter

剩下要做的就是

修改MyTableGateway__construct()以允许 DbAdapter 参数,您就完成了。这样,您就可以访问网关内的 DbAdapter,并且代码都是干净的

,并且;)