php 8.6项目若要求实体只能通过工厂创建,可以编写phpstan自定义rule检查new_节点。规则仅报告直接命名类的创建行为,并允许指定工厂内部使用;这种业务约束与类型检查、历史错误基线是不同的检查任务。

官方文档:The Rule interface
准备规则类的自动加载
安装phpstan/phpstan:^2,把App命名空间映射到src/并执行composer dump-autoload。假定项目已有App\Domain\Person与App\Domain\PersonFactory;将下面规则保存为src/Rules/PersonFactoryRule.php。
使用官方Model Context Protocol PHP SDK将PHP应用程序功能暴露为MCP工具、资源和提示,用于代理工作流。

官方文档:Registering the rule in the configuration
识别目标实体并返回有标识的错误
<?php
namespace App\Rules;
use PhpParser\Node;
use PHPStan\Analyser\Scope;
use PHPStan\Rules\Rule;
use PHPStan\Rules\RuleErrorBuilder;
/** @implements Rule<Node\Expr\New_> */
final class PersonFactoryRule implements Rule {
public function getNodeType(): string { return Node\Expr\New_::class; }
public function processNode(Node $node, Scope $scope): array {
if (!$node->class instanceof Node\Name ||
$scope->resolveName($node->class) !== \App\Domain\Person::class) {
return [];
}
if ($scope->isInClass() &&
$scope->getClassReflection()->getName() === \App\Domain\PersonFactory::class) {
return [];
}
return [RuleErrorBuilder::message('Use PersonFactory to create Person.')
->identifier('app.personFactory')->build()];
}
}注册并核对允许和禁止样例
# phpstan.neon
parameters:
level: 8
paths:
- src
rules:
- App\Rules\PersonFactoryRule运行vendor/bin/phpstan analyse。普通服务中直接new实体应出现app.personFactory,工厂中的同样调用不应出现该错误。再加入类别名与完全限定类名样例,确认名称解析一致。规则有意不处理new $class等动态构造和匿名类;要覆盖这些路径,需要另外设计类型分析,不能把这条规则宣称为所有绕过方式的防线。


















