【问题标题】:Create Service with Symfony2使用 Symfony2 创建服务
【发布时间】:2012-10-27 10:49:23
【问题描述】:

使用 symfony2 我正在关注 this documentation 来创建和使用服务来执行一般任务。

我差不多完成了,但我还有一个问题(肯定是由于对 Symfony2 中的服务容器的一些误解。

类是这样的:

class MyClass{
    private $myProperty;

    public funciton performSomethingGeneral{
        return $theResult;
    }
}

现在,在我的 config.yml 中:

services:
    myService:
        class: Acme\MyBundle\Service\MyClass
        arguments: [valueForMyProperty]

最后,在我的控制器中:

$myService = $this -> container -> get('myService');

在那一行之后,当我检查 $myService 时,我仍然看到 $myService -> $myProperty 未初始化。

有些事情我没有得到正确的。我还需要做什么才能使属性初始化并准备好与config.yml 中先前配置的值一起使用?以及如何设置多个属性?

【问题讨论】:

    标签: php service symfony


    【解决方案1】:

    你的 yml 文件中的arguments 被传递给你的服务的构造函数,所以你应该在那里处理它。

    services:
        myService:
            class: Acme\MyBundle\Service\MyClass
            arguments: [valueForMyProperty, otherValue]
    

    和php:

    class MyClass{
        private $myProperty;
        private $otherProperty;
    
        public funciton __construct($property1, $property2){
             $this->myProperty = $property1;   
             $this->otherProperty = $property2;   
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 2015-05-13
      • 2023-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多