如何在Kentico Kontent PHP SDK中自定义PropertyMapper并解决返回null问题?
解决自定义PropertyMapper的实现问题
1. 正确编写自定义PropertyMapper类
以Kentico Kontent PHP SDK为例,直接继承默认的DefaultPropertyMapper并重写getProperty方法,移除驼峰转换逻辑即可:
use Kentico\Kontent\Delivery\PropertyMappers\DefaultPropertyMapper; class CustomPropertyMapper extends DefaultPropertyMapper { public function getProperty($item, $arrKey) { // 注释/删除驼峰转换代码,保留原键名逻辑 // $arrKey = TextHelper::getInstance()->camelCase($arrKey); if (array_key_exists($arrKey, $item)) { return $item[$arrKey]; } return null; } }
2. 正确注入自定义Mapper到DeliveryClient
不要直接给$client->propertyMapper赋值,SDK不支持这种直接修改公共属性的方式,需通过官方提供的配置或setter方法注入:
方式一:初始化客户端时传入配置
$client = new DeliveryClient($this->projectID, $this->previewKey, [ 'propertyMapper' => new CustomPropertyMapper() ]);
方式二:按条件动态切换
如果需要根据特定条件启用自定义逻辑,可先初始化客户端,再判断注入:
$client = new DeliveryClient($this->projectID, $this->previewKey); // 自定义判断条件,比如环境标识、开关变量等 if ($needOriginalKeyFormat) { $client->setPropertyMapper(new CustomPropertyMapper()); }
3. 直接赋值返回null的原因
SDK内部的PropertyMapper是通过依赖注入机制管理的,直接修改公共属性不会触发内部初始化逻辑,导致后续调用时无法正确获取Mapper实例,最终返回null。只有通过官方提供的配置或setter方法,才能让SDK正确识别并使用你的自定义Mapper。
内容的提问来源于stack exchange,提问作者ChanhHuynh
相关产品推荐
相关产品推荐

