1

データベースからロードするたびにImageエンティティのサムネイルの場所を取得するには、 AvalancheImagineBundleが必要です。

彼らのgithubページに書かれているように、これを行うのはコントローラーで非常に簡単です。

$avalancheService = $this->get('imagine.cache.path.resolver');
$cachedImage = $avalancheService->getBrowserPath($object->getWebPath(), 'my_thumb');

問題は、これをコントローラーに入れたくないということです。データベースからロードするたびにエンティティがこれを呼び出す必要がありますが、エンティティ内からSymfonyサービスにアクセスできません。私が見つけたように、「エンティティは自分自身と他のエンティティについてのみ知っている必要がある」ため、サービスコンテナを取得することはできませんが、どうすれば目的を達成できますか?

具体的には、サービスメソッドを呼び出して、各エンティティの読み込み時にエンティティプロパティ内にその値を格納するにはどうすればよいですか?

4

1 に答える 1

0

特定のエンティティ タイプの作成、読み込み、更新などを管理するエンティティ マネージャを持つことができます。

たとえば、FOSUserBundleでは、古い方法でユーザー エンティティを作成する代わりに、 UserManagerを使用したい場合があります。

// Good
$user = $container->get('fos_user.user_manager')->createUser();

// Not so good
$user = new User();

このようにして、管理を別のクラス (この場合はUserManager ) に委任し、追加のコントロールを追加できます。

それでは、エンティティがあるとしましょうFoo。作成時と読み込み時に自動的FooManagerに関連付けるサービスを作成する必要があります。ImagineFoo

実在物 :

<?php

namespace Acme\DemoBundle\Entity;

class Foo
{
    protected $id;

    protected $imagine;

    public function getId()
    {
        return $this->id;
    }

    public function setImagine($imagine)
    {
        $this->imagine = $imagine;

        return $this;
    }

    public function getImagine()
    {
        return $this->imagine;
    }

    public function getBrowserPath()
    {
        return $this->imagine->getBrowserPath($this->getWebPath(), 'my_thumb')
    }

    public function getWebPath()
    {
        return 'the_path';
    }
}

マネジャー :

<?php

namespace Acme\DemoBundle\Manager;

class FooManager
{
    // Service 'imagine.cache.path.resolver' injected by DIC
    protected $imagine;

    // Entity repository injected by DIC
    protected $repository;

    public function __construct($imagine, $repository)
    {
        $this->imagine = $imagine;
        $this->repository = $repository;
    }

    public function find($id)
    {
        // Load entity from database
        $foo = $this->repository->find($id);

        // Set the Imagine service so we can use it inside entities
        $foo->setImagine($this->imagine);

        return $foo;
    }
}

次に、のようなものを使用します$foo = $container->get('foo_manager')->find($id);

もちろん、このクラスを少し調整する必要があります。

これが最善の方法かどうかはわかりませんが、サービスをエンティティに挿入できないため、私が見つけた唯一の回避策です。

于 2012-12-26T10:52:23.737 に答える