php - 使用 Zend Framework 2 连接到 mysql

标签 php mysql zend-framework2

我正在尝试使用 zend 框架连接 mysql 数据库,但无法连接。 我跟进了 zend 文档和其他一些关于如何连接到 mysql 的教程,但它在“$sm = $this->getServiceLocator();”这一行上给了我一个错误

错误消息:

Zend\ServiceManager\ServiceManager::get was unable to fetch or create an instance for Post\Model\PostTable

全局.php

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',
    ),
),);

本地.php

 return array(
'db' => array(
    'username' => 'root',
    'password' => '',
),

);

PostController.php

public function getPostTable() {
    if (!$this->postTable) {
        $sm = $this->getServiceLocator();
        $this->postTable = $sm->get('Post\Model\PostTable');
    }
    return $this->postTable;
}

//module/Post/src/Post/Model/PostTable.php

<?php
namespace Post\Model;

use Zend\Db\Adapter\Adapter;
use Zend\Db\ResultSet\ResultSet;
use Zend\Db\TableGateway\AbstractTableGateway;

class PostTable extends AbstractTableGateway
{
  protected $table ='tbl_post';

   public function __construct(Adapter $adapter)
{
    $this->adapter = $adapter;
    $this->resultSetPrototype = new ResultSet();
    $this->resultSetPrototype->setArrayObjectPrototype(new Post());
    $this->initialize();
}

public function fetchAll()
{
    $resultSet = $this->select();
    return $resultSet;
}
}

最佳答案

在您的 Module.php 中,您应该使用“Post\Model\PostTable”注入(inject)表格

祝你好运:)

关于php - 使用 Zend Framework 2 连接到 mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25049283/

相关文章:

zend-form - 禁用notInArray验证程序Zend Framework 2

php - MySQL : Order by and Group By combining not giving the latest record

php - 使用 meta_query 将当前日期与 Wordpress 中的时间戳进行比较

mysql - 如何获取mysql中未映射的记录

php - 如果一个类不存在,你应该抛出哪个 PHP SPL 异常

testing - ZF2 测试 - serviceManager 忽略的模拟对象

php - 在 SQL 的 WHERE 中排序

php - 我的 Composer 不会用 Laravel 4 完全更新它被 artisan 卡住了

mysql - 以下 node.js mySQL 查询存在什么问题?

mysql - magento 的服务器解决方案