十一:JSON参数自动转为实体对象(下):成果测试、调用的基本姿势
一:JSON 转化为实体对象 完整代码
<?php
//Json数据转化为实体,映射机制;
//$class w为class 名称不是对象;
function jsonForObject($class)
{
$req=request();
try{
$contentType=$req->getHeader('content-type');
if(!$contentType||false===stripos($contentType[0],\Swoft\Http\Message\ContentType::JSON))
{
return false;
}
$raw=$req->getBody()->getContents();
$map=json_decode($raw,true);// key=>value数组
$class_obj=new ReflectionClass($class);//反射对象;
$class_instance=$class_obj->newInstance();//根据反射对象创建的实例;
$methods=$class_obj->getMethods(ReflectionMethod::IS_PUBLIC);
foreach ($methods as $method)
{
//echo $method->getName().PHP_EOL;
//可以使用set开头的方法对属性进行赋值;只要set开头命名的方法即可,通过正则去匹配方法名;
if(preg_match("/^set(\w+)/",$method->getName(),$matches))
{
//echo $matches[0].PHP_EOL;//这里得到方法名,如方法名是setProdId
//echo $matches[1].PHP_EOL;//这里得到方法名,如方法名是setProdId,得到的就是ProdId
invokeSetterMethod($matches[1],$class_obj,$map,$class_instance);
}
}
return $class_instance;
}
catch (Exception $exception)
{
return false;
}
}
//传入对象的时候,new 的哪个类 就把哪个类加上,比如下面的方法 传入ReflectionClass $class_obj
//这样写代码时候就会出现提示;
function invokeSetterMethod($name,ReflectionClass $class_obj,$jsonMap,&$class_instance)
{
//好比把ProdId转化成Prod_Id
$filter_name=strtolower(preg_replace("/(?<=[a-z])([A-Z])/","_$1",$name));
//获取一组属性
$props=$class_obj->getProperties(ReflectionProperty::IS_PRIVATE);
foreach ($props as $prop)
{
if(strtolower($prop->getName())==$filter_name)
{
try {
$method = $class_obj->getMethod("set" . $name);
$args=$method->getParameters();//取出方法参数;
//isset($jsonMap[$filter_name]) 保证提供的参数是存在的;
if(count($args)==1&&isset($jsonMap[$filter_name]))
{
$method->invoke($class_instance,$jsonMap[$filter_name]);
}
} catch (ReflectionException $e) {
}
}
}
}
二:请求


三:



浙公网安备 33010602011771号