前几天做项目,需要记录操作日志,用tp框架写。每次根据操作单独写日志的内容太麻烦了,所以想到将需要记录的方法日志记录到每个方法的注释上,这样随时灵活更改。所以,查了一些资料,最终总结如下:
if (!function_exists("getMethodAnnotationValue")){
/**
* @param $className 类全名 xxx:class
* @param $methodName 方法名 action
* @param $annotationName 注释名称 desc
* @return mixed|null
* @throws ReflectionException
* @author: 大炸蟹
* @createTime: 2024/8/14
*/
function getMethodAnnotationValues($className, $methodName, $annotationName="@log") {
$reflectionMethod = new ReflectionMethod($className, $methodName);
$docComment = $reflectionMethod->getDocComment();
// 将所有多个空格转为一个
$docComment=preg_replace("/\s+/",' ',$docComment);
$comment_arr = explode("* ", $docComment);
$comment_arr_withkeyval = [];
foreach ($comment_arr as $item) {
$item=str_replace(['/*','*/'],'',$item);
$item=trim($item);
if (empty($item)) continue;
if (str_contains($item," ")){
$item_arr = explode(" ", $item);
$key = trim($item_arr[0],"@");
$val = trim($item_arr[1]);
if (!empty($val)) $comment_arr_withkeyval[$key] = $val;
}else{
$comment_arr_withkeyval[]=$item;
}
}
if (!empty($annotationName)) return $comment_arr_withkeyval[$annotationName];
return $comment_arr_withkeyval;
}
}