You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 13:45:03