2014-05-19 22 views
1

Symfony 2典型的問題,但沒有明確的迴應(我做了一些研究)。Symfony 2 FatalErrorException:錯誤:調用一個非對象的成員函數有()

給出下面的「DefaultController」類,它的實際工作:

<?php 

namespace obbex\AdsBundle\Controller; 

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 

class DefaultController extends Controller 
{ 
    public function indexAction() 
    { 
     $em = $this->getDoctrine()->getEntityManager(); 
     $connection=$em->getConnection(); 
     $string="SELECT DISTINCT country_code FROM country_data"; 
     $statement = $connection->prepare($string); 
     $statement->execute(); 
     $result = $statement->fetchAll(); 
     var_dump($result); //works not problem 
     die(); 
    } 
} 

我想委派調用數據庫稱爲「DatabaseController」另一個類的「DefaultController」現在設置如下:

<?php 

namespace obbex\AdsBundle\Controller; 

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use obbex\AdsBundle\Controller\DatabaseController; //new DatabaseController 

class DefaultController extends Controller 
{ 
    public function indexAction() 
    { 
     $dbController = new DatabaseController(); 
     $res = $dbController->getQuery(); 
    } 
} 

和 「DatabaseController」 被設置爲執行以下操作:

namespace obbex\AdsBundle\Controller; 

use Symfony\Bundle\FrameworkBundle\Controller\Controller; 

class DatabaseController extends Controller{ 

    public function __construct() { 
    } 


    public function getQuery() 
    { 
     $em = $this->getDoctrine()->getEntityManager(); 
     $connection=$em->getConnection(); 
     $string="SELECT DISTINCT country_code FROM country_data"; 
     $statement = $connection->prepare($string); 
     $statement->execute(); 
     return $statement->fetchAll(); 
    } 

} 

而這個throw和下面的錯誤:FatalErrorException:錯誤:調用成員函數has()對於/home/alfonso/sites/ads.obbex.com/public_html/vendor/symfony/symfony/src/中的非對象Symfony/Bundle/FrameworkBundle/Controller/Controller.php line 202

因爲我擴展了完全相同的類「控制器」,所以我現在的想法正在流行。爲什麼它在一個案例中而不是在另一個案件中工作?

顯然,這是一個「容器問題」,可以被設置爲根據在另一個線程或經由延伸的「控制器·類然而並不在這種情況下工作。

回答

0

首先的響應槽服務,你shouldn`t委託數據庫管理到另一個控制器,這是一個不好的做法。

相反,你可以注入包含所有DB邏輯

Symfony2 Use Doctrine in Service Container

服務或使用實體庫

​​

關於與has()功能,您要創建一個控制器的一個實例,不會對任何容器中的問題。因此,當控制器嘗試撥打$this->container->has()時會引發錯誤,因爲未定義容器。

0

我終於設置對象調用者和我要求的集裝箱航線如下:

主控制器上的services.yml文件

service: 
    manage_ads: 
    class: obbex\AdsBundle\Classes\ManageAds 
    calls: 
     - [setContainer, ["@service_container"]] 

$ads_manager = $this->get('manage_ads'); 
$ads_manager->functionCallingTheRawQuery(); 

但我仍然可以選擇使用它,因爲現在我正在從實體的存儲庫設置查詢,而不是創建自己的對象(現在,我是symfony2的新手)

相關問題