3

私はsymfony 2フレームワークを調査しています。私のサンプル アプリには、Blog エンティティと BlogEntry エンティティがあります。それらは 1 対多の関係で接続されています。これは BlogEntry クラスです:

class BlogEntry
{
    ....
    private $blog;
    ....
    public function getBlog()
    {
        return $this->blog;
    }

    public function setBlog(Blog $blog)
    {
        $this->blog = $blog;
    }
}

メソッド setBlogByBlogId を BlogEntry クラスに追加したいのですが、次のように表示されます。

public function setBlogByBlogId($blogId)
    {
        if ($blogId && $blog = $this->getDoctrine()->getEntityManager()->getRepository('AppBlogBundle:Blog')->find($blogId))
        {
            $this->setBlog($blog);
        }
        else
        {
            throw \Exception();
        }
    }

これはモデルクラスで教義を取得する方法ですか? これは Symfony 2 MVC アーキテクチャの観点から正しいですか? または、コントローラーでこれを行う必要がありますか?

4

1 に答える 1

5

BlogEntry エンティティに設定する前に、blogId を使用してブログ オブジェクトのリポジトリをクエリする必要があります。

ブログ オブジェクトを取得したら、BlogEntry エンティティで setBlog($blog) を呼び出すだけです。

これはコントローラで行うか、ブログ サービス (ブログ マネージャ) を作成して行うことができます。サービスでそれを行うことをお勧めします:

Your/Bundle/Resources/config/services.yml でサービスを定義します。

services
    service.blog:
    class: Your\Bundle\Service\BlogService
    arguments: [@doctrine.orm.default_entity_manager]

あなたの/Bundle/Service/BlogService.php:

class BlogService
{

    private $entityManager;

    /*
     * @param EntityManager $entityManager
     */
    public function __construct($entityManager)
    {
        $this->entityManager = $entityManager;
    }

    /*
     * @param integer $blogId
     *
     * @return Blog
     */
    public function getBlogById($blogId)

        return $this->entityManager
                    ->getRepository('AppBlogBundle:Blog')
                    ->find($blogId);
    }
}

そして、コントローラーで次のように簡単に移動できます。

$blogId = //however you get your blogId
$blogEntry = //however you get your blogEntry

$blogService = $this->get('service.blog');
$blog = $blogService->getBlogById($blogId);

$blogEntry->setBlog($blog);
于 2012-06-26T16:56:50.273 に答える