Magento2.4.4创建模型提示未继承\Magento\Framework\DataObject
异常说明
Magento 2.4.4环境下创建自定义模型时触发如下异常:
1 exception(s): Exception #0 (InvalidArgumentException): Training4\Vendor\Model\Training4_Vendor2Product does not extend \Magento\Framework\DataObject
代码中模型类已经声明继承Magento\Framework\Model\AbstractModel(该类本身已继承\Magento\Framework\DataObject,满足Magento模型的继承要求),但异常依旧触发。
根本原因
异常核心触发点是模型、资源模型类名使用了下划线:
Magento 2的类自动加载、ORM映射、对象管理器实例化逻辑兼容旧版PSR-0加载规则,会自动将类名中的下划线解析为目录分隔符,导致框架无法正确定位编写的类文件,类加载失败后触发继承关系校验,抛出当前异常。
另外代码中类常量const vendor_id='id'不符合PHP类常量大写的通用规范,虽不会直接触发当前报错,但易引发后续调用错误。
修复方案
- 重命名类和对应文件,移除类名中的下划线,统一使用大驼峰命名:
- 将原模型类名
Training4_Vendor2Product改为Vendor2Product,对应文件路径从app/code/Training4/Vendor/Model/Training4_Vendor2Product.php改为app/code/Training4/Vendor/Model/Vendor2Product.php - 将原资源模型类名
Training4_Vendor2Product改为Vendor2Product,对应文件路径从app/code/Training4/Vendor/Model/ResourceModel/Training4_Vendor2Product.php改为app/code/Training4/Vendor/Model/ResourceModel/Vendor2Product.php - 将原集合类所在目录
app/code/Training4/Vendor/Model/ResourceModel/Training4_Vendor2Product/重命名为app/code/Training4/Vendor/Model/ResourceModel/Vendor2Product/,目录下Collection.php文件名无需修改
- 将原模型类名
- 修正三个类文件内的命名空间、类名和引用关系:
修正后模型类代码:
修正后资源模型类代码:<?php namespace Training4\Vendor\Model; use Magento\Framework\Model\AbstractModel; class Vendor2Product extends AbstractModel { const VENDOR_ID = 'id'; protected $_idFieldName = self::VENDOR_ID; protected function _construct() { $this->_init(\Training4\Vendor\Model\ResourceModel\Vendor2Product::class); } }
修正后集合类代码:<?php namespace Training4\Vendor\Model\ResourceModel; use Magento\Framework\Model\ResourceModel\Db\AbstractDb; class Vendor2Product extends AbstractDb { protected function _construct() { $this->_init('training4_vendor2product','id'); } }<?php namespace Training4\Vendor\Model\ResourceModel\Vendor2Product; use Magento\Framework\Model\ResourceModel\Db\Collection\AbstractCollection; class Collection extends AbstractCollection { protected $_idFieldName = 'id'; protected function _construct() { $this->_init( \Training4\Vendor\Model\Vendor2Product::class, \Training4\Vendor\Model\ResourceModel\Vendor2Product::class ); } } - 清理生成文件与缓存,在Magento根目录执行如下命令:
rm -rf generated/* var/cache/* var/page_cache/* php bin/magento setup:upgrade php bin/magento cache:clean
执行完成后异常即可消失,自定义模型可正常使用。
注:Magento 2全版本均不推荐在PHP类名中使用下划线,所有类名统一采用大驼峰格式,避免触发自动加载兼容问题。
内容的提问来源于stack exchange,提问作者DanielHe
相关产品推荐
相关产品推荐

