入门篇 - RESTful API 实战

知识库
知识库文档
/tech-stacks/phalcon/tutorial/入门篇 - RESTful API 实战.md

文档

Phalcon 入门教程:RESTful API 实战

1. 背景

Phalcon 以 C 扩展形式提供极致性能。本教程带你构建 RESTful Product API,掌握 Phalcon 的 MVC 模式、模型和验证。

2. 前置概念

概念 说明
DI 容器 Phalcon 依赖注入是框架的核心
Loader Phalcon 的 PSR-4 自动加载器
Model ORM 模型,连接数据库
Validation 内置验证器链

3. 分步操作

步骤一:项目结构

my-api/
├── public/
│   └── index.php
├── app/
│   ├── controllers/
│   │   └── ProductController.php
│   ├── models/
│   │   └── Product.php
│   ├── config/
│   │   └── config.php
│   └── migrations/
└── .htrouter.php

步骤二:入口文件 public/index.php

<?php

use Phalcon\Autoload\Loader;
use Phalcon\Di\Di;
use Phalcon\Mvc\Application;
use Phalcon\Mvc\Router;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Phalcon\Mvc\Model\Manager as ModelsManager;

$loader = new Loader();
$loader->setDirectories(['../app/controllers/', '../app/models/']);
$loader->register();

$di = new Di();

// 数据库
$di->set('db', function () {
    return new Mysql([
        'host' => 'localhost',
        'username' => 'root',
        'password' => '',
        'dbname' => 'phalcon_api',
    ]);
});

// 路由
$di->set('router', function () {
    $router = new Router();
    $router->add('/api/products', [
        'controller' => 'product',
        'action' => 'list',
    ])->via(['GET']);
    $router->add('/api/products', [
        'controller' => 'product',
        'action' => 'create',
    ])->via(['POST']);
    $router->add('/api/products/{id}', [
        'controller' => 'product',
        'action' => 'show',
    ])->via(['GET']);
    $router->add('/api/products/{id}', [
        'controller' => 'product',
        'action' => 'update',
    ])->via(['PUT']);
    $router->add('/api/products/{id}', [
        'controller' => 'product',
        'action' => 'delete',
    ])->via(['DELETE']);
    return $router;
});

$di->set('modelsManager', new ModelsManager());

$app = new Application($di);
$app->handle($_SERVER['REQUEST_URI'])->send();

步骤三:Model app/models/Product.php

<?php

use Phalcon\Mvc\Model;

class Product extends Model
{
    public int $id;
    public string $name;
    public float $price;
    public string $category;
    public int $stock;

    public function initialize()
    {
        $this->setSource('products');
    }
}

步骤四:Controller app/controllers/ProductController.php

<?php

use Phalcon\Http\Response;
use Phalcon\Mvc\Controller;

class ProductController extends Controller
{
    public function listAction(): Response
    {
        $products = Product::find();
        return $this->response
            ->setContentType('application/json')
            ->setJsonContent($products->toArray());
    }

    public function createAction(): Response
    {
        $data = $this->request->getJsonRawBody(true);

        $product = new Product();
        $product->name = $data['name'];
        $product->price = $data['price'];
        $product->category = $data['category'] ?? '';
        $product->stock = $data['stock'] ?? 0;

        if ($product->save()) {
            return $this->response
                ->setContentType('application/json')
                ->setStatusCode(201)
                ->setJsonContent(['message' => 'Product created', 'id' => $product->id]);
        }

        return $this->response
            ->setContentType('application/json')
            ->setStatusCode(422)
            ->setJsonContent(['errors' => $product->getMessages()]);
    }

    public function showAction(int $id): Response
    {
        $product = Product::findFirst($id);
        if (!$product) {
            return $this->response->setStatusCode(404)->setJsonContent(['error' => 'Not found']);
        }
        return $this->response->setContentType('application/json')->setJsonContent($product->toArray());
    }

    public function updateAction(int $id): Response
    {
        $product = Product::findFirst($id);
        if (!$product) {
            return $this->response->setStatusCode(404)->setJsonContent(['error' => 'Not found']);
        }

        $data = $this->request->getJsonRawBody(true);
        $product->assign($data, ['name', 'price', 'category', 'stock']);
        $product->save();

        return $this->response->setContentType('application/json')->setJsonContent($product->toArray());
    }

    public function deleteAction(int $id): Response
    {
        $product = Product::findFirst($id);
        if ($product) {
            $product->delete();
            return $this->response->setStatusCode(204);
        }
        return $this->response->setStatusCode(404)->setJsonContent(['error' => 'Not found']);
    }
}

步骤五:数据库

CREATE TABLE products (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(128) NOT NULL,
    price DECIMAL(10,2) NOT NULL,
    category VARCHAR(64),
    stock INT DEFAULT 0
);

4. 验证

php -S localhost:8080 -t public/ .htrouter.php

curl -X POST http://localhost:8080/api/products \
  -H "Content-Type: application/json" \
  -d '{"name":"Phalcon Book","price":29.99,"category":"Books","stock":100}'

curl http://localhost:8080/api/products

5. 思考题

  1. Phalcon 的 ORM 和独立 Eloquent 有什么区别?
  2. 如何利用 Phalcon 的 C 扩展特性实现缓存优化?
  3. 如何在 Phalcon 中实现 JWT 认证中间件?

信息

路径
/tech-stacks/phalcon/tutorial/入门篇 - RESTful API 实战.md
更新时间
2026/5/31