sarphp/return-data-format

PHP 返回数据格式 - 这用于为网络应用程序创建良好的返回数据格式

0.1.1 2017-09-22 17:47 UTC

This package is not auto-updated.

Last update: 2024-09-29 04:36:47 UTC


README

这个PHP包帮助格式化任何类型方法的返回数据。如果有人需要以特定格式(数组、JSON、序列化)返回数据,可以使用它。

示例

class Examples
{
    function __construct() {
    }
    function getData(){
        $data = [
            [
                'id' => 1, 
                'name' => 'Jon D',            
            ],
            [
                'id' => 2, 
                'name' => 'Michel N',            
            ]
        ];
        $apiKey = "Aie"; 
        
        return \ReturnDataFormat\Response::success()->message('Data saved successfully!')
                                                     ->data($data)
                                                     ->apiKey($apiKey);
                                                     // Anything you can add here will be in array 
    }
}

$obj = new Examples();
$data = $obj->getData();
print_r($data->toArray()); 
print_r($data->toJson()); 
print_r($data->toSerialize()) ;

输出

## ARRAY
Array
(
    [result] => 1
    [message] => Data saved successfully!
    [data] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Jon D
                )

            [1] => Array
                (
                    [id] => 2
                    [name] => Michel N
                )

        )

    [apiKey] => Aie
)
## JSON
{"result":true,"message":"Data saved successfully!","data":[{"id":1,"name":"Jon D"},{"id":2,"name":"Michel N"}],"apiKey":"Aie"}

## Serialize 
a:4:{s:6:"result";b:1;s:7:"message";s:24:"Data saved successfully!";s:4:"data";a:2:{i:0;a:2:{s:2:"id";i:1;s:4:"name";s:5:"Jon D";}i:1;a:2:{s:2:"id";i:2;s:4:"name";s:8:"Michel N";}}s:6:"apiKey";s:3:"Aie";}

因此,添加索引到数组没有任何限制,无论何时需要任何东西,都可以使用 \ReturnDataFormat\Response::success()->ANY_INDEX(ASSIGN_DATA)->ANY_INDEX(ASSIGN_DATA) .. .. 因此,它非常灵活,可以用于任何类型的函数。

安装

php composer.phar sarphp/return-data-format

OR 

composer require sarphp/return-data-format