定制 ap-lib/openapi-plus 二次开发

按需修改功能、优化性能、对接业务系统,提供一站式技术支持

邮箱:yvsm@zunyunkeji.com | QQ:316430983 | 微信:yvsm316

ap-lib/openapi-plus

Composer 安装命令:

composer require ap-lib/openapi-plus

包简介

README 文档

README

MIT License

A PHP specification system for generating OpenAPI 3.1-compatible schemas from PHP classes, enhanced with extra features and macros.

Compatible with: OpenAPI 3.1 Specification

Highlights

  • Seamlessly integrates with PHP attributes and validators
  • Supports schema generation from constructors or properties
  • Allows macro extensions for enums and custom types

Installation

composer require ap-lib/openapi-plus

Requirements

  • PHP 8.3 or higher

Getting Started

1. Initialize the OpenAPIPlus Loader

Create a loader class to configure the system with your custom object definitions and enums:

class OpenAPI
{
    private static OpenAPIPlus $openAPIPlus;

    public static function get(): OpenAPIPlus
    {
        return self::$openAPIPlus ??= new OpenAPIPlus([
            new ImplementedObject(),
        ]);
    }
}

2. Use Traits to Generate Schemas

Choose between generating schemas from constructor arguments or class properties.

Constructor-Based Schema

trait ByConstructorOpenAPI
{
    public static function openAPI(): array
    {
        return OpenAPI::get()->scheme(
            (new \ReflectionClass(static::class))
                ->getConstructor()
                ->getParameters()
        );
    }
}

Property-Based Schema

trait PropertiesOpenAPI
{
    public static function openAPI(): array
    {
        return OpenAPI::get()->scheme(
            (new \ReflectionClass(static::class))
                ->getProperties()
        );
    }
}

3. Annotate and Generate

Apply the trait to your class and use attribute-based validators (e.g. from ap-lib/validator):

Example how to implement OpenAPIModificator: https://github.com/ap-lib/validator/blob/main/src/String/Email.php

class SignUpBody
{
    use PropertiesOpenAPI;

    #[LabelCompany]
    public string $company_name;

    #[Email]
    public string $email;

    #[Password(min_length: 8)]
    public string $password;

    #[Timezone]
    public ?string $timezone = null;
}

Generate the OpenAPI schema:

echo json_encode(
    value: SignUpBody::openAPI(),
    flags: JSON_PRETTY_PRINT
);

Example Output

{
  "type": "object",
  "properties": {
    "company_name": {
      "type": "string",
      "minLength": 1,
      "maxLength": 32
    },
    "email": {
      "type": "string",
      "format": "email"
    },
    "password": {
      "type": "string",
      "format": "password"
    },
    "timezone": {
      "type": ["string", "null"],
      "default": null,
      "maxLength": 30
    }
  },
  "required": [
    "company_name",
    "email",
    "password"
  ]
}

统计信息

  • 总下载量: 20
  • 月度下载量: 0
  • 日度下载量: 0
  • 收藏数: 0
  • 点击次数: 0
  • 依赖项目数: 1
  • 推荐数: 0

GitHub 信息

  • Stars: 0
  • Watchers: 0
  • Forks: 0
  • 开发语言: PHP

其他信息

  • 授权协议: MIT
  • 更新时间: 2025-08-06