2017-10-10 31 views
0

我有一個這樣的樹:Symfony的3服務未發現異常

src 
`-- AppBundle 
    |-- AppBundle.php 
    |-- Controller 
    | `-- MyController.php 
    `-- Service   
     `-- MyStringService.php 

現在我想在「myController的」使用服務「MyStringService」是這樣的:

<?php 

namespace AppBundle\Controller; 

use Symfony\Component\Routing\Annotation\Route; 
use Symfony\Bundle\FrameworkBundle\Controller\Controller; 
use Symfony\Component\HttpFoundation\Request; 
use Symfony\Component\Validator\Constraints\Date; 
use Symfony\Component\VarDumper\Cloner\Data; 

class MyController extends Controller 
{ 
    public function usernameAction(Request $request, $username) 
    { 
     $data = $this->get('my_string_service')->getString($username); 
     return $this->render('profile.html.twig', $data); 
    } 
} 

那麼讓我們來看看在服務,那不基本沒什麼:

<?php 

namespace AppBundle\Service; 

class MyStringService 
{ 

    public function getString($string) 
    { 
     return $string; 
    } 

} 

而且,這樣我可以通過ID調用它我在小號以下ervices.yml:

services: 
    my_string_service: 
     class: AppBundle/Service/MyStringService 

當我使用php bin/console debug:container my_string_service我得到:

Information for Service "my_string_service" 
=========================================== 

---------------- ----------------------------------- 
    Option   Value 
---------------- ----------------------------------- 
    Service ID  my_string_service     
    Class   AppBundle/Service/MyStringService 
    Tags    -         
    Public   no         
    Synthetic  no         
    Lazy    no         
    Shared   yes         
    Abstract   no 
    Autowired  yes         
    Autoconfigured yes 
---------------- ----------------------------------- 

現在,當我啓動服務,並打開網頁localhost:8000/localhost:8000/MyUsername我得到一個ServiceNotFoundException

所以現在我只是從symfony開始,不知道我在想什麼。

由於提前

+0

爲什麼'公開不'? – Matteo

回答

1

這裏的關鍵項目在輸出Public no

默認情況下,使用全新的Symfony安裝,服務是私有的,意圖使它們用作依賴而不是從容器中獲取(因此,通過構造函數或帶有一點額外配置的類型暗示)一個ControllerAction)。

您可以聲明服務爲public: true在services.yml文件,或(更好的,長期的),開始在構造函數中定義它們:

<?php 
namespace AppBundle\Service; 

use AppBundle\Service\MyStringService 

class MyStringService 
{ 
    private $strService; 

    public function __constructor(MyStringService $strService) 
    { 
     $this->strService = $strService; 
    } 

    public function getString($string) 
    { 
     $data = $this->strService->getString($username); 
     return $this->render('profile.html.twig', $data); 
     ... 

上有service_container page文檔。

+0

謝謝你,現在我可以使用Invalidname''''AppBundle/Service/MyStringService'「不是」my_string_service「服務的有效類名稱.' – Xeni91

+1

它是\ namespace \ class名稱 –