Symfony 2, неопределенная переменная, защищенный член, инициализированный в конструкторе как ошибка ArrayCollection, из-за того, что она не определена

Я использую Symfony 2. У меня есть Entity с защищенной переменной, которая инициализируется в конструкторе как ArrayCollection. Но чем я использую команду

>php app/console doctrine:fixtures:load -vvv

я получаю ошибку:

 [Symfony\Component\Debug\Exception\ContextErrorException]
Notice: Undefined variable: comments

Exception trace:
() at C:\Bitnami\wampstack-5.5.30-0\sym_prog\dctr\src\BlogBundle\Entity\Post.ph
p:183
Symfony\Component\Debug\ErrorHandler->handleError() at C:\Bitnami\wampstack-5.5
.30-0\sym_prog\dctr\src\BlogBundle\Entity\Post.php:183
BlogBundle\Entity\Post->addComment() at C:\Bitnami\wampstack-5.5.30-0\sym_prog\
dctr\src\BlogBundle\DataFixtures\ORM\LoadAuthorData.php:54
<...>

//C:\Bitnami\wampstack-5.5.30-0\sym_prog\dctr\src\BlogBundle\Entity\Post.php

/**
* Add comment
*
* @param \BlogBundle\Entity\Comment $comment
*
* @return Post
*/
public function addComment(\BlogBundle\Entity\Comment $comment)
{
182    $this->comments[] = $comment;
183    $comments->setPost($this);
184    return $this;
}

// Полный файл: \ dctr \ src \ BlogBundle \ Entity \ Post.php

<?php

namespace BlogBundle\Entity;

use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
use Doctrine\ORM\Mapping\Entity;
use Doctrine\ORM\Mapping\Id;
use Doctrine\ORM\Mapping\GeneratedValue;
use Doctrine\ORM\Mapping\Column;
use Doctrine\ORM\Mapping\OneToMany;
use Doctrine\ORM\Mapping\ManyToMany;
use Doctrine\ORM\Mapping\JoinTable;
use Doctrine\ORM\Mapping\JoinColumn;
//use Symfony\Component\Validator\Constraints as Assert;


/**
* Post
*
* @ORM\Table(indexes={@ORM\Index(name="publication_date_idx",columns="publicationDate")})
* @ORM\Entity(repositoryClass="BlogBundle\Entity\PostRepository")
*/
class Post
{
/**
* @var integer
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;

/**
* @var string
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;

/**
* @var string
*
* @ORM\Column(name="body", type="text")
*/
private $body;

/**
* @var \DateTime
*
* @ORM\Column(name="publicationDate", type="datetime")
*/
private $publicationDate;

/**
* @var Comment[]
*
* @ORM\OneToMany(targetEntity="Comment", mappedBy="post")
*/
protected $comments;

/**
* @var Tag[]
*
* @ORM\ManyToMany(targetEntity="Tag", inversedBy="posts", fetch="EAGER", cascade={"persist"}, orphanRemoval=true)
* @ORM\JoinTable(
*      inverseJoinColumns={@ORM\JoinColumn(name="tag_name", referencedColumnName="name")}
* )
*/
protected $tags;

/**
* @var PostAuthor
*
* @ORM\ManyToOne(targetEntity="PostAuthor", inversedBy="posts")
*/
protected $author;

/**
* Initializes collections
*/
public function __construct()
{
$this->comments = new ArrayCollection();
$this->tags = new ArrayCollection();
}

/**
* Get id
*
* @return integer
*/
public function getId()
{
return $this->id;
}

/**
* Set title
*
* @param string $title
*
* @return Post
*/
public function setTitle($title)
{
$this->title = $title;

return $this;
}

/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}

/**
* Set body
*
* @param string $body
*
* @return Post
*/
public function setBody($body)
{
$this->body = $body;

return $this;
}

/**
* Get body
*
* @return string
*/
public function getBody()
{
return $this->body;
}

/**
* Set publicationDate
*
* @param \DateTime $publicationDate
*
* @return Post
*/
public function setPublicationDate($publicationDate)
{
$this->publicationDate = $publicationDate;

return $this;
}

/**
* Get publicationDate
*
* @return \DateTime
*/
public function getPublicationDate()
{
return $this->publicationDate;
}



