特定のエンティティ タイプの作成、読み込み、更新などを管理するエンティティ マネージャを持つことができます。
たとえば、FOSUserBundleでは、古い方法でユーザー エンティティを作成する代わりに、 UserManagerを使用したい場合があります。
// Good
$user = $container->get('fos_user.user_manager')->createUser();
// Not so good
$user = new User();
このようにして、管理を別のクラス (この場合はUserManager ) に委任し、追加のコントロールを追加できます。
それでは、エンティティがあるとしましょうFoo
。作成時と読み込み時に自動的FooManager
に関連付けるサービスを作成する必要があります。Imagine
Foo
実在物 :
<?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);
。
もちろん、このクラスを少し調整する必要があります。
これが最善の方法かどうかはわかりませんが、サービスをエンティティに挿入できないため、私が見つけた唯一の回避策です。