Phalcon3のマイクロアプリケーションでDBインサートできるAPIを作成する

Phalcon3のマイクロアプリケーションでDBインサートできるAPIを作成する

Select文の発行は完了しましたので、Insert文をHTTPのPOSTメソッドで発行するAPIを作成してみます。

InsertやUpdate操作の際はモデルクラスで設定したバリデーションが効きます。

models\Empuser.phpは一旦以下のようにします。


<?php
namespace App\Models;
use Phalcon\Validation;
class Empuser extends \Phalcon\Mvc\Model
{
public function validation()
{
// とりあえずこれだけ
$validator = new Validation();
}
}
view raw

gistfile1.txt

hosted with ❤ by GitHub

POSTでリクエストボディを渡す

POSTメソッドの場合は一般的にはパスパラメータもしくはリクエストボディを使います。

今回はリクエストボディで値を渡します。以下JSON形式で渡します。


{
"id":10,
"firstname":"test1",
"lastname":"test2",
"age":20
}
view raw

gistfile1.txt

hosted with ❤ by GitHub

この値をphpでは以下のように受け取ることができます。$appは\Phalcon\Mvc\Microのインスタンスです。

$app->request->getJsonRawBody();
$id = $body->id; // id
$firstname = $body->firstname; // firstname
$lastname = $body->lastname; // lastname
$age = $body->age; // age

これをpostメソッドの第二引数の匿名関数で取得します。


function () use ($app) {
$body = $app->request->getJsonRawBody(); // リクエストボディを受け取る
$status = $app
->modelsManager
->executeQuery(
'INSERT INTO App\Models\Empuser (id, firstname, lastname, age) VALUES ' .
'(:id:, :firstname:, :lastname:, :age:) ',
[
'id' => $body->id,
'firstname' => $body->firstname,
'lastname' => $body->lastname,
'age' => $body->age
]
);
}
view raw

gistfile1.txt

hosted with ❤ by GitHub

Phalcon\Http\Responseクラスでレスポンスを生成します。全体的なindex.phpは以下になります。


<?php
declare(strict_types=1);
error_reporting(E_ALL);
// オートローダー設定
$loader = new Phalcon\Loader();
$loader->registerNamespaces(
[
'App\Models' => __DIR__ . '/models/',
]
);
$loader->register();
// DB接続情報
$container = new Phalcon\Di\FactoryDefault();
$container->set(
'db',
function () {
return new Phalcon\Db\Adapter\Pdo\Postgresql(
[
'host' => 'localhost',
'port' => 5432,
'username' => 'postgres',
'password' => 'confrage',
'dbname' => 'postgres'
]
);
}
);
$app = new \Phalcon\Mvc\Micro($container); // DB情報を引数で渡す必要がある
$app->post(
'/api/v2/createRecod',
function () use ($app) {
$body = $app->request->getJsonRawBody(); // リクエストボディを受け取る
$status = $app
->modelsManager
->executeQuery(
'INSERT INTO App\Models\Empuser (id, firstname, lastname, age) VALUES ' .
'(:id:, :firstname:, :lastname:, :age:) ',
[
'id' => $body->id,
'firstname' => $body->firstname,
'lastname' => $body->lastname,
'age' => $body->age
]
);
$response = new Phalcon\Http\Response();
if ($status->success() === true) {
$response->setStatusCode(201, 'Created');
$response->setJsonContent(
[
'status' => 'OK',
'data' => ''
]
);
} else {
$response->setStatusCode(409, 'Conflict');
$errors = [];
foreach ($status->getMessages() as $message) {
$errors[] = $message->getMessage();
}
$response->setJsonContent(
[
'status' => 'ERROR',
'messages' => $errors,
]
);
}
return $response;
}
);
$app->handle(
$_SERVER["REQUEST_URI"]
);
view raw

gistfile1.txt

hosted with ❤ by GitHub
GitHub - takahashi-h5/phalcon-insert
Contribute to takahashi-h5/phalcon-insert development by creating an account on GitHub.

コメント

タイトルとURLをコピーしました