Symfony 3.3.5 config service

时间:2017-08-05 11:34:53

标签: symfony

I have some class ObjectManager and want create service for him, I create config

services:
_defaults:
    autowire: true
    autoconfigure: true
    public: false

AppBundle\:
    resource: '../../src/AppBundle/*'
    exclude: '../../src/AppBundle/{Entity,Repository,Tests}'

AppBundle\Service\:
    resource: '../../src/AppBundle/Service'
    public: true

app.object_manager:
    class: AppBundle\Service\ObjectManager
    arguments:
        - '@jms_serializer'
        - '@validator'

and after get this service in controller and have error

$objectManager = $this->get('app.object_manager');

You have requested a non-existent service "app.object_manager".

Why this happened, symfony 3.3.5 have different way for config services ?

3 个答案:

答案 0 :(得分:1)

首先,当您希望能够使用get调用服务时,必须将其公开定义。

app.object_manager:
    class: AppBundle\Service\ObjectManager
    public: true

但你也可以在services.yml的顶部做到这一点,以定义所有服务都是公共的:

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: true

这样,你就不必在每项服务上明确地​​做到这一点。

此外,我建议您使用Symfony的新自动装配功能。这样,您就不必在services.yml中定义服务。

只需在ObjectManager类中定义构造函数:

class ObjectManager
{
    private $jms_serializer;
    private $validator;

    public function __construct(SerializerInterface $jms_serializer, ValidatorInterface $validator)
    {
        $this->jms_serializer   = $jms_serializer;
        $this->validator        = $validator;
    }
}

他会通过自动装配找到正确的服务。而且您不必在services.yml中定义任何内容。

所以,总结一下你的services.yml应该只包含以下内容:

services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: true

AppBundle\:
    resource: '../../src/AppBundle/*'
    exclude: '../../src/AppBundle/{Entity,Repository,Tests}'

答案 1 :(得分:0)

如果你想通过get()使用它们,你需要在Symfony 3中明确地将你的服务定义为公共服务。

# app/config/services.yml
services:
    # default configuration for services in *this* file
    _defaults:
        # ...
        public: false

此处有更多信息 - http://symfony.com/doc/current/service_container.html#public-versus-private-services

答案 2 :(得分:0)

您实际上可以将Symfony 3.3 + 用于full potential

如果我理解正确,您需要AppBundle\Service\ObjectManager到您的控制器。

在那种情况下......

1。修改您的services.yml

services:
    _defaults:
        autowire: true

    AppBundle\:
        resource: '../../src/AppBundle/*'
        exclude: '../../src/AppBundle/{Entity,Repository,Tests}'

2。需要AppBundle\Service\ObjectManager通过构造函数(在任何需要的地方)

use AppBundle\Service\ObjectManager;

final class MyController
{
    /**
     * @var ObjectManager
     */
    private $objectManager;

    public function __construct(ObjectManager $objectManager)
    {
        $this->objectManager = $objectManager;
    }

    public function someAction()        
    {
        $this->objectManager->someCoolMethod();
    }
}

这就是全部!

没什么特别的,只是纯粹的Symfony真棒!