PHPackages                             mertcanekiz/phpydantic - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. mertcanekiz/phpydantic

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

mertcanekiz/phpydantic
======================

A reflection-driven BaseModel inspired by pydantic for JSON Schema generation in PHP

v1.1.1(11mo ago)140MITPHPPHP &gt;=8.0

Since May 23Pushed 11mo ago1 watchersCompare

[ Source](https://github.com/mertcanekiz/phpydantic)[ Packagist](https://packagist.org/packages/mertcanekiz/phpydantic)[ RSS](/packages/mertcanekiz-phpydantic/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (1)Versions (4)Used By (0)

Phpydantic
==========

[](#phpydantic)

[![Packagist Version](https://camo.githubusercontent.com/37d6144e69d2d0c74d0a821d855de7eb11ce6f89df2430d09e1f63f184db5182/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d65727463616e656b697a2f7068707964616e7469632e737667)](https://packagist.org/packages/mertcanekiz/phpydantic)[![PHP Version](https://camo.githubusercontent.com/c8e8015f0146b3c0defbfd252b0ea5f3eab0eeb3bb747340e839ee3d6a45d277/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f7068702d762f6d65727463616e656b697a2f7068707964616e7469632e737667)](https://www.php.net/)[![License](https://camo.githubusercontent.com/610ad4c3469fc4f14b55fdef54ec0fdcb1f11690fc348252a4e48b13f5aee3c2/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6d65727463616e656b697a2f7068707964616e7469632e737667)](LICENSE)

A lightweight PHP library for generating JSON Schemas from PHP models, inspired by Python's Pydantic. Ideal for integrating with OpenAI structured outputs, function calling, or any other JSON-schema–driven tooling.

---

Table of Contents
-----------------

[](#table-of-contents)

- [Features](#features)
- [Requirements](#requirements)
- [Installation](#installation)
- [Usage](#usage)
    - [1. Defining Models](#1-defining-models)
    - [2. Generating JSON Schema](#2-generating-json-schema)
    - [3. OpenAI Structured Outputs](#3-openai-structured-outputs)
    - [4. Deserializing JSON Data](#4-deserializing-json-data)
- [API Reference](#api-reference)
- [Testing](#testing)
- [Contributing](#contributing)
- [License](#license)

---

Features
--------

[](#features)

- **Automatic Type Inference**: Infers JSON Schema types from PHP property types (`int`, `float`, `string`, `bool`).
- **Nullable Support**: Handles nullable types (e.g., `?string`) as `type: ["string", "null"]`.
- **Nested Models &amp; Arrays**: Supports nested `BaseModel` and arrays of models via `@var ModelName[]` annotations.
- **Property Descriptions**: Leverage `@Description` tags in docblocks to include descriptions in schemas.
- **Strict Mode**: Generate strict schemas for OpenAI function calling or JSON validation.

Requirements
------------

[](#requirements)

- PHP **8.0** or higher
- Composer

Installation
------------

[](#installation)

Install via Composer:

```
composer require mertcanekiz/phpydantic
```

Usage
-----

[](#usage)

### 1. Defining Models

[](#1-defining-models)

Extend `Phpydantic\BaseModel` and declare public properties. Use docblocks for metadata:

```
use Phpydantic\BaseModel;

class Step extends BaseModel
{
    /** @Description A detailed explanation for this step */
    public string $explanation;

    /** @Description The result or output of this step */
    public string $output;
}

class MathReasoning extends BaseModel
{
    /**
     * @var Step[]
     * @Description List of reasoning steps
     */
    public array $steps;

    /** @Description The final answer to the problem */
    public string $finalAnswer;
}
```

### 2. Generating JSON Schema

[](#2-generating-json-schema)

Use static methods to generate schema definitions:

```
// Returns schema as PHP array
$schemaArray = MathReasoning::schema();

// Returns pretty-printed JSON string
$schemaJson = MathReasoning::jsonSchema();
```

**Example JSON Schema**

```
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "MathReasoning",
  "type": "object",
  "properties": {
    "steps": {
      "type": "array",
      "items": { "$ref": "#/definitions/Step" }
    },
    "finalAnswer": { "type": "string" }
  },
  "required": ["steps", "finalAnswer"],
  "additionalProperties": false
}
```

### 3. OpenAI Structured Outputs

[](#3-openai-structured-outputs)

Generate schemas compatible with OpenAI function calling or JSON mode:

```
use OpenAI\OpenAI;

$client = OpenAI::client('YOUR_API_KEY');
$schema = MathReasoning::openAiSchema();

$response = $client->chat()->create([
    'model' => 'gpt-4o-2024-08-06',
    'messages' => [
        ['role' => 'system',  'content' => 'You are a helpful math tutor. Guide the user step by step.'],
        ['role' => 'user',    'content' => 'How can I solve 8x + 7 = -23?'],
    ],
    'response_format' => [
        'type' => 'json_schema',
        'json_schema' => $schema,
    ],
]);

$data = json_decode($response['choices'][0]['message']['content'], true);
// Access results: $data['steps'], $data['finalAnswer']
```

### 4. Deserializing JSON Data

[](#4-deserializing-json-data)

Use `fromJson` to create model instances from JSON strings:

```
$json = '{
    "steps": [
        {
            "explanation": "First, subtract 7 from both sides",
            "output": "8x = -30"
        },
        {
            "explanation": "Then divide both sides by 8",
            "output": "x = -3.75"
        }
    ],
    "finalAnswer": "x = -3.75"
}';

$reasoning = MathReasoning::fromJson($json);

// Access the data as PHP objects
foreach ($reasoning->steps as $step) {
    echo $step->explanation . "\n";
    echo $step->output . "\n";
}
echo "Final answer: " . $reasoning->finalAnswer;
```

The `fromJson` method handles:

- Nested model deserialization
- Arrays of models
- Type casting for primitive values
- Nullable properties
- JSON validation

API Reference
-------------

[](#api-reference)

MethodDescription`::schema(): array`Returns schema as a PHP array.`::jsonSchema(): string`Returns pretty-printed JSON schema.`::openAiSchema(): array`Wraps `schema()` for OpenAI function-calling compatibility.`::fromJson(string): static`Creates a model instance from a JSON string.Testing
-------

[](#testing)

Run PHPUnit tests:

```
composer test
```

Contributing
------------

[](#contributing)

Contributions are welcome! Please follow these steps:

1. Fork the repository
2. Create a new branch: `git checkout -b feature/YourFeature`
3. Commit your changes: `git commit -m 'Add new feature'`
4. Push to your branch: `git push origin feature/YourFeature`
5. Open a Pull Request

Ensure all tests pass and adhere to PSR-12 coding standards.

License
-------

[](#license)

This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details.

###  Health Score

29

—

LowBetter than 59% of packages

Maintenance50

Moderate activity, may be stable

Popularity9

Limited adoption so far

Community7

Small or concentrated contributor base

Maturity44

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~2 days

Total

3

Last Release

356d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/9316e51983dd5b4e364c29626c3a8e4602a6ebb21992439b7890291470c5fa09?d=identicon)[mertcanekiz](/maintainers/mertcanekiz)

---

Top Contributors

[![mertcanekiz](https://avatars.githubusercontent.com/u/2145468?v=4)](https://github.com/mertcanekiz "mertcanekiz (5 commits)")

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/mertcanekiz-phpydantic/health.svg)

```
[![Health](https://phpackages.com/badges/mertcanekiz-phpydantic/health.svg)](https://phpackages.com/packages/mertcanekiz-phpydantic)
```

###  Alternatives

[netzmacht/contao-leaflet-maps

Contao Leaflet maps integration

1111.0k1](/packages/netzmacht-contao-leaflet-maps)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
