【问题标题】:Symfony service declaration namespaceSymfony 服务声明命名空间
【发布时间】:2016-10-03 06:16:16
【问题描述】:

我对 symfony2 有一个奇怪的问题。 在 service.yml 我声明了分页服务:

site.paginate_service:
class: "Smestaj\SiteBundle\Services\PaginationService"
arguments:
  - "@service_container"

服务如下所示:

namespace Smestaj\SiteBundle\Services;
use Symfony\Component\DependencyInjection\ContainerInterface;
class PaginationService{

protected $cn;
protected $numberOfData;

public function __construct(ContainerInterface $container)
{
    $this->cn = $container;
    $this->numberOfData = $container->getParameter("limit")['adsPerPage'];
}

问题是当我在 service.yml 中将此服务作为依赖注入调用到另一个服务中时

site.ads_service:
class: "Smestaj\SiteBundle\Services\AdsService"
arguments:
  - "@doctrine.orm.entity_manager"
  - "@service_container"
calls:
  - [setPaginate, ["@site.paginate_service"]]

然后我收到此错误消息:

尝试从命名空间“Smestaj\SiteBundle”加载类“ServicesaginationService”。 您是否忘记了另一个命名空间的“使用”语句?

所以,从这条消息中可以明显看出 symfony 试图调用类“ServicesaginationService”。我的班级有 Smestaj\SiteBundle\Services\PaginationService。 Symfony,以某种方式合并 Services 和 PaginationService 名称,并从名称中删除“P”。

如果我将类名称更改为 AaaService,那么一切正常。

【问题讨论】:

  • 尝试从class 值中删除引号。
  • 将 service_container 注入服务本身是个坏主意。你应该只注入依赖的服务、参数等,而不是服务容器

标签: php symfony service dependency-injection


【解决方案1】:

当您在 service.yml 的类名中使用双引号时,您必须通过添加另一个 \ 来转义 \

class: "Smestaj\\SiteBundle\\Services\\PaginationService"

但避免问题的最佳方法是删除引号,因为路径将被 YML 解析器正确解释为字符串:

class: Smestaj\SiteBundle\Services\PaginationService

【讨论】:

  • 感谢您的回复。你的回答解决了我的问题
猜你喜欢
  • 1970-01-01
  • 2011-01-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多