【问题标题】:Zend: the controller is looking for the model inside the controllers folderZend:控制器正在控制器文件夹中寻找模型
【发布时间】:2015-07-18 21:40:19
【问题描述】:

我有一个问题,我似乎无法脱身:

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

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”类。

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

“致命错误:第 28 行的 D:\Web\Code\ZendRest\module\Restapi\src\Restapi\Controller\AdminController.php 中找不到类 'Restapi\Controller\Restapi\Model\Country'”。

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

【问题讨论】:

    标签: model controller zend-framework2


    【解决方案1】:

    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 的现有引用也可以修复错误。但不要这样做 - 命名空间的主要目的是允许您在代码中使用较短的类名。

    【讨论】:

    • 感谢您的帮助,我已经尝试过了,但并没有改变任何事情。此外,如果我评论调用国家模型的行,问题继续出现在 TableGateway 上:“致命错误:在 D:\Web\Code 中找不到 Class 'Restapi\Controller\Zend\Db\TableGateway\TableGateway' \ZendRest\module\Restapi\src\Restapi\Controller\AdminController.php 在第 30 行“我同意这个问题与命名空间有关,但我不知道它来自哪里。
    • 对不起,它运行良好,我只是在使用 $tableGateWay = new Zend\Db\TableGateway\TableGateway 时出错了 use Zend\Db\TableGateway\TableGateway;,非常感谢 :)
    猜你喜欢
    • 2012-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-01-23
    • 1970-01-01
    • 2015-09-14
    • 2018-09-08
    • 2014-11-24
    • 2013-07-23
    相关资源
    最近更新 更多