如何在PHP中遵循DRY原则 优化重复调用textStyles拼接样式类的代码
优化方案
第一步:精简原有textStyles函数冗余代码
原函数中前两次get_sub_field调用参数完全一致,属于无效重复,可直接删除冗余行,优化后代码如下:
function textStyles($prefix, $position, $type){ $title = get_sub_field($prefix . '_' . $position . '_font_' . $type); $titleNG = get_field($prefix . '_' . $position . '_font_' . $type); $titleOption = get_field($prefix . '_' . $position . '_font_' . $type, 'options'); $titleTheme = get_theme_mod( 'hero_text_' . $type, 0 ); return $title ?: $titleNG ?: $titleOption ?: $titleTheme; }
第二步:封装批量生成样式类的辅助函数
因为你每次都需要固定获取size、color、weight、alignment四个属性再拼接为类名,可以把这个逻辑封装为独立函数,避免重复写调用和拼接逻辑,后续调整属性列表也只需要修改一处即可:
function buildTextClass($prefix, $position) { // 定义需要获取的样式属性列表 $styleTypes = ['size', 'color', 'weight', 'alignment']; // 循环调用textStyles获取所有属性值 $classArr = array_map(function($type) use ($prefix, $position) { return textStyles($prefix, $position, $type); }, $styleTypes); // 过滤空值后拼接为类名字符串,避免多余空格 return implode(' ', array_filter($classArr)); }
第三步:简化调用逻辑
封装完成后,原来的重复调用代码可以直接简化为两行:
$titleClass = buildTextClass($sepPrefix, 'title'); $introClass = buildTextClass($sepPrefix, 'intro');
如果后续需要新增其他位置的样式类(比如正文、副标题等),只需要调用一次buildTextClass传入对应参数即可。
内容的提问来源于stack exchange,提问作者Kelsey Brookes
相关产品推荐
相关产品推荐

