大佬教程收集整理的这篇文章主要介绍了php-原则实体和特征.正确的路,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个Comment实体(用于用户评论),我想在旧实体中添加一个新功能(CommentablE).
我创建了一个特征Commentable:
Trait Commentable
{
/**
* List of comments
*
* @var Comment[]|ArrayCollection
*
* @ORM\OneToMany(targetEntity="Comment")
*/
protected $comments;
/**
* Constructor
*/
public function __construct()
{
$this->comments = new ArrayCollection();
}
/**
* Get Comments
*
* @return Comment[]|ArrayCollection
*/
public function getComments()
{
return $this->comments;
}
/**
* Add comment to the entity
*
* @param Comment $comment
*/
public function addComment(Comment $comment)
{
$this->comments->add($comment);
}
}
在旧实体中,我会执行以下操作:
class Image
{
use Commentable {
Commentable::__construct as private __commentableConstruct;
}
/** some stuff **/
}
Comment类如下所示:
class Comment
{
/**
* Identifier
*
* @var int
*
* @ORM\Id
* @ORM\column(type="Integer")
* @ORM\GeneratedValue(strategy="IDENTITY")
*/
protected $id;
/**
* Comment owner
*
* @var User
*
* @ORM\ManyToOne(targetEntity="User", inversedBy="comments")
* @ORM\Joincolumn(name="user_id", referencedcolumnName="id")
*/
protected $user;
/**
* Comment content
*
* @var String
*
* @ORM\column(type="text")
*/
protected $content;
/**
* @var Image
*
* @ORM\ManyToOne(targetEntity="Image", inversedBy="comments")
*/
protected $image;
/** all the classes using Commentable **/
/** some stuff */
}
我认为这个主意还不错.我可以创建新的行为并将其轻松添加到实体中.
但是我不喜欢Comment实体上的想法.使用COR_859_11845@mentable特性添加所有类不是’usefull’.
我收到此错误…但是我不知道如何使用特征来解决该问题:
OneToMany mapping on field 'comments' requires the 'mappedBy' attribute.
解决方法:
我使用解决了问题
Trait Commentable
{
/**
* List of comments
*
* @var Comment[]|ArrayCollection
*
* @ORM\ManyToMany(targetEntity="XXXX\Entity\Comment")
* @ORM\OrderBy({"createdAt" = "DESC"})
*/
protected $comments;
/**
* Constructor
*/
public function __construct()
{
$this->comments = new ArrayCollection();
}
/**
* Get Comments
*
* @return Comment[]|ArrayCollection
*/
public function getComments()
{
return $this->comments;
}
/**
* Add comment to the entity
*
* @param Comment $comment
*/
public function addComment(Comment $comment)
{
$this->comments->add($comment);
}
}
以上是大佬教程为你收集整理的php-原则实体和特征.正确的路全部内容,希望文章能够帮你解决php-原则实体和特征.正确的路所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。