[英]Symfony2 Dependency Injection to custom/business classes
我没有在Googleing或Stackoverflow上找到类似的问题/解决方案,所以我在这里需要帮助。 我正在将PHP项目从自定义框架移植到Symfony框架(v2.5),该框架具有自定义依赖项注入(基于类反射)。 许多业务逻辑类都注入了属性,我很想知道是否有一种方法可以在Symfony中做类似的事情而无需将这些类声明为服务,因为某些类用于临时保存/操作来自第三者端点和我需要它们的不同实例。
更确切地说,有一种方法可以将依赖注入与使用new关键字实例化对象结合使用。 因此,如果我需要一个依赖于记录器或验证器的新类,我该怎么做?
我要解决依赖项注入的内容类:
class Content extends SomeObject
{
private $pictureUrl;
...
public __construct(array $array = null)
{
parent::__construct($array);
}
public setPicture(...\Picture $picture)
{
// what's the best way to inject/enable this into my class
$errors = $this->get('validator')->validate($picture->getUrl());
...
$this->pictureUrl = $picture->getUrl();
}
...
}
实例化上一类的类(在这种特殊情况下,这可以是服务,但在其他情况下,这是与业务逻辑相关的另一类):
class EndpointService extends Service
{
...
public fetchContent()
{
$dataArray = $this->endpoint->fetch();
$contentArray = array();
foreach ($dataArray as $key => $value) {
$content = new Content(array());
$content->setPicture($value->picture);
...
$contentArray[$key] = $content;
}
}
...
}
注意 :如果存在逻辑/语法错误,请忽略它们,这是一个演示我的问题的示例,并且是与我的代码库的遥远抽象。
我看到了一种方法,可以通过将依赖项validator
程序的依赖项传递给EndpointService
来实现。 然后,您可以将其传递给新的Content
。
class EndpointService extends Service
{
...
public function construct($validator)
{
$this->validator = $validator;
}
public fetchContent()
{
$dataArray = $this->endpoint->fetch();
$contentArray = array();
foreach ($dataArray as $key => $value) {
$content = new Content($this->validator, array());
$content->setPicture($value->picture);
...
$contentArray[$key] = $content;
}
}
...
}
class Content extends SomeObject
{
private $pictureUrl;
...
public __construct($validator, array $array = null)
{
$this->validator = $validator;
parent::__construct($array);
}
public setPicture(...\Picture $picture)
{
// what's the best way to inject/enable this into my class
$errors = $this->validator->validate($picture->getUrl());
...
$this->pictureUrl = $picture->getUrl();
}
...
}
在我看来,您的Content
是一个模型,验证应该在EndpointService
类中完成。
您可能考虑重构,以便将验证器注入到EndpointService
继承的Service
父类中,如果您不想直接将其注入到EndpointService
。
class EndpointService extends Service
{
protected $validator;
public __construct(Validator $validator) {
$this->validator = $validator;
}
...
public fetchContent()
{
$dataArray = $this->endpoint->fetch();
$contentArray = array();
foreach ($dataArray as $key => $value) {
$content = new Content(array());
$errors = $this->validator->validate($value->picture->getUrl());
$content->setPicture($value->picture);
...
$contentArray[$key] = $content;
}
}
...
}
并在您的配置中:
// config.yml
services:
app.endpoint_service:
class: Acme\DemoBundle\External\EndpointService
arguments: [@validator]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.