Zend:控制器正在寻找控制器文件夹中的模型

时间:2015-07-18 21:40:19

标签: model controller zend-framework2

我有一个问题,我似乎无法离开:

我有一个看起来像这样的控制器

namespace Restapi\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Zend\Db\TableGateway\TableGateway;

class AdminController extends AbstractActionController
{

    public function indexAction()
    {
        $this->getAllCountries();
        return new ViewModel();
    }

    public function homeAction()
    {
        return new ViewModel();
    }

    protected function getAllCountries()
    {
        $sm = $this->getServiceLocator();
        $dbAdapter = $sm->get('Zend\Db\Adapter\Adapter');
        $resultSetPrototype = new \Zend\Db\ResultSet\ResultSet;
        $resultSetPrototype->setArrayObjectPrototype(new Restapi\Model\Country);
        $tableGateWay = new Zend\Db\TableGateway\TableGateway('country', $dbAdapter, null, $resultSetPrototype);

        $countryTable = new Model\CountryTable($tableGateWay);
        var_dump($countryTable->fetchAll());
    }

}

哪个应该叫"国家" " Restapi / Model"文件夹中。

但是当我尝试使用调用该模型的方法时出现错误:

  

"致命错误:Class' Restapi \ Controller \ Restapi \ Model \ Country'在第28行和第34行的D:\ Web \ Code \ ZendRest \ module \ Restapi \ src \ Restapi \ Controller \ AdminController.php中找不到。

Zend绝对想在Controller文件夹中查找模型。有谁知道为什么以及如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

TLDR :将use Restapi\Model\Country添加到文件的顶部(其他use行所在的位置),并更改您将类实例化为只是:new Country

更长的解释:这只是一个PHP名称空间问题。在文件的顶部,您已声明了命名空间Restapi\Controller,它告诉PHP假设您随后使用的任何类都在该命名空间内,除非您导入它们(使用use命令),或使用via引用它们。全局命名空间(以反斜杠开头的类名)。

因此,当您致电new Restapi\Model\Country时,您实际所做的是new \Restapi\Controller\Restapi\Model\Country),因此错误。

要解决此问题,请通过添加以下内容导入文件顶部的类:

use Restapi\Model\Country

在您已有的其他use行的末尾。然后,您只需执行以下操作即可实例化该类:

new Country

如果您愿意,可以改为别名:

use Restapi\Model\Country as CountryModel

然后,new CountryModel会起作用。

或者,只需将现有引用更改为use \Restapi\Model\Country也可以修复错误。但是不要这样做 - 名称空间的主要目的是允许您在代码中使用较短的类名。