PHP code example of maymeow / cakephp-api-resource

1. Go to this page and download the library: Download maymeow/cakephp-api-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/ */

    

maymeow / cakephp-api-resource example snippets



namespace App\Http\Resources;

use MayMeow\API\Resource;

class UserResource extends Resource
{
    public function toArray()
    {
        return [
            'id' => $this->id,
            'email' => $this->email,
            'created_at' => $this->created
        ];
    }
}


// ...
use App\Http\Resources\UserResource;
// ... class definition above
 public function index()
    {
        $query = $this->Users->find();

        $users = UserResource::collection($query);

        $this->set([
            'users' => $users,
            '_serialize' => ['users']
        ]);
    }

// BelongsTo, HasOne
$user = (new UserResource($userQuery))->get();

// HasMany, HasAndBelongsToMany
$users = UserResource::collection($query);

public function toArray()
    {
        return [
            'id' => $this->id,
            'raw_body' => $this->text,
            'html_body' => function ($q) {
                return (new Parsedown())->$text($q->text); // text is parsed before data is send to client
            }
        ];
    }

public function toArray()
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'profile' => function ($q) {
                return (new ProfileResource($q->profile))->get(); // single entity (belongsTo, HasOne)
            },
            'posts' => function ($q) {
                return PostResource::collection($q->posts); // collection of resources (hasMany)
            }
        ];
    }