簡體   English   中英

symfony4,依賴注入,無默認參數

[英]symfony4, Dependency injection, no default argument

我已經為這樣的控制器功能設置了服務

App\Controller\Controller:
    calls:
        - [new, ['@request_stack','@doctrine.orm.default_entity_manager']]

我需要控制器操作中的Entity Manager ,我的功能如下所示

public function new(RequestStack $request, EntityManager $em): Response
{
    $currentRequest = $request->getCurrentRequest();
    $data = json_decode($currentRequest->getContent(), true);
    ....
    return new ApiResponse(['message' => $message['message'], 'body' => 'success']);
}

當執行到 line return new ApiResponse它會給出錯誤

Controller "Controller::new()" requires that you provide a value for the "$request" argument. Either the argument is nullable and no null value has been provided, no default value has been provided or because there is a non optional argument after this one.

如何在控制器操作中獲取實體管理器或如何解決此問題?

正如 Symfony 4 Doc on Doctrine 所說:

// you can fetch the EntityManager via $this->getDoctrine()
// or you can add an argument to your action: index(EntityManagerInterface $entityManager)
$entityManager = $this->getDoctrine()->getManager();

所以你可以在你的控制器中以這種方式獲取實體管理器

但是,您也可以將實體管理器注冊為服務以使用它。

確保將 autowire 設置為 true :

# config/services.yaml
services:
    _defaults:
        autowire: true

並將其注冊為服務:

   # config/services.yaml
   services:
     #....
        controller_em:
            class: App\Controller\Controller
            arguments: [ '@doctrine.orm.default_entity_manager' ]
            public: true

這樣您就可以在控制器中像這樣使用它:

private $objectManager;

public function __construct(ObjectManager $objectManager)
{
    $this->objectManager = $objectManager;

}

您也可以通過這種方式在 Voter 或 Manager 中使用實體管理器。

好。 你需要將你的東西注入控制器的對象構造函數——在 Symfony-way(或通過 set-methods)中稱為DI

services.yml - 如果您的自動裝配一切正常

App\Controller\Controller:
    calls:
        - [new]

如果不手動添加:

 App\Controller\Controller:
    arguments:
        - '@doctrine.orm.default_entity_manager'
    calls:
        - [new]

控制器.php

/** @var EntityManager */
private $em;

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

然后在你的方法中使用它:

public function new(RequestStack $request): Response
{
    $this->em ...
}

為了您的信息,您可以創建自己的 AbsractController 以在所有控制器中注入 EntityManager 像這樣擴展它。

<?php

namespace App\Controller;

use Doctrine\ORM\EntityManagerInterface;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController as BaseController;

abstract class AbstractController extends BaseController
{
    /**
     * @var EntityManagerInterface
     */
    protected $em;

    /**
     * @required
     *
     * @param EntityManagerInterface $em
     */
    public function setEntityManager(EntityManagerInterface $em)
    {
        $this->em = $em;
    }
}

如果控制器擴展了這個 AbstractController,你可以在它的任何地方訪問 $this->em。

此處的“必需”注釋是啟用您嘗試執行的操作的關鍵,而無需像您那樣添加配置。 這就像在您的配置中添加一條呼叫線路!

您可以為所有控制器中所需的每個服務執行類似的操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM