use*_*660 6 symfony symfony-3.3
在使用时Symfony 3.3,我宣布这样的服务:
class TheService implements ContainerAwareInterface
{
use ContainerAwareTrait;
...
}
Run Code Online (Sandbox Code Playgroud)
在我需要EntityManager的每个动作中,我从容器中获取它:
$em = $this->container->get('doctrine.orm.entity_manager');
Run Code Online (Sandbox Code Playgroud)
这有点烦人,所以我很好奇Symfony是否有类似的东西EntityManagerAwareInterface.
Ste*_*wen 22
传统上,您将在services.yml文件中创建一个新的服务定义,将实体管理器设置为构造函数的参数
app.the_service:
class: AppBundle\Services\TheService
arguments: ['@doctrine.orm.entity_manager']
Run Code Online (Sandbox Code Playgroud)
最近,随着symfony 3.3的发布,默认的symfony-standard-edition将其默认services.yml文件更改为默认使用autowire并添加AppBundle要成为服务的所有类.这消除了添加自定义服务的需要,并且在构造函数中使用类型提示将自动注入正确的服务.
您的服务类将如下所示
use Doctrine\ORM\EntityManagerInterface
class TheService
{
private $em;
public function __construct(EntityManagerInterface $em)
{
$this->em = $em;
}
// ...
}
Run Code Online (Sandbox Code Playgroud)
有关自动定义服务依赖关系的更多信息,请参阅https://symfony.com/doc/current/service_container/autowiring.html
新的默认services.yml配置文件可在此处获得:https://github.com/symfony/symfony-standard/blob/3.3/app/config/services.yml
| 归档时间: |
|
| 查看次数: |
10601 次 |
| 最近记录: |