承接 syncfly/python-in-php 相关项目开发

从需求分析到上线部署,全程专人跟进,保证项目质量与交付效率

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

syncfly/python-in-php

Composer 安装命令:

composer require syncfly/python-in-php

包简介

"Python-In-PHP" allows you to use any Python packages directly in PHP, as if they were native PHP classes. This PHP-Python bridge comes with built-in package manager, which is integrated directly into Composer

README 文档

README

⏳ The project is currently under active development. It is still in the alpha stage, but it is already working.
⭐️ Star the repository to support the project and follow us

Python-in-PHP

The Python-in-PHP library allows you to easily use any Python packages as if they were native PHP packages 🐘

🔥 Fully use artificial intelligence frameworks for AI models inference or training directly in PHP!
You can run AI models with libraries like transformers, torch, vllm, numpy, etc. in your PHP project with PHP syntax.

✅ Environment with Python is installed automatically with Composer.

✅ Any Python packages are installed via Composer with a built-in package manager.

✅ Automatic PHPDoc generation for code completion in IDEs for any Python packages.

Python-in-PHP

System requirements

Requirement Version
PHP ≥ 8.2
OS Linux, macOS, Windows
Architecture x86_64, arm64

The library automatically downloads and installs the uv tool and a Python environment on first use. No manual Python installation is required.

Note for Windows users: symlink creation may require Administrator privileges or Developer Mode enabled.

Installation

composer require syncfly/python-in-php

Answer yes when Composer asks to activate the plugin. This will:

  1. Download uv (~10 MB) into vendor/bin/
  2. Create a Python virtual environment in vendor/bin/python-in-php/
  3. Generate PHPDoc stubs for installed packages in py/

Quick start

After installation, Python's standard library is available immediately:

<?php

use py\json;
use py\datetime\datetime;

echo json::dumps(['hello' => 'world']); // {"hello": "world"}
echo datetime::now()->isoformat();       // 2024-01-15T12:34:56.789012

Install additional packages, then use them:

composer pip install numpy
<?php

use py\numpy;

$arr = numpy::array([1, 2, 3, 4, 5]);
echo numpy::mean($arr); // 3.0

For a complete Python → PHP syntax reference (kwargs, iteration, dicts, context managers, exceptions, and more) see docs/usage.md.

Package manager

The built-in package manager wraps uv pip with Composer integration.

# Install a package
composer pip install requests

# Install a specific version
composer pip install "numpy:^1.24"

# Install with a custom PyPI index (e.g. PyTorch with ROCm)
composer pip install torch --index-url https://download.pytorch.org/whl/rocm6.3

# Install a local package from a directory
composer pip install /path/to/my-local-package

# Uninstall a package
composer pip uninstall requests

# Upgrade a package
composer pip install --upgrade numpy

Installed packages and their sources are saved to composer.json under extra.python-in-php.packages and are re-installed automatically on the next composer install.

Configuration

Configure Python-in-PHP in composer.json:

{
    "extra": {
        "python-in-php": {
            "python-version": "3.12",
            "packages": [
                {"name": "requests", "version": "*"},
                {"name": "numpy",    "version": "^1.24"},
                {
                    "name":      "torch",
                    "version":   "2.7.0+rocm6.3",
                    "index-url": "https://download.pytorch.org/whl/rocm6.3"
                },
                {
                    "name":    "my-local-lib",
                    "version": "*",
                    "path":    "/home/user/my-local-lib"
                }
            ]
        }
    }
}
Key Type Default Description
python-version string "3.12" Python version to install
packages array [] List of packages to install
packages[].name string Package name
packages[].version string "*" Version constraint (PEP 440 or *)
packages[].index-url string Custom PyPI index URL for this package
packages[].path string Absolute path to a local package directory

Using Python objects

Python objects are returned as PythonObject instances that support method calls and attribute access:

<?php

use py\requests;

$response = requests::get('https://httpbin.org/json');
$data = $response->json();  // method call
echo $response->status_code; // attribute access

Context managers

