Symfony2在服务容器中使用原则

时间:2022-09-15 20:12:47

How do I use Doctrine in a service container?

如何在服务容器中使用Doctrine ?

The Code just causes an error message "Fatal error: Call to undefined method ...::get()".

代码只会导致一个错误消息“致命错误:调用未定义的方法…:get()”。

<?php

namespace ...\Service;

use Doctrine\ORM\EntityManager;
use ...\Entity\Header;

class dsdsf
{ 
    protected $em;

    public function __construct(EntityManager $em)
    {
        $this->em = $em;
    }

    public function create()
    {
        $id = 10;
        $em = $this->get('doctrine')->getEntityManager();
        $em->getRepository('...')->find($id);
    }
}

services.yml

services.yml

service:
    site:
        class: ...\Service\Site

7 个解决方案

#1


82  

According to your code, you already have an EntityManager injected. You don't need to call $em = $this->get('doctrine')->getEntityManager() — just use $this->em.

根据您的代码,您已经注入了一个EntityManager。您不需要调用$em = $this->get('doctrine')->getEntityManager() -只需使用$this->em。

If you don't inject an EntityManager already, read this.

如果还没有注入EntityManager,请阅读本文。

UPDATE:

更新:

You need to make the container inject an EntityManager into your service. Here's an example of doing it in config.yml:

您需要让容器将EntityManager注入到您的服务中。这是config.yml中的一个例子:

services:
    your.service:
        class: YourVendor\YourBundle\Service\YourService
        arguments: [ @doctrine.orm.entity_manager ]

I prefer to define bundles' services in their own services.yml files, but that's a bit more advanced, so using config.yml is good enough to get started.

我更喜欢在它们自己的服务中定义bundle的服务。yml文件,但是这有点高级,使用配置。yml很好,可以开始了。

#2


9  

For easily accessing the Entitymanager use the following one:

要方便地访问Entitymanager,请使用以下方法:

//services.yml
  your service here:
    class: yourclasshere
    arguments: [@doctrine.orm.entity_manager]

And in the class itself:

在课堂上

class foo
{
  protected $em;



  public function __construct(\Doctrine\ORM\EntityManager $em)
  {
    $this->em = $em;
  }

  public function bar()
  {
      //Do the Database stuff
      $query = $this->em->createQueryBuilder();

      //Your Query goes here

      $result = $query->getResult();
  }
}

This is my first answer so any comments are appreciated :)

这是我的第一个回答,希望大家能给我一些建议。

#3


4  

Please try this code:

请试试这段代码:

 $em=$this->container->get('doctrine')->getEntityManager();

 $rolescheduels=$em->getRepository('OCSOCSBundle:RoleScheduel')->findByUser($user->getId());

#4


3  

For Symfony 3.x

The most easy-peasy solution for me was to just turn on autowiring/autoconfiguring, and then injecting the service I needed via the constructor. Note that I have also allowed any controller to be injected as a service by setting resource: '../../src/AppBundle/*'

对我来说,最简单的解决方案是打开自动配线/自动配置,然后通过构造函数注入所需的服务。注意,我还允许通过设置资源“.. ./../src/AppBundle/*”将任何控制器作为服务注入。

 #services.yml or config.yml
 services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false
    # Allow any controller to be used as a service
    AppBundle\:
        resource: '../../src/AppBundle/*'    
        # you can exclude directories or files
        # but if a service is unused, it's removed anyway
        exclude: '../../src/AppBundle/{Entity,Repository,Tests,DataFixtures,Form}'

Then in any service, you can inject & use the entity manager $em (or any other service/controller) via the constructor like this:

然后,在任何服务中,您都可以通过这样的构造器注入并使用实体管理器$em(或任何其他服务/控制器):

// class xyz
private $em;
// constructor
public function __construct(\Doctrine\ORM\EntityManager $em)  {
    $this->em = $em;
}
public function bar() {
    //Do the Database stuff
    $query = $this->em->createQueryBuilder();
    //Your Query goes here
    $result = $query->getResult();
}

#5


2  

for anyone who works with symfony3: u need to do the following inside config/services.yml in order to use doctrine in Service Container:

对于使用symfony3的任何人:您需要在配置/服务中执行以下操作。在服务容器中使用原则:

servicename_manager:
          class: AppBundle\Services\MyServiceClass
          arguments: [ "@doctrine.orm.entity_manager" ]

#6


0  

Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.

自2017年和Symfony 3.3以来,您可以将存储库注册为服务,具有它所有的优点。

Your code would change like this.

你的代码会像这样变化。

1. Service configuration

# app/config/services.yml
services:
    _defaults:
        autowire: true

    ...\Service\:
       resource: ...\Service

2. Create new class - custom repository:

use Doctrine\ORM\EntityManagerInterface;

class YourRepository
{ 
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(YourEntity::class);
    }

    public function find($id)
    {
        return $this->repository->find($id);
    }
}

3. Use in any Controller or Service like this

class dsdsf
{ 
    private $yourRepository;

    public function __construct(YourRepository $yourRepository)
    {
        $this->yourRepository = $yourRepository;
    }

    public function create()
    {
        $id = 10;
        $this->yourRepository->find($id);
    }
}

Do you want to see more code and pros/cons lists?

你想看到更多的代码和优缺点列表吗?

Check my post How to use Repository with Doctrine as Service in Symfony.

查看我的帖子,如何在Symfony中使用仓库作为服务。

#7


0  

I am using Symfony 3.4. If you want to create a service in a bundle this works for me:

我使用的是Symfony 3.4。如果你想在一个包中创建一个服务,这对我来说是可行的:

services:
 Vendor\YourBundle\Service\YourService:
   arguments:
     $em: '@doctrine.orm.entity_manager'

In your Service.php

在你Service.php

<?php

namespace Hannoma\ElternsprechtagBundle\Service;

use Doctrine\ORM\EntityManager;
use Hannoma\ElternsprechtagBundle\Entity\Time;

class TimeManager
{
 protected $em;

 public function __construct(EntityManager $em)
 {
    $this->em = $em;
 }

}

#1


82  

According to your code, you already have an EntityManager injected. You don't need to call $em = $this->get('doctrine')->getEntityManager() — just use $this->em.

根据您的代码,您已经注入了一个EntityManager。您不需要调用$em = $this->get('doctrine')->getEntityManager() -只需使用$this->em。

If you don't inject an EntityManager already, read this.

如果还没有注入EntityManager,请阅读本文。

UPDATE:

更新:

You need to make the container inject an EntityManager into your service. Here's an example of doing it in config.yml:

您需要让容器将EntityManager注入到您的服务中。这是config.yml中的一个例子:

services:
    your.service:
        class: YourVendor\YourBundle\Service\YourService
        arguments: [ @doctrine.orm.entity_manager ]

I prefer to define bundles' services in their own services.yml files, but that's a bit more advanced, so using config.yml is good enough to get started.

我更喜欢在它们自己的服务中定义bundle的服务。yml文件,但是这有点高级,使用配置。yml很好,可以开始了。

#2


9  

For easily accessing the Entitymanager use the following one:

要方便地访问Entitymanager,请使用以下方法:

//services.yml
  your service here:
    class: yourclasshere
    arguments: [@doctrine.orm.entity_manager]

And in the class itself:

在课堂上

class foo
{
  protected $em;



  public function __construct(\Doctrine\ORM\EntityManager $em)
  {
    $this->em = $em;
  }

  public function bar()
  {
      //Do the Database stuff
      $query = $this->em->createQueryBuilder();

      //Your Query goes here

      $result = $query->getResult();
  }
}

This is my first answer so any comments are appreciated :)

这是我的第一个回答,希望大家能给我一些建议。

#3


4  

Please try this code:

请试试这段代码:

 $em=$this->container->get('doctrine')->getEntityManager();

 $rolescheduels=$em->getRepository('OCSOCSBundle:RoleScheduel')->findByUser($user->getId());

#4


3  

For Symfony 3.x

The most easy-peasy solution for me was to just turn on autowiring/autoconfiguring, and then injecting the service I needed via the constructor. Note that I have also allowed any controller to be injected as a service by setting resource: '../../src/AppBundle/*'

对我来说,最简单的解决方案是打开自动配线/自动配置,然后通过构造函数注入所需的服务。注意,我还允许通过设置资源“.. ./../src/AppBundle/*”将任何控制器作为服务注入。

 #services.yml or config.yml
 services:
    _defaults:
        autowire: true
        autoconfigure: true
        public: false
    # Allow any controller to be used as a service
    AppBundle\:
        resource: '../../src/AppBundle/*'    
        # you can exclude directories or files
        # but if a service is unused, it's removed anyway
        exclude: '../../src/AppBundle/{Entity,Repository,Tests,DataFixtures,Form}'

Then in any service, you can inject & use the entity manager $em (or any other service/controller) via the constructor like this:

然后,在任何服务中,您都可以通过这样的构造器注入并使用实体管理器$em(或任何其他服务/控制器):

// class xyz
private $em;
// constructor
public function __construct(\Doctrine\ORM\EntityManager $em)  {
    $this->em = $em;
}
public function bar() {
    //Do the Database stuff
    $query = $this->em->createQueryBuilder();
    //Your Query goes here
    $result = $query->getResult();
}

#5


2  

for anyone who works with symfony3: u need to do the following inside config/services.yml in order to use doctrine in Service Container:

对于使用symfony3的任何人:您需要在配置/服务中执行以下操作。在服务容器中使用原则:

servicename_manager:
          class: AppBundle\Services\MyServiceClass
          arguments: [ "@doctrine.orm.entity_manager" ]

#6


0  

Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.

自2017年和Symfony 3.3以来,您可以将存储库注册为服务,具有它所有的优点。

Your code would change like this.

你的代码会像这样变化。

1. Service configuration

# app/config/services.yml
services:
    _defaults:
        autowire: true

    ...\Service\:
       resource: ...\Service

2. Create new class - custom repository:

use Doctrine\ORM\EntityManagerInterface;

class YourRepository
{ 
    private $repository;

    public function __construct(EntityManagerInterface $entityManager)
    {
        $this->repository = $entityManager->getRepository(YourEntity::class);
    }

    public function find($id)
    {
        return $this->repository->find($id);
    }
}

3. Use in any Controller or Service like this

class dsdsf
{ 
    private $yourRepository;

    public function __construct(YourRepository $yourRepository)
    {
        $this->yourRepository = $yourRepository;
    }

    public function create()
    {
        $id = 10;
        $this->yourRepository->find($id);
    }
}

Do you want to see more code and pros/cons lists?

你想看到更多的代码和优缺点列表吗?

Check my post How to use Repository with Doctrine as Service in Symfony.

查看我的帖子,如何在Symfony中使用仓库作为服务。

#7


0  

I am using Symfony 3.4. If you want to create a service in a bundle this works for me:

我使用的是Symfony 3.4。如果你想在一个包中创建一个服务,这对我来说是可行的:

services:
 Vendor\YourBundle\Service\YourService:
   arguments:
     $em: '@doctrine.orm.entity_manager'

In your Service.php

在你Service.php

<?php

namespace Hannoma\ElternsprechtagBundle\Service;

use Doctrine\ORM\EntityManager;
use Hannoma\ElternsprechtagBundle\Entity\Time;

class TimeManager
{
 protected $em;

 public function __construct(EntityManager $em)
 {
    $this->em = $em;
 }

}