PHP code example of invinbg / hyperf-response

1. Go to this page and download the library: Download invinbg/hyperf-response library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

invinbg / hyperf-response example snippets

 bin/hyperf.php vendor:publish invinbg/hyperf-response

// 如果需要同步HttpStatus这里设置为true
'withHttpStatus' => false, // sync httpStatus
// 自定义response data 中的键名映射
'data' => [                // data mapping
    'code' => 'code',
    'data' => 'data',
    'message' => 'message'
]

// config/autoload/dependencies.php
return [
    Hyperf\HttpServer\Contract\ResponseInterface::class => Invinbg\HyperfResponse\ResponseFactory::class,
];

namespace App\Controller;

use Invinbg\HyperfResponse\Contract\ResponseInterface;

class DemoController
{
    public function response(ResponseInterface $response)
    {
        $user = User::query()->first();
        $data = [
            // ...额外的数据
        ];
        $extra = [
            // ...扩展数据
        ];
        // withData可以链式追加数据
        return $response->withData($user)->withData($data)->withExtraData($extra)->success();
    }
}

namespace App\Controller;

use Hyperf\Di\Annotation\Inject;
use Invinbg\HyperfResponse\Contract\ResponseInterface;

class DemoController
{
    /**
     * @Inject
     * @var ResponseInterface
     */
    protected $response;

    public function response()
    {
        return $this->response->withCode(401)->error('unauthorized.');
    }
}