PHP code example of goletter / hyperf-resource

1. Go to this page and download the library: Download goletter/hyperf-resource 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/ */

    

goletter / hyperf-resource example snippets


use Goletter\Resource\ApiResponse;

class UserService
{
    use ApiResponse;

    public function show(int $id)
    {
        $user = User::query()->findOrFail($id);

        // 自动解析 App\Resource\User 或 App\Resource\UserResource
        return $this->success($user);

        // 或显式指定
        // return $this->success($user, UserResource::class, 200, 'ok');
    }

    public function index()
    {
        $users = User::query()->paginate();

        return $this->collection($users, UserResource::class);
    }

    public function store()
    {
        // 业务失败:抛出 BusinessException(需在项目中注册异常处理器)
        $this->fail(422, '邮箱已被占用');
    }
}

namespace App\Resource;

use Goletter\Resource\Resource;

class UserResource extends Resource
{
    /** 单资源允许通过 ?��可与单资源不同) */
    protected static array $collectionAvailableIncludes = [
        'profile',
    ];

    public function toArray(): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'profile' => $this->whenLoaded('profile'),
            'roles' => $this->whenLoaded('roles'),
        ];
    }

    /** 可选:约束 
bash
php bin/hyperf.php vendor:publish goletter/hyperf-resource
http
GET /users/1?de=profile