Force array keys in method parameters
P粉006977956
P粉006977956 2024-01-29 14:55:32
0
2
463

So I have a method in my class that will create a new lead with a $fields parameter that the user can pass in the fields.

Let's say I have the following format:

$new_pardot = new FH_Pardot();
$new_pardot->create_prospect();

create_prospect() The method has $fields parameters and needs to be passed in an array, so the example is as follows:

$new_pardot->create_prospect([
    'email' => $posted_data['email'], // Make key mandatory or throw error on method.
    'firstName' => $posted_data['first-name'],
    'lastName' => $posted_data['last-name'],
]);

Is there a way to make the email key in $fields mandatory? Users need to pass the email key, but they can choose to pass other keys as shown above.

Here is the sample method:

public function create_prospect(array $fields)
{
    // Other logic in here.
}

P粉006977956
P粉006977956

reply all(2)
P粉019353247

You should create a validation for your $posted_data['email']. and check if it is required. But if you want this format, you can try the following:

1- Use separate parameters for email:

public function create_prospect($email,array $fields)
{
    // Other logic in here.
}

2-A better approach is to check the email field in an array, with or without an external function:

public function create_prospect(array $fields)
{
    if(!array_key_exists("email", $fields)){
        // printing error! => echo 'error' or throw an exception
        return;
     }
}
P粉668146636

You can verify using one of several methods. The two obvious ways are to validate within the create_prospect function, or to validate before/outside calling create_prospect.

The traditional approach is to validate before trying to create the entity. It makes collecting and displaying validation errors easier than throwing validation messages from everywhere.

Within

public function create_prospect(array $fields)
{
    if (!isset($fields['email']) {
        throw new ValidationException('Please provide an email');     
    }

    ... carry on with your work
}

Before/Beyond

$fields = [
    'email' => $posted_data['email'],
    'firstName' => $posted_data['first-name'],
    'lastName' => $posted_data['last-name'],
];

if (!isset($fields['email']) {
    throw new ValidationException('Please provide an email');     
}

$new_pardot = new FH_Pardot();
$new_pardot->create_prospect($fields);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!