PHP code example of hiromi2424 / api

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

    

hiromi2424 / api example snippets


Router::prefix('api', function ($routes) {
    // ルート定義
});

$components = [
	'Api.Api'
];
// または
$this->loadComponent('Api.Api');
  

/**
 * signup api
 *
 * @return void
 */
public function signup()
{
	$this->request->onlyAllow('post');
	$this->Api->recordMap = [
		'User' => [
			'name',
			'email',
			'password',
		],
	];
	$params = $this->Api->

/**
 * login api
 *
 * @return void
 */
public function login()
{
	$this->request->onlyAllow('post');

	$data = $this->Api->nSet(['Login']);
	$this->User->create($this->request->data);
	$loggedIn = $this->User->validates() && $this->Auth->login();
	if ($loggedIn) {
		$this->Api->success();
	} else {
		$this->Api->raiseValidationErrors();
	}
}

App::uses('LackParametersException', 'Api.Error');

Class CommentsController extends AppController {

	/**
	 * index api
	 *
	 * @return void
	 */
	public function api_index($postId = null) {
		$this->request->onlyAllow('get');
		if ($postId === null) {
			throw new LackParametersException('postId');
		}

		$this->Api->recordMap = [
			'Comment' => [
				'id',
				'body',
				'created',
				'updated',
			],
			'User' => [
				'_wrap' => 'user',
				'id',
				'name',
			],
		];

		$this->Comment->create();
		$this->Comment->set('post_id', $postId);
		if (!$this->Comment->validates(['fieldList' => ['post_id']])) {
			$this->Api->recordMap = ['Comment' => ['post_id']];
			return $this->Api->processValidationErrors();
		}

		$limit = 20;
		$page = $this->Api->collectParam('page');
		$page = $page ? (int)$page : 1;
		$contain = ['User'];
		$comments = $this->Comment->findAllByPostId($postId, compact('limit', 'page', 'contain'));

		foreach ($comments as &$comment) {
			$comment = $this->Api->recordToParams($comment);
		}
		$this->Api->success(compact([
			'page',
			'limit',
			'comments',
		]));
	}

}