将存储库、实体管理器注入服务的最佳实践是什么?
我想我至少可以通过三种方式做到这一点。
这样就可以很容易地通过测试覆盖服务。您所需要做的就是将模拟的依赖项传递给构造函数,然后您就准备好了。
class TestService
{
public function __construct(MyEntityRepository $my, AnotherEntityRepository $another, EntityManager $manager)
{
$this->my = $my;
$this->another = $another;
$this->manager = $manager;
}
public function doSomething()
{
$item = $this->my->find(<...>);
<..>
$this->manager->persist($item);
$this->manager->flush();
}
}
Run Code Online (Sandbox Code Playgroud)
如果您需要来自同一管理器的 4 个存储库,则测试起来会有点困难。我认为这样你必须模拟经理的 getRepository 调用。
class TestService
{
public function __construct(EntityManager $manager)
{
$this->manager = $manager;
}
public function doSomething()
{
$item = $this->manager->getRepository('my')->find(<...>);
<..>
$this->manager->persist($item);
$this->manager->flush();
}
}
Run Code Online (Sandbox Code Playgroud)
这样,您就不会遇到教义事件订阅者的循环引用异常,但模拟所有内容会更困难。
这也是 sensiolabs Insights 不会给我带来注入 EntityManager 架构违规的唯一方法。
class TestService
{
public …Run Code Online (Sandbox Code Playgroud) 我正在尝试扩展一个Abstract对象.
var Abstract = function() { code = 'Abstract'; };
Abstract.prototype.getCode = function() { return code; };
Abstract.prototype.getC = function() { return c; };
var ItemA = function() { code = 'ItemA'; c = 'a'; };
ItemA.prototype = Object.create(Abstract.prototype);
ItemA.prototype.constructor = ItemA;
var ItemB = function() { code = 'ItemB'; };
ItemB.prototype = Object.create(Abstract.prototype);
ItemB.prototype.constructor = ItemB;
var b = new ItemB();
console.log(b.getCode());
var a = new ItemA();
console.log(b.getCode());
console.log(b.getC());
Run Code Online (Sandbox Code Playgroud)
结果:
ItemB
ItemA
a
Run Code Online (Sandbox Code Playgroud)
我在ItemB实例中获得ItemA的范围有什么特别的原因吗?我该如何解决?
containers ×1
doctrine-orm ×1
extending ×1
global ×1
javascript ×1
prototype ×1
registry ×1
symfony ×1
variables ×1