“在非对象上调用成员函数 has()"来自 Symfony 2 控制器 [英] "Call to a member function has() on a non-object" from Symfony 2 Controller

查看:27
本文介绍了“在非对象上调用成员函数 has()"来自 Symfony 2 控制器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到一个错误

致命错误:在第 161 行的/labs/Projects/What2Do/vendor/symfony/src/Symfony/Bundle/FrameworkBundle/Controller/Controller.php 中的非对象上调用成员函数 has()

我不确定如何调试.错误出在 Symfony 2 文件中,而不是我的……我的控制器如下所示.我正在运行 indexAction

Am not exactly sure how to debug this. The error is in a Symfony 2 file, not mine ... my controller looks like below. I am running the indexAction

<?php
class ProjectsController extends Controller {

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

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

    /**
     * @Route("/")
     * @Route("/projects", name="listProjects")
     * @Template()
     */
    public function indexAction() {
        $projects = $this->em->getRepository(Project::NAME)->findAll();

        return array('projects' => $projects);
    }

    /**
     * @Route("/projects/{projId}", name="viewProject") 
     * @Template()
     */
    public function viewAction($projId) {
        // retrieve project
        $proj = $this->em->getRepository(Project::NAME)->findOneById($projId);
        if ($proj == null)
            throw $this->createNotFoundException ('Invalid project');

        return array('proj' => $proj);
    }
}

推荐答案

Symfony 2 控制器没有 __construct 方法,所以虽然调用父构造函数不是一个坏主意,但它不会有帮助.

The Symfony 2 controller has no __construct method so while calling parent constructors is not a bad idea, it's not going to help.

问题是容器在 __construct 之后被注入,所以试图在构造函数中获取你的学说实体管理器是行不通的.我知道这有点违反直觉,但让经理了解你的行动方法.

The problem is that the container gets injected after __construct so trying to get your doctrine entity manager in the constructor will simply not work. I know it's a bit counter intuitive but get the manager in your action methods.

我假设您的 Project::NAME 类常量中包含类似ProjectBundle:Project"的内容.

And I'm assuming your Project::NAME class constant has something like 'ProjectBundle:Project' in it.

这篇关于“在非对象上调用成员函数 has()"来自 Symfony 2 控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