Home > Enterprise >  Mandate array key in method parameter
Mandate array key in method parameter

Time:06-24

So I have a method inside my class which will create a new prospect, which has a $fields parameter that users can pass in the fields.

So let's say that I have the following format:

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

The create_prospect() method has $fields param that needs a array passed into it, so an example would be like this:

$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 the $fields mandatory? Users will need to pass in the email key, but then they have the option to pass in additional keys as shown above.

Here is the example method:

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

CodePudding user response:

You can take one of many approaches to where the validation takes place. The two obvious ways are doing the validation within the create_prospect function, or doing the validation before/outside calling create_prospect.

The traditional approach is to do your validation before trying to create the entity. It makes collecting and displaying validation errors easier than throwing validation messages from various places.

within

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

    ... carry on with your work
}

Before/Outside

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

CodePudding user response:

you should create a validation for your $posted_data['email']. and check it to be required. but if you want this format you may try to ways :

1- use separate argument for email:

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

2- better way is to check the email field in your 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;
     }
}
  •  Tags:  
  • php
  • Related