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

Zend: the controller is looking for the model inside the controllers folder

我有问题,我好像出不来:

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

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" 文件夹中调用 "Country" class。

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

"Fatal error: Class 'Restapi\Controller\Restapi\Model\Country' not found in D:\Web\Code\ZendRest\module\Restapi\src\Restapi\Controller\AdminController.php on line 28".

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

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

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

因此,当您调用 new Restapi\Model\Country 时,您实际做的是 new \Restapi\Controller\Restapi\Model\Country),因此出现错误。

要解决此问题,请在文件顶部导入 class,方法是添加:

use Restapi\Model\Country

在您已有的其他 use 行的末尾。然后,您可以通过以下方式简单地实例化 class:

new Country

如果你愿意,你可以给它加上别名:

use Restapi\Model\Country as CountryModel

那么,new CountryModel 就可以了。

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