-
-
Notifications
You must be signed in to change notification settings - Fork 1
API
You may need to import this feature on top of your code.
use \Scarlets\Library\API;This API library will help you simplify the code structure when creating API for your website.
Usually the developer want to obtain some fields of data only when using the API, and this will also help the performance of your app because not processing and sending too many data.
API::fields(&$default, $available);
# Example ($_POST['fields'] = 'birthday,gender')
$default = ['user_id', 'username']; // You can also skip this declaration
API::fields($default, ['birthday', 'address', 'country', 'gender']);
# And the $default variable will have value
# ['user_id', 'username', 'birthday', 'gender']When you receiving data from request query, usually it would be received as a string. And you usually check if it's was defined or not. But with this feature, the data type will be adapted with known data types and you could also set the default value when it's not defined.
$data = API::request($field, $default = null);
# Example ($_POST['year'] = '2019')
var_dump(API::request('year', 0));
// Output: int(2019)This feature is almost similar with API::request but this allow you to take and sanitize data with your defined data sanitizer.
API::obtain(&$data, $fields, $sanitizer = false);
# Example
$sanitizeNumber = function($number){
return intval(filter_var($number, FILTER_SANITIZE_NUMBER_INT));
};
API::obtain($data, ['day', 'month', 'year', 'age'], $sanitizeNumber);
// Or you could also pass function name of PHP function
API::obtain($data, ['day', 'month', 'year', 'age'], 'intval');
var_dump($data);
/* Output: array(4) {
["day"]=>int(12)
["month"]=>int(6)
["year"]=>int(2019)
["age"]=>int(21)
}*/This one will help you aliasing the request query to another name. Instead of using if(isset(...)) when you want to update your database table's column with different request name, you can use this feature to rename it. This was almost similar with API::obtain.
API::alias(&$data, $fields, $sanitizer = false);
# Example ($_POST['job_year'] = '2019')
API::alias($data, ['job_year' => 'year'], 'intval');
// Output: ['year' => 2019]