CakePHP4:将 Cake\ORM\Entity 转换或转换为实际实体以进行类型提示
假设我有一个方法需要发票实体作为参数。因此,我添加了类型提示 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
@greg-schmidt 让我找到了正确的方向。恐怕我的问题只是在我说“在我的单元测试中”时提到了传递的关键线索。
事实证明,我的单元测试有一个扩展
InvoiceTable
的假发票表。我的假表确实调用setTable
和setAlias
,以便它看起来像真正的表。但是,当我在假对象上调用
get()
时,调用链会绕过 InvoiceTable,进入 ORM/Table,并最终调用 ORM/Query。当 ORM/Table 调用 ORM/Query 上的构造函数时,它会传递$this
,它是我的假实例,而不是真正的底层 InvoiceTable 的实例(setTable
和setAlias
此时不起作用)。正如@greg-schmidt 猜测的那样,我的解决方案是让我的假发票实现它自己的
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 callsetTable
andsetAlias
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
andsetAlias
have no effect at this point). And as @greg-schmidt guessed,My solution will be to have my fake invoice implement its own
get()
method which will return the response from a real InvoiceTable.