错误:在非对象上调用成员函数getAuthor()

时间:2014-07-20 10:25:05

标签: php symfony

使用symfony2和doctrine2。当我尝试使用方法getAutho()从Article实体恢复Author属性时,它会抛出此错误:

FatalErrorException: Error: Call to a member function getAuthor() on a non-object in D:\xampp\htdocs\Portofolio\src\Portofolio\FrontBundle\Controller\FrontController.php line 65  

这是我的功能:

public function showAction($slug) {
    $em = $this->getDoctrine()->getManager();
    //retrieve the the article using it's id
    $article = $em->getRepository('PortofolioAdminBundle:Article')->getArticleBySlug($slug);
    var_dump($article->getAuthor());
    //get About entity
    $about = $em->getRepository('PortofolioAdminBundle:About')->findOneBy(array('email' => 'baccouch.taieb@gmail.com'));
    //get all categories
    $categories = $em->getRepository('PortofolioAdminBundle:Category')->findAll();
    $articles = $em->getRepository('PortofolioAdminBundle:Article')->getLatestArticles();
    //create the search form
    $search = new Search();
    $searchForm = $this->createForm(new SearchType(), $search);
    return $this->render('PortofolioFrontBundle:Front:show.html.twig', array(
                'article' => $article, 'about' => $about, 'categories' => $categories,
                'articles' => $articles, 'searchForm' => $searchForm->createView(),
    ));
}  

如何解决此错误?

1 个答案:

答案 0 :(得分:0)

似乎在数据库中没有给定slug的文章,因此存储库返回NULL。 请使用数据库引擎的数据库客户端检查文章表中是否存在阻塞slu。

您还应该在代码中处理这种情况。请检查symfony docs http://symfony.com/doc/current/book/controller.html#managing-errors-and-404-pages