2017-10-10 5 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; 
    } 

} 

私は私の次のもので私はそれを呼び出すことができますervices.yml:私はphp bin/console debug:container my_string_serviceを使用する場合

services: 
    my_string_service: 
     class: AppBundle/Service/MyStringService 

私が手:私はサービスを開始し、ページlocalhost:8000/またはlocalhost:8000/MyUsernameを開いたときに

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 
---------------- ----------------------------------- 

は今、私はServiceNotFoundExceptionを取得します。

今、私はsymfonyを使い始めましたが、私が紛失しているものは分かりません。アドバンス

+0

なぜ 'public no'ですか? – Matteo

答えて

1

おかげで、ここで出力のキー項目はPublic noです。

デフォルトでは、新鮮なSymfonyインストールでは、サービスはプライベートであり、コンテナからフェッチするのではなく、依存関係として使用することを意図しています(したがって、コンストラクタを介してタイプヒントされるか、 ControllerAction)を使用します。

あなたのservices.ymlファイルにpublic: trueとしてそのサービスを宣言し、または(より良い、長期的に)、コンストラクタでそれらを定義するために開始することができ、次のいずれか

<?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名です –

関連する問題