Use PythonBridge::with() to work with Python context managers:

<?php

use Python_In_PHP\PythonBridge;
use py\open;

$bridge = PythonBridge::startOrGetRunning();
$file = $bridge->importModule('builtins');
// ...

Exceptions

Python exceptions are thrown as Python_In_PHP\PythonException:

<?php

use Python_In_PHP\PythonException;
use py\json;

try {
    json::loads('invalid json');
} catch (PythonException $e) {
    echo $e->getMessage();   // "Python error: Expecting value: line 1..."
    echo $e->traceback;      // full Python traceback
}

AI model example

<?php

use py\transformers;
use py\torch;

$model_name = 'google/gemma-3-4b-it';

$tokenizer = transformers\AutoTokenizer::from_pretrained($model_name);

$model = transformers\AutoModelForCausalLM::from_pretrained(
    $model_name,
    torch_dtype: torch::$bfloat16,
    device_map: "auto"
);

$messages = [
    ['role' => 'user', 'content' => 'Why PHP is great?']
];

$input_ids = $tokenizer->apply_chat_template(
    $messages,
    return_tensors: 'pt',
    add_generation_prompt: true
);

$outputs = $model->generate($input_ids, max_new_tokens: 2048);
$result = $tokenizer->decode($outputs[0], skip_special_tokens: true);

Or simpler with transformers pipeline:

<?php

use py\transformers;
use py\torch;

$pipe = transformers\pipeline(
    'text-generation',
    model: 'google/gemma-3-4b-it',
    torch_dtype: torch::$bfloat16,
    device_map: 'auto'
);

$messages = [['role' => 'user', 'content' => 'Why PHP is great?']];
$output = $pipe($messages, max_new_tokens: 2048);
$result = end($output[0]['generated_text'])['content'];

Troubleshooting

uv download fails / no internet access

The library downloads uv automatically during composer install. If your environment has no internet access, install uv manually before running Composer:

  • macOS/Linux: curl -Ls https://astral.sh/uv/install.sh | sh
  • Windows: winget install astral-sh.uv

Then set the UV_BIN env variable or ensure uv is in your PATH.

"Class py\xxx not found"

PHPDoc stubs are generated in vendor/syncfly/python-in-php/py/. Run composer install to regenerate them after adding new packages.

"Python script was not found"

The Python binary symlink is missing. Remove vendor/bin/python-in-php/ and re-run composer install.

Python server does not start within 30 seconds

Check that the Python binary works: vendor/bin/python-in-php/python --version. If it fails, remove the environment and reinstall: rm -rf vendor/bin/python-in-php && composer install.

Permission denied on Windows

Symlink creation requires Administrator privileges or Windows Developer Mode. Run your terminal as Administrator, or enable Developer Mode in Windows Settings → System → Developer options.

License

This project is distributed under a source-available license.

Allowed:

  • Using the package in your projects, including commercial ones ✅
  • Making changes and submitting pull requests to this repository

Prohibited:

  • Creating public forks or distributing the project under your own name
  • Uploading the code (modified or original) anywhere else

✅ All contributions are accepted through pull requests to the official repository

Attribution:

  • Attribution notice is required for software with publicly available source code

See LICENSE.md for full details.

syncfly/python-in-php 适用场景与选型建议

syncfly/python-in-php 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 54 次下载、GitHub Stars 达 2, 最近一次更新时间为 2026 年 03 月 30 日, 在 PHP 生态内属于活跃度较高的组件。

我们在过去多个企业项目中使用过 syncfly/python-in-php 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。

围绕 syncfly/python-in-php 我们能提供哪些服务?
定制开发 / 二次开发

基于 syncfly/python-in-php 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。

BUG 修复 & 性能优化

线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。

项目外包 & 长期维护

承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。

yvsm@zunyunkeji.com QQ:316430983 微信:yvsm316 西安尊云信息科技 · 专注 PHP / Go / 分布式系统研发

统计信息

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

GitHub 信息

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

其他信息

  • 授权协议: proprietary
  • 更新时间: 2026-03-30