从实体调用存储库方法

时间:2012-09-14 09:49:41

标签: php doctrine-orm

是否可以在实体上调用存储库方法? 我的意思是这样的

$article = $em->getRepository('Entities\Articles')->findOneBy(array('id' => $articleId));
$category = $em->getRepository('Entities\Categories')->findOneBy(array('id' => 86));

$article->addArticleToCategory($category);

其中addArticleToCategory是存储库中的方法(只是示例代码)

public function addArticleToCategory($category){
    $categoryArticles = new CategoryArticles();
    $categoryArticles->setArticle(!!/** This is where I want to have my variable $article from this method call **/!!);
    $categoryArticles->setCategory($category);
    $this->getEntityManager()->persist($categoryArticles);
    $this->getEntityManager()->flush();
}

最好的方法是什么?

另外我想知道将自定义set / create方法放在存储库中是一个好习惯吗?

2 个答案:

答案 0 :(得分:2)

根据定义,您无法从实体对象中调用存储库类的方法...这是基本的面向对象编程。

我认为您应该在addArticle实体中创建Category函数,如下所示:

function addArticle($article)
{
   $this->articles[] = $article;
   $article->setCategory($this);
}

然后你做

$article = $em->getRepository('Entities\Articles')->findOneBy(array('id' => $articleId));
$category = $em->getRepository('Entities\Categories')->findOneBy(array('id' => 86));

$category->addArticle($article);
$em->persist($category);
$em->flush();

如果级联配置正确,则可以使用

答案 1 :(得分:0)

您可以编写自己的存储库管理器并根据需要创建方法。

http://docs.doctrine-project.org/en/2.0.x/reference/working-with-objects.html#custom-repositories