【问题标题】:Symfony2, Doctrine, getDoctrine() without __construct() methodSymfony2, Doctrine, getDoctrine() 没有 __construct() 方法
【发布时间】:2013-01-31 12:58:25
【问题描述】:

我们有服务

services:
    service_name:
        class: One\SomeBundle\Controller\OurController

我们需要添加什么来使 $this->getDoctrine() 在我们的 "OurController" 中工作? 我在“OurController”中尝试过

$this->countainer->get('doctrine') 
// and
$this->getDoctrine()

但什么也没发生,只是错误。

我希望这个控制器使用本地方法,例如 $this->getDoctrine()。据我所知,我们可以为控制器提供参数(services.yml 中的参数),然后应用它,但我们可以将其设置为默认值吗?没有

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

和其他额外的东西。我所需要的只是让 $this->getDocrine() 工作。

【问题讨论】:

    标签: symfony service controller doctrine


    【解决方案1】:

    我认为该原则适用于所有这样的控制器

    $em = $this->getDoctrine()->getEntityManager();

    如果您希望在您的服务中使用该教义,请使用类似的内容

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

    【讨论】:

    • 我明白没有解决办法,所以最好通过论证给 EM
    【解决方案2】:

    定义服务时,必须将参数作为参数传递如下(因为默认情况下服务无权访问主容器):

    <services>
        <service id="myservice" class="path/to/my/class">
            <argument type="service" id="doctrine" />
            ...
        </service>
    </services>
    

    这是用xml配置的,但如果你愿意,我会让你把它转换成yml。

    然后在你的服务类中你只需要这样设置你的构造函数:

    class MyServiceClass
    {
        protected $doctrine;
    
        public function __construct(\Doctrine $doctrine, ...)
        {
            $this->doctrine = $doctrine;
            ....
        }
    }
    

    现在学说服务将在您自己的服务类中可用。

    【讨论】:

    • 我写的有问题,没有 __construct 方法,我知道如何用参数来做
    【解决方案3】:

    您可以使用 JMSDiExtra 为 Controller 中的属性设置服务:

    控制器代码:

    <?php
    
    namespace Acme\DemoBundle\Controller;
    
    use Symfony\Bundle\FrameworkBundle\Controller\Controller;
    use JMS\DiExtraBundle\Annotation as DI;
    
    /**
     * Controller class
     */
    class MyController extends Controller
    {
        /**
         * @DI\Inject
         */
        protected $request;
    
        /**
         * @DI\Inject("doctrine.orm.entity_manager")
         */
        protected $em;
    
        // .....
    
        /**
         * Action
         */
        public function myAction()
        {
            // ....
            $this->em->persist($myObject);
            // ....
        }
    }
    

    更多关于 JMSDiExtra 的文档 - http://jmsyst.com/bundles/JMSDiExtraBundle

    这个包是 Symfony2 框架中的默认包

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      • 2016-03-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多