php 8.6独立项目可以使用symfony dependencyinjection组件注册服务,把依赖通过构造函数传入业务类,再编译和导出容器供入口复用。这样无需引入整个symfony框架。容器负责对象装配,业务对象仍依赖接口;以下示例使用组件现有api,不是php 8.6新增加的语法。
准备组件和业务类
在项目实际使用的PHP 8.6环境执行Composer,保留锁文件;不要忽略平台要求。下面把类定义和装配放在同一文件便于说明,实际项目可按PSR-4拆入src目录。
composer require symfony/dependency-injection:^8.1 composer check-platform-reqs
<?php
require __DIR__.'/vendor/autoload.php';
interface Formatter { public function format(string $text): string; }
final class PlainFormatter implements Formatter {
public function format(string $text): string { return trim($text); }
}
final class Notice {
public function __construct(private Formatter $formatter) {}
public function render(string $text): string {
return $this->formatter->format($text);
}
}
Symfony官方文档中的服务注册和依赖引用示例
显式注册后编译
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;
use Symfony\Component\DependencyInjection\Dumper\PhpDumper;
$container = new ContainerBuilder();
$container->register('formatter', PlainFormatter::class);
$container->register('notice', Notice::class)
->addArgument(new Reference('formatter'))->setPublic(true);
$container->compile();
echo $container->get('notice')->render(' ready '), PHP_EOL;
$php = (new PhpDumper($container))->dump(['class' => 'AppCompiledContainer']);
if (!is_dir(__DIR__.'/var')) { mkdir(__DIR__.'/var', 0700, true); }
$temporary = tempnam(__DIR__.'/var', 'container-');
if ($temporary === false) { throw new RuntimeException('Cannot create cache file'); }
try {
if (file_put_contents($temporary, $php) === false
|| !rename($temporary, __DIR__.'/var/container.php')) {
throw new RuntimeException('Cannot publish container cache');
}
} finally { if (is_file($temporary)) { unlink($temporary); } }notice作为入口可读取服务显式设为public;内部formatter可保持私有并由编译过程优化。不要在每个业务方法里获取容器,也不要在编译后再改参数。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

Symfony官方文档中的编译容器导出示例
复用缓存并处理配置变更
后续请求先加载业务类的自动加载文件,再require已生成的var/container.php,实例化AppCompiledContainer并获取notice。部署时应先生成新缓存并做启动检查,再切换代码;服务定义或类构造参数改变后必须重新构建。缓存属于可信PHP代码,不能写入用户上传目录,也不能把未经信任的类名注册成服务。示例的同目录临时文件改名面向本地文件系统,跨文件系统或共享存储需要采用其自身的发布机制。


















