2015-07-18 83 views
0

我有一個問題,裏面的模型,我似乎無法脫身:的Zend:控制器正在尋找控制器文件夾

我有一個控制器,它看起來像這樣

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」類。

但我有一個錯誤,當我嘗試使用誰調用模型的方法:

"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文件夾中的模型。有人知道爲什麼以及如何解決這個問題?

回答

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也可以解決該錯誤。但是不要這樣做 - 命名空間的主要目的是讓你在代碼中使用更短的類名。

+0

感謝您的幫助,我已經嘗試過,但沒有改變任何事情。 並進一步,如果我評論說,呼籲國家示範線路,問題繼續與TableGateway: 「致命錯誤:類‘RESTAPI \控制器\ Zend的\ DB \ TableGateway \ TableGateway’不在第30行找到D:\ Web \ Code \ ZendRest \ module \ Restapi \ src \ Restapi \ Controller \ AdminController.php「 我同意問題是關於命名空間,但我不知道它在哪裏來自。 – Lazyrocker

+0

對不起它的工作很好,我只是用錯了 $ tableGateWay =新的Zend \ DB \ TableGateway \ TableGateway 同時使用使用Zend的\ DB \ TableGateway \ TableGateway ;, 感謝很多:) – Lazyrocker