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

PHP中应用DRY原则动态修改数组指定字段的技术问询

How to Dynamically Modify Your Sales Payload Without Duplicating Code

Absolutely! You don't have to copy the entire array every time you need to adjust a few fields—this is exactly the kind of scenario where the DRY (Don't Repeat Yourself) principle is meant to help. Let’s break down how to refactor this to keep your code clean and maintainable:

1. Create a Reusable Base Payload Template

First, extract your core sales payload into a reusable function. This way, you define the common structure once, and only tweak the parts that change across different use cases.

// Define a function to generate your base sales payload
function getBaseSalesPayload($getOrg, $contact_id, $source, $strToRemove, $online_marketing_check) {
    return [
        'organization_id' => $getOrg['data'][0]['id'],
        'contact_id' => $contact_id,
        'status' => 'Open',
        'responsible_employee_id' => 'employee:50c76c15262b12d36d44e34a3f0f8c3d',
        'source' => [
            'id' => $source['data'][0]['id'],
            'name' => $source['data'][0]['name'],
        ],
        'subject' => " " . str_replace($strToRemove, "", $_POST['billing_myfield12']) . " - Online marketing Duitsland",
        'start_date' => date("Y-m-d"),
        'expected_closing_date' => date("Y-m-d", strtotime(date("Y-m-d") . "+ 14 days")),
        'chance_to_score' => '10%',
        'expected_revenue' => 0,
        'note' => $_POST['order_comments'],
        'progress' => [
            'id' => 'salesprogress:200a53bf6d2bbbfe'
        ],
        "custom_fields" => [["voorstel_diensten" => implode("-", $online_marketing_check)]],
    ];
}

2. Dynamically Modify Only the Fields You Need

Now, whenever you need a variation of the payload, call the function to get the base structure, then overwrite only the specific fields that need to change. This avoids duplicating the entire array every time.

Example: Modify Top-Level Fields

// Get the base payload
$sales_payload = getBaseSalesPayload($getOrg, $contact_id, $source, $strToRemove, $online_marketing_check);

// Update specific top-level fields
$sales_payload['status'] = 'Closed';
$sales_payload['expected_revenue'] = 1500;
$sales_payload['chance_to_score'] = '75%';

Example: Modify Nested Fields

If you need to update nested values (like source or progress), target them directly without rewriting the entire nested array:

// Update the source name while keeping the existing ID
$sales_payload['source']['name'] = 'Updated Referral Source';

// Change the sales progress ID
$sales_payload['progress']['id'] = 'salesprogress:new-progress-id-123';

Example: Modify Custom Fields

For more complex sections like custom_fields, adjust individual values or replace the array entirely if needed:

// Update just the specific custom field value
$sales_payload['custom_fields'][0]['voorstel_diensten'] = implode(",", $updated_service_list);

// Or replace the entire custom_fields array with new entries
$sales_payload['custom_fields'] = [
    ["voorstel_diensten" => "Webdesign-SEO"],
    ["additional_notes" => "Client requested priority support"]
];

3. Bonus: Extract Static Values to Constants

To make maintenance even easier, pull static, unchanging values (like employee IDs or progress IDs) into constants. This way, if you need to update them later, you only do it in one place:

// Define constants at the top of your file or config
define('DEFAULT_RESPONSIBLE_EMPLOYEE', 'employee:50c76c15262b12d36d44e34a3f0f8c3d');
define('DEFAULT_SALES_PROGRESS_ID', 'salesprogress:200a53bf6d2bbbfe');

// Use constants in your base payload function
'responsible_employee_id' => DEFAULT_RESPONSIBLE_EMPLOYEE,
'progress' => [
    'id' => DEFAULT_SALES_PROGRESS_ID
],

This approach keeps your code DRY, cuts down on duplication, and makes future changes far less tedious—no more hunting through 3000+ lines to update a single value!

内容的提问来源于stack exchange,提问作者Kevin.a

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:45:00