Home  >  Q&A  >  body text

Force array keys in method parameters

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粉006977956P粉006977956287 days ago509

reply all(2)I'll reply

  • P粉019353247

    P粉0193532472024-01-30 12:35:18

    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;
         }
    }

    reply
    0
  • P粉668146636

    P粉6681466362024-01-30 12:20:08

    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);
    

    reply
    0
  • Cancelreply