2017-10-10 88 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名称 –