5

I have a rest api that has many parameters via the query string. I am wondering if someone knows of a design pattern or has a nice way of organizing all the parameters (Objects, functions, array, json). Right now I am parsing and validating all my parameters in the same function, very ugly code.

Ideally I would like some way to handle the parameters similar to a database ORM or even a config file/array/json. However, I have tried to come up with a solution to this without any luck.

Any insight would be appreciated!

Example of my thoughts:

<?php ... $parameters = [ // ?fields=id,name 'fields' => [ 'default' => ['id', 'name'], 'valid' => ['id', 'name', 'date], 'type' => 'csv', // list of values (id & name) 'required' => ['id'], 'replace' => ['title' => 'name'], // if the database & api names don't match 'relation' => null, // related database table ], // ?list=true 'list' => [ 'default' => ['false'], 'valid' => ['true', 'false'], 'type' => 'boolean' // single value (true or false) 'required' => [], 'replace' => [], // if the database & api names don't match 'relation' => 'category', // related database table ], .... ]; 

1 Answer 1

2

Seems to me like you are looking for a validation library. My favorite is Symfony's: https://github.com/symfony/validator. I know Zend Framework 2 also has a validation component. I haven't used it personally, but I expect that to be very good too.

Example from the symfony/validator readme:

<?php use Symfony\Component\Validator\Validation; use Symfony\Component\Validator\Constraints as Assert; $validator = Validation::createValidator(); $constraint = new Assert\Collection(array( 'name' => new Assert\Collection(array( 'first_name' => new Assert\Length(array('min' => 101)), 'last_name' => new Assert\Length(array('min' => 1)), )), 'email' => new Assert\Email(), 'simple' => new Assert\Length(array('min' => 102)), 'gender' => new Assert\Choice(array(3, 4)), 'file' => new Assert\File(), 'password' => new Assert\Length(array('min' => 60)), )); 

$input would be $_GET or something obtained with parse_str etc. It is also possible to define the validation rules in some other format, such as YAML.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.