我对变量的初始化有疑问
我的控制器:
namespace SB\FrontendBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\ORM\EntityManager;
use Mie\FrontendBundle\Entity\Product;
class FrontendController extends Controller
{
protected $em;
public function __construct(EntityManager $entityManager = null)
{
$this->em = $this->getDoctrine()->getManager(); //--->TEST 1
$this->em = $entityManager; //--->TEST2
}
public function dispatchUrl(Request $request)
{
$this->em = $this->getDoctrine()->getManager(); //--->TEST 3
$product = new Product();
$product->setName('A Foo Bar');
$product->setPrice('19.99');
$product->setDescription('Lorem ipsum dolor');
$this->em->persist($product);
$this->em->flush();
die();
}
}
在我的 services.yml 中,配置将教义服务传递给我的控制器 FrontendController
parameters:
mie.frontend.controller.frontend.class: Mie\FrontendBundle\Controller\FrontendController
services:
# ---> ESSAI 1
mie.frontend.controller:
class: "%mie.frontend.controller.frontend.class%"
arguments:
- "@doctrine.orm.entity_manager"
# ---> ESSAI 2
mie.frontend.controller:
class: "%mie.frontend.controller.frontend.class%"
arguments: [ @doctrine.orm.entity_manager ]
# ---> ESSAI 3
# mie.frontend.controller:
# class: "%mie.frontend.controller.frontend.class%"
# calls:
# - [setEntityManager, ["@doctrine.orm.entity_manager"]]
- 测试 1 不起作用
- 带有 ESSAI 1,2,3 (services.yml) 的测试 2 不起作用
- 测试 3 作品
使用 TEST 1,我收到以下错误:错误:在第 291 行的 vendor\symfony\symfony\src\Symfony\Bundle\FrameworkBundle\Controller\Controller.php 中调用一个成员函数 has() on null
使用 TEST 2 $entityManager(__construct 的参数)为 NULL
我没有在控制器中读取带有实体管理器实例的变量初始化的任何内容。我认为使用 Symfony2.3,TEST 2 可以工作。
我是否忘记了教义配置中的某些内容?
谢谢,
菲尔