如何在Zend Framework 2中连接数据库并进行crud操作?

时间:2016-06-30 08:22:09

标签: php zend-framework zend-framework2

我安装了Zend Framework 2并创建了新模块,直到打印hello消息才能正常工作。             现在我想连接我的数据库并执行基本CRUD操作。我在xampp上运行它。

我写了

return array(
    'db' => array(
        'driver' => 'Pdo',
        'dsn' => 'mysql:dbname=zend;host=localhost',
        'driver_options' => array(
            PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\''
        ),
    ),
    'service_manager' => array(
        'factories' => array(
            'Zend\Db\Adapter\Adapter' => 'Zend\Db\Adapter\AdapterServiceFactory',
        ),
    ),
); 
位于config / autoload中的global.php中的

在我写的控制器中

return new ViewModel(array(
    'hello' => $this->getHelloTable()->fetchAll(),
));

如果我运行它Zend\ServiceManager\Exception\ServiceNotFoundException和         Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Hello\Model\HelloTable错误即将来临。

我错过了什么?

  

参考   我在推荐这个This

     

已编辑:getHelloTable

public function getHelloTable() {
    if (!$this->helloTable) {
        $sm = $this->getServiceLocator();
        $this->helloTable = $sm->get('Users\Model\HelloTable');
    }
    return $this->helloTable;
}
  

@newage

public function getServiceConfig()
 {
     return array(
         'factories' => array(
             'Hello\Model\HelloTable' =>  function($sm) {
                 $tableGateway = $sm->get('HelloTableGateway');
                 $table = new HelloTable($tableGateway);
                 return $table;
             },
             'HelloTableGateway' => function ($sm) {
                 $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
                 $resultSetPrototype = new ResultSet();
                 $resultSetPrototype->setArrayObjectPrototype(new Hello());
                 return new TableGateway('hello', $dbAdapter, null, $resultSetPrototype);
             },
         ),
     );
 }

0 个答案:

没有答案