PHP code example of vudp / cakephp-rest-api

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

    

vudp / cakephp-rest-api example snippets


$this->addPlugin('RestApi');



return [
    'ApiRequest' => [
        'debug' => false,
        'responseType' => 'json',
        'xmlResponseRootNode' => 'response',
    	'responseFormat' => [
            'statusKey' => 'status',
            'statusOkText' => 'OK',
            'statusNokText' => 'NOK',
            'resultKey' => 'result',
            'messageKey' => 'message',
            'defaultMessageText' => 'Empty response!',
            'errorKey' => 'error',
            'defaultErrorText' => 'Unknown request!'
        ],
        'log' => false,
	'logOnlyErrors' => true,
        'logOnlyErrorCodes' => [404, 500],
        'jwtAuth' => [
            'enabled' => true,
            'cypherKey' => 'R1a#2%dY2fX@3g8r5&s4Kf6*sd(5dHs!5gD4s',
            'tokenAlgorithm' => 'HS256'
        ],
        'cors' => [
            'enabled' => true,
            'origin' => '*',
            'allowedMethods' => ['GET', 'POST', 'OPTIONS'],
            'allowedHeaders' => ['Content-Type, Authorization, Accept, Origin'],
            'maxAge' => 2628000
        ]
    ]
];

Authorization: Bearer [token]


return [
    'ApiRequest' => [
        'cors' => [
            'enabled' => true,
            'origin' => '*',
            'allowedMethods' => ['GET', 'POST', 'OPTIONS'],
            'allowedHeaders' => ['Content-Type, Authorization, Accept, Origin'],
            'maxAge' => 2628000
        ]
    ]
];


return [
    'ApiRequest' => [
        'cors' => [
            'enabled' => true,
            'origin' => ['localhost', 'www.example.com', '*.example.com'],
            'allowedMethods' => ['GET', 'POST', 'OPTIONS'],
            'allowedHeaders' => ['Content-Type, Authorization, Accept, Origin'],
            'maxAge' => 2628000
        ]
    ]
];


return [
    'ApiRequest' => [
        'log' => true,
        // other config options
    ]
];


declare(strict_types=1);
namespace App\Controller;

use RestApi\Controller\ApiController;
use RestApi\Utility\JwtToken;

/**
 * AuthController Controller
 *
 */
class AuthController extends ApiController
{
    /**
     * Login method
     *
     * @return void
     */
    public function login()
    {
        $this->request->allowMethod('post');
        $this->loadModel('Users');
        $entity = $this->Users->newEntity($_REQUEST, ['validate' => 'LoginApi']);

        if ($entity->getErrors()) {
                $this->httpStatusCode = 400;
                $this->apiResponse['message'] = 'Validation failed.';
                foreach ($entity->errors() as $field => $validationMessage) {
                    $this->apiResponse['error'][$field] = $validationMessage[key($validationMessage)];
                }
            } else {
                $user = $this->Users->find()
                    ->where([
                        'email' => $entity->email,
                        'password' => md5($entity->password),
                        'status' => 1
                    ])
                    ->first();
        if (empty($user)) {
                    $this->httpStatusCode = 403;
                    $this->apiResponse['error'] = 'Invalid email or password.';
        return;
                }
        $payload = ['email' => $user->email, 'name' => $user->name];
        $this->apiResponse['token'] = JwtToken::generateToken($payload);
                $this->apiResponse['message'] = 'Logged in successfully.';
        unset($user);
                unset($payload);
            }
    }

        /**
     * Register method
     *
     * Returns a token on successful registration
     *
     * @return void
     */
    public function register()
    {
        $this->request->allowMethod('post');

        $this->loadModel('Users');

        $user = $this->Users->newEntity($_REQUEST);

        try {
            if ($this->Users->save($user)) {

                $this->apiResponse['message'] = 'Registered successfully.';
                $payload = ['email' => $user->email, 'name' => $user->name];
                $this->apiResponse['token'] = JwtToken::generateToken($payload);
            } else {
                $this->httpStatusCode = 400;
                $this->apiResponse['message'] = 'Unable to register user.';
                if ($user->errors()) {
                    $this->apiResponse['message'] = 'Validation failed.';
                    foreach ($user->errors() as $field => $validationMessage) {
                        $this->apiResponse['error'][$field] = $validationMessage[key($validationMessage)];
                    }
                }
            }
        } catch (Exception $e) {
            $this->httpStatusCode = 400;
            $this->apiResponse['message'] = 'Unable to register user.';
        }

        unset($user);
        unset($payload);
    }
}


declare(strict_types=1);

namespace App\Model\Table;

use Cake\ORM\Query;
use Cake\ORM\RulesChecker;
use Cake\ORM\Table;
use Cake\Validation\Validator;
use Cake\Event\Event;
use Cake\Datasource\EntityInterface;
use ArrayObject;

/**
 * Users Model
 *
 * @method \App\Model\Entity\User newEmptyEntity()
 * @method \App\Model\Entity\User newEntity(array $data, array $options = [])
 * @method \App\Model\Entity\User[] newEntities(array $data, array $options = [])
 * @method \App\Model\Entity\User get($primaryKey, $options = [])
 * @method \App\Model\Entity\User findOrCreate($search, ?callable $callback = null, $options = [])
 * @method \App\Model\Entity\User patchEntity(\Cake\Datasource\EntityInterface $entity, array $data, array $options = [])
 * @method \App\Model\Entity\User[] patchEntities(iterable $entities, array $data, array $options = [])
 * @method \App\Model\Entity\User|false save(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\User saveOrFail(\Cake\Datasource\EntityInterface $entity, $options = [])
 * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface|false saveMany(iterable $entities, $options = [])
 * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface saveManyOrFail(iterable $entities, $options = [])
 * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface|false deleteMany(iterable $entities, $options = [])
 * @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface deleteManyOrFail(iterable $entities, $options = [])
 *
 * @mixin \Cake\ORM\Behavior\TimestampBehavior
 */
class UsersTable extends Table
{
    /**
     * Initialize method
     *
     * @param array $config The configuration for the Table.
     * @return void
     */
    public function initialize(array $config): void
    {
        parent::initialize($config);

        $this->setTable('users');
        $this->setDisplayField('name');
        $this->setPrimaryKey('id');
        $this->addBehavior('Timestamp');
    }

    /**
     * Default validation rules.
     *
     * @param \Cake\Validation\Validator $validator Validator instance.
     * @return \Cake\Validation\Validator
     */
    public function validationDefault(Validator $validator): Validator
    {

        $validator
            ->allowEmptyString('id', null, 'create');

        $validator
            ->scalar('name')
            ->maxLength('name', 255)
            ->