CakePHP4:将 Cake\ORM\Entity 转换或转换为实际实体以进行类型提示

发布于 2025-01-11 13:44:47 字数 433 浏览 0 评论 0原文

假设我有一个方法需要发票实体作为参数。因此,我添加了类型提示 Invoice,如下所示:

public function doThatThing (Invoice $invoiceEntity)
{
    // ... operate on $invoiceEntity
}

不幸的是,当我传递 InvoiceTable->get(123) 的结果时,我收到错误“TypeError: Argument 1传递给 doThatThing 的实例必须是 App\Model\Entity\Invoice 的实例,是 Cake\ORM\Entity 的实例...”在我的单元测试中。

有没有一种好方法可以将 ->get() 的通用 ORM 结果转换或转换为我知道它必须是的特定实体类型?

Let's say I have a method that is expecting an Invoice entity as a parameter. So I add the type hint Invoice like so:

public function doThatThing (Invoice $invoiceEntity)
{
    // ... operate on $invoiceEntity
}

Unfortunately, when I pass the results of InvoiceTable->get(123), I get the error "TypeError: Argument 1 passed to doThatThing must be an instance of App\Model\Entity\Invoice, instance of Cake\ORM\Entity given..." in my unit tests.

Is there a good way to cast or convert the generic ORM results of ->get() to the specific Entity type that I know it must be?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

空心↖ 2025-01-18 13:44:47

@greg-schmidt 让我找到了正确的方向。恐怕我的问题只是在我说“在我的单元测试中”时提到了传递的关键线索。

事实证明,我的单元测试有一个扩展 InvoiceTable 的假发票表。我的假表确实调用setTablesetAlias,以便它看起来像真正的表。

但是,当我在假对象上调用 get() 时,调用链会绕过 InvoiceTable,进入 ORM/Table,并最终调用 ORM/Query。当 ORM/Table 调用 ORM/Query 上的构造函数时,它会传递 $this,它是我的假实例,而不是真正的底层 InvoiceTable 的实例(setTablesetAlias 此时不起作用)。正如@greg-schmidt 猜测的那样,

InvoiceTable 几乎可以肯定不是您的发票表实现

我的解决方案是让我的假发票实现它自己的 get() 方法,该方法将返回来自真实发票的响应 发票表。

@greg-schmidt got me looking in the right direction. I'm afraid my question only mentioned the key clue in passing when I said "in my unit tests."

As it turns out, my unit test has a fake invoice table that extends InvoiceTable. My fake does call setTable and setAlias so that it looks like the real table.

But when I call get() on the fake, the call chain bypasses InvoiceTable, lands in ORM/Table, and eventually calls into ORM/Query. When ORM/Table calls the constructor on ORM/Query, it passes $this, which is an instance of my fake, and not of the real, underlying InvoiceTable (setTable and setAlias have no effect at this point). And as @greg-schmidt guessed,

InvoiceTable is almost certainly not your invoice table implementation

My solution will be to have my fake invoice implement its own get() method which will return the response from a real InvoiceTable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文