Symfony 3.1 / Doctrine、Repository或include路径错误


Symfony 3.1 / Doctrine, Repository or include path wrong

我得到了这个错误:

警告:Doctrine'ORM'EntityRepository::__construct()缺少参数1

我使用phpstorm进行编码,在TestController.php

new ProductRepository(); 

用下划线表示:

必需参数$em缺少less.

调用参数类型与声明的不兼容。

但是我还没有使用$em参数。

我使用了3个文件:

AppBundle
    |__Controller
    |            |__ TestController.php
    |__Entity
            |_______ Product.php
            |_______ ProductRepository.php

TestController.php:

<?php
namespace AppBundle'Controller;

use Sensio'Bundle'FrameworkExtraBundle'Configuration'Route;
use Symfony'Bundle'FrameworkBundle'Controller'Controller;
use Doctrine'ORM'EntityRepository;
use AppBundle'Entity'ProductRepository;
use Symfony'Component'HttpFoundation'Response;
class TestController extends Controller
{
/**
 * @Route("/test", name="test")
 */
  public function indexAction()
  {
    $pr = new ProductRepository();
    return new Response('OK '.$pr->test());
  }
}

Product.php:

<?php
// src/AppBundle/Entity/Product.php
namespace AppBundle'Entity;
use Doctrine'ORM'Mapping as ORM;
/**
 * @ORM'Entity
 * @ORM'Table(name="product")
 * @ORM'Entity(repositoryClass="AppBundle'Entity'ProductRepository")
 */
class Product
{ /* ......CODE ...*/}

ProductRepository.php:

namespace AppBundle'Entity;
use Doctrine'ORM'EntityRepository;
class ProductRepository extends EntityRepository
{
    public function test()
    {
        return 'hello';
    }
 }

通过学说服务获取知识库,控制器通过getDoctrine方法返回学说服务

  public function indexAction()
  {
    $pr = $this->getDoctrine()->getRepository('AppBundle:Product');
    return new Response('OK '.$pr->test());
  }

您不应该直接创建存储库。使用EntityManager。您可以尝试以下代码:

class TestController extends Controller
{
    private $entityManager;
    public function __construct('Doctrine'ORM'EntityManager $entityManager)
    {
        $this->entityManager = $entityManager;
    }
/**
 * @Route("/test", name="test")
 */
  public function indexAction()
  {
    $pr = $this->entityManager->getRepository('AppBundle'Entity'ProductRepository');
    return new Response('OK '.$pr->test());
  }
}