Hướng Dẫn Tạo API RESTful Với Phalcon Framework
1
phút đọc
Trong bài viết này, chúng ta sẽ tạo một API RESTful đơn giản để quản lý thông tin người dùng với Phalcon 5, sử dụng MySQL làm cơ sở dữ liệu.
1. Cấu Hình Cơ Sở Dữ Liệu
1.1. Tạo database MySQL
CREATE DATABASE phalcon_api;
USE phalcon_api;
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(100) NOT NULL,
email VARCHAR(100) UNIQUE NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);
1.2. Cấu hình database trong Phalcon
Mở file config/config.php
và chỉnh sửa:
return [
'database' => [
'adapter' => 'Mysql',
'host' => '127.0.0.1',
'username' => 'root',
'password' => '',
'dbname' => 'phalcon_api',
'charset' => 'utf8',
],
];
2. Tạo Model
Tạo file app/models/Users.php
:
namespace App\Models;
use Phalcon\Mvc\Model;
class Users extends Model
{
public $id;
public $name;
public $email;
public $created_at;
public function initialize()
{
$this->setSource("users");
}
}
3. Tạo Controller API
Tạo file app/controllers/UserController.php
:
namespace App\Controllers;
use App\Models\Users;
use Phalcon\Mvc\Controller;
use Phalcon\Http\Response;
class UserController extends Controller
{
// Lấy danh sách users
public function index()
{
$users = Users::find();
return $this->responseJson($users);
}
// Lấy thông tin user theo ID
public function show($id)
{
$user = Users::findFirst($id);
if (!$user) {
return $this->responseJson(["message" => "User not found"], 404);
}
return $this->responseJson($user);
}
// Tạo user mới
public function store()
{
$data = $this->request->getJsonRawBody();
$user = new Users();
$user->name = $data->name;
$user->email = $data->email;
if ($user->save()) {
return $this->responseJson(["message" => "User created"], 201);
} else {
return $this->responseJson(["message" => "Error creating user"], 400);
}
}
// Cập nhật user
public function update($id)
{
$user = Users::findFirst($id);
if (!$user) {
return $this->responseJson(["message" => "User not found"], 404);
}
$data = $this->request->getJsonRawBody();
$user->name = $data->name ?? $user->name;
$user->email = $data->email ?? $user->email;
if ($user->save()) {
return $this->responseJson(["message" => "User updated"]);
} else {
return $this->responseJson(["message" => "Error updating user"], 400);
}
}
// Xóa user
public function delete($id)
{
$user = Users::findFirst($id);
if (!$user) {
return $this->responseJson(["message" => "User not found"], 404);
}
if ($user->delete()) {
return $this->responseJson(["message" => "User deleted"]);
} else {
return $this->responseJson(["message" => "Error deleting user"], 400);
}
}
// Helper function để trả JSON response
private function responseJson($data, $status = 200)
{
$response = new Response();
$response->setStatusCode($status);
$response->setContentType("application/json", "UTF-8");
$response->setJsonContent($data);
return $response;
}
}
4. Định Tuyến API (Routes)
Mở app/routes.php
và thêm các route:
use Phalcon\Mvc\Micro;
use App\Controllers\UserController;
$app = new Micro($di);
// Danh sách users
$app->get('/api/users', [new UserController(), 'index']);
// Chi tiết user
$app->get('/api/users/{id}', [new UserController(), 'show']);
// Tạo user
$app->post('/api/users', [new UserController(), 'store']);
// Cập nhật user
$app->put('/api/users/{id}', [new UserController(), 'update']);
// Xóa user
$app->delete('/api/users/{id}', [new UserController(), 'delete']);
$app->handle($_SERVER["REQUEST_URI"]);
5. Chạy API Và Kiểm Tra
5.1. Khởi động server
php -S localhost:8000 -t public
5.2. Kiểm tra API với Postman hoặc cURL
Lấy danh sách users:
curl -X GET http://localhost:8000/api/users
Tạo user mới:
curl -X POST http://localhost:8000/api/users \
-H "Content-Type: application/json" \
-d '{"name": "Nguyen Minh Tuan", "email": "tuan@example.com"}'
Cập nhật user:
curl -X PUT http://localhost:8000/api/users/1 \
-H "Content-Type: application/json" \
-d '{"name": "Tuan Updated"}'
Xóa user:
curl -X DELETE http://localhost:8000/api/users/1
6. Kết Luận
Chúng ta đã tạo thành công một API RESTful với Phalcon, bao gồm các chức năng CRUD cơ bản. Phalcon giúp tối ưu hiệu suất, giảm tiêu thụ tài nguyên và cung cấp nhiều công cụ hỗ trợ mạnh mẽ. Nếu bạn cần một API nhanh và nhẹ, Phalcon là lựa chọn tuyệt vời! 🚀