2016-02-28 12 views
0

我總是使用來自控制器或實體庫類的原則,現在我試圖從靜態類中使用它,但我找不到任何有關如何做id的示例。 基本上我需要(我認爲)以靜態方法創建實體管理器的方法。如何從靜態方法使用原則

感謝 中號

+1

所提供的答案是錯的,因爲沒有關於靜態方法的解釋。請不要接受答案 – Trix

回答

-2

我不知道從你的問題,你用靜態類/方法的意思,一些代碼示例可能會有幫助。但是你可以將這個類聲明爲一個服務,它聽起來好像它可能是無論如何,然後注入實體管理器作爲依賴。

services.yml

services: 
    my_service: 
     class: Acme\AppBundle\Services\MyService 
     arguments: ["@doctrine.orm.entity_manager"] 

然後在你的類,你將不得不使用這樣的實體管理器:

<?php 

namespace Acme\AppBundle\Services; 

use Doctrine\ORM\EntityManager; 

class MyService 
{ 

    /** 
    * Entity Manager 
    * 
    * @var Doctrine\ORM\EntityManager 
    */ 
    protected $em; 

    public function __construct(EntityManager $em) 
    { 
     $this->em = $em; 
    } 

    ... 
} 

然後你就可以在你的控制器使用此服務,像這樣:

$this->get('my_service')->doSomething(); 
+0

我知道這種方式來做到這一點,但我需要的是從靜態方法進行查詢,因爲我需要通過調用 $ myResult = MyStaticClass :: getMyValue($ params)來獲得結果。 。所以我需要使用類似於公共靜態函數getMyValue($ params){}的東西。我不希望被迫調用構造函數。謝謝。 – user3174311

+0

實際上,隨後使用上面的服務,您只需向其中添加一個名爲getMyValue($ params)的方法並將其稱爲像''''myResult = this-> get('my_service') - > getMyValue($ params)'' '''。無需調用構造函數,因爲該服務將被實例化,並且實體管理器已經在該點自動注入。 如果你有這個靜態方法的原因是「能夠從任何地方方便地調用它」,那麼服務幾乎是Symfony的做法,我想。 – sekl

+0

謝謝,我會盡快嘗試!我如何從擴展PHPUnit_Framework_TestCase的類調用該服務? – user3174311

2

您可以調用setter函數,注入實體管理器,在那裏調用stati C方法:

myController的

Class MyController extends Controller 
{ 
    public function newAction() 
    { 
     $entityManager = $this->getDoctrine()->getManager(); 
     SomeClass::setEntityManager($entityManager); 
     $result = SomeClass::myStaticMethod(); 
    } 
} 

SomeClass的

Class SomeClass 
{ 
    private static $entityManager;   

    public static function setEntityManager($entityManager) 
    { 
     self::$entityManager = $entityManager; 
    } 

    public static function myStaticMethod() 
    { 
     return $entityManager->getRepository(SomeEntity::class)->findAll(); 
    } 
} 
相關問題