/**
* Add comment
*
* @param \BlogBundle\Entity\Comment $comment
*
* @return Post
*/
public function addComment(\BlogBundle\Entity\Comment $comment)
{
$this->comments[] = $comment;
$comments->setPost($this);
return $this;
}
/* Another important thing, as already explained,
* is that Doctrine only manages the owning side of an association.
* This is why we call the setPost() method of the Comment entity
* in the addComment() method. This allows persisting
* with an association from the inverse side. */


/**
* Remove comment
*
* @param \BlogBundle\Entity\Comment $comment
*/
public function removeComment(\BlogBundle\Entity\Comment $comment)
{
$this->comments->removeElement($comment);
}

/**
* Get comments
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getComments()
{
return $this->comments;
}

/**
* Add tag
*
* @param \BlogBundle\Entity\Tag $tag
*
* @return Post
*/
public function addTag(\BlogBundle\Entity\Tag $tag)
{
$this->tags[] = $tag;

return $this;
}

/**
* Remove tag
*
* @param \BlogBundle\Entity\Tag $tag
*/
public function removeTag(\BlogBundle\Entity\Tag $tag)
{
$this->tags->removeElement($tag);
}

/**
* Get tags
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTags()
{
return $this->tags;
}

/**
* Set author
*
* @param \BlogBundle\Entity\PostAuthor $author
*
* @return Post
*/
public function setAuthor(\BlogBundle\Entity\PostAuthor $author = null)
{
$this->author = $author;

return $this;
}

/**
* Get author
*
* @return \BlogBundle\Entity\PostAuthor
*/
public function getAuthor()
{
return $this->author;
}
}

//sym_prog\dctr\src\BlogBundle\DataFixtures\ORM\LoadAuthorData.php

line 54 $post->addComment($comment);

//sym_prog\dctr\src\BlogBundle\DataFixtures\ORM\LoadAuthorData.php

<?php

namespace BlogBundle\DataFixtures;

/* This fixture creates instances
of Post, PostAuthor, Comment, and CommentAuthor
and then persists them to the database.
*/

use BlogBundle\Entity\Comment;
use BlogBundle\Entity\CommentAuthor;
use BlogBundle\Entity\Post;
use BlogBundle\Entity\PostAuthor;
use Doctrine\Common\DataFixtures\Doctrine;
use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;

/**
* Author fixtures
*/
class LoadAuthorData implements FixtureInterface
{
/**
* {@inheritDoc}
*/
public function load(ObjectManager $manager)
{
$postAuthor = new PostAuthor();
$postAuthor->setName('George Abitbol');
$postAuthor->setEmail('[email protected]');
$postAuthor->setBio('L\'homme le plus classe du monde');

$manager->persist($postAuthor);

$post = new Post();
$post->setTitle('My post');
$post->setBody('Lorem ipsum');
$post->setPublicationDate(new \DateTime());
$post->setauthor($postAuthor);

$manager->persist($post);

$commentAuthor = new CommentAuthor();
$commentAuthor->setName('Kévin Dunglas');
$commentAuthor->setEmail('[email protected]');

$manager->persist($commentAuthor);

$comment = new Comment();
$comment->setBody('My comment');
$comment->setAuthor($commentAuthor);
$comment->setPublicationDate(new \DateTime());

$post->addComment($comment);
$manager->persist($comment);

$manager->flush();
}
}

0

Решение

Строка 183, которую вы используете $comments с S, но ваша функция получает $comment без С.

/**
* Add comment
*
* @param \BlogBundle\Entity\Comment $comment
*
* @return Post
*/
public function addComment(\BlogBundle\Entity\Comment $comment)
{
182    $this->comments[] = $comment;
183    $comments->setPost($this); // Should be $comment->setPost($this);
184    return $this;
}
0

Другие решения

Решение:
C: \ Bitnami \ wampstack-5.5.30-0 \ sym_prog \ dctr \ SRC \ BlogBundle \ Entity \ Post.php
<…>

 public function addComment(\BlogBundle\Entity\Comment $comment)
{
181  $this->comments[] = $comment;
182  $comment->setPost($this);
//instead of $comments->setPost($this);
183  return $this;
}

В строке 182 я должен установитьPost для объекта $ comment, а не для переменной $ comments.
Переменная комментариев не существует в этом методе, она существует только как $ this-> comments.
$ this-> comments является переменной, поэтому он не может иметь метод setPost ($ this).

0

По вопросам рекламы [email protected]