You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 

114 lines
3.2 KiB

<?php
declare(strict_types=1);
/**
* ScoreStrategyFactory.php
* Created by PhpStorm.
* Date: 2026/10/17
* Time: 09:40
* Author: qian.guo
* E-mail: yiyezhiqiutel@gmail.com
*/
namespace app\service\score;
use app\service\score\exception\UnsupportedStrategyException;
/**
* 评分策略工厂
* 设计说明:
* - 按 alias 实例化并缓存。策略是无状态的纯计算对象,重复 new 只是浪费
* 若将来某个策略需要持有状态,必须先去掉这个缓存并同步改掉「纯函数」的约定
* - 注册表在构造时整体校验,配置错误在启动阶段就暴露
* 否则要等到用户答完 60 题提交时才炸,而那时已经产生了无效作答
*/
class ScoreStrategyFactory
{
// 策略配置
private $config;
// alias => 实现类
private $strategy_map = [];
// 已实例化缓存
private $instance_list = [];
public function __construct($config)
{
$this->config = $config;
$this->strategy_map = (array) ($config['strategies'] ?? []);
$this->checkRegistry();
}
/**
* 创建策略实例
* createStrategy
* @param string $alias 策略标识,为空取默认策略
* @return ScoreStrategyInterface
*/
public function createStrategy($alias = '')
{
if ($alias === '') {
$alias = (string) ($this->config['default'] ?? '');
}
if (empty($this->strategy_map[$alias])) {
if (!empty($this->config['strict'])) {
throw new UnsupportedStrategyException($alias, $this->getAliasList());
}
// strict = false 才允许回退,这是给本地调试开的口子,生产必须保持 strict
$alias = (string) ($this->config['default'] ?? '');
}
if (empty($this->instance_list[$alias])) {
$class = $this->strategy_map[$alias];
$options = (array) ($this->config['options'] ?? []);
$this->instance_list[$alias] = new $class($options);
}
return $this->instance_list[$alias];
}
/**
* 获取已注册的策略标识列表
* getAliasList
* @return array
*/
public function getAliasList()
{
return array_keys($this->strategy_map);
}
/**
* 校验策略注册表
* checkRegistry
* @return void
*/
private function checkRegistry()
{
foreach ($this->strategy_map as $alias => $class) {
if (!class_exists($class)) {
throw new UnsupportedStrategyException($alias, $this->getAliasList());
}
$options = (array) ($this->config['options'] ?? []);
$probe = new $class($options);
if (!($probe instanceof ScoreStrategyInterface)) {
throw new UnsupportedStrategyException($alias, $this->getAliasList());
}
// alias 与 getName() 不一致会让落库的 strategy 字段对不上配置,必须拦住
if ($probe->getName() !== $alias) {
throw new UnsupportedStrategyException(
$alias . '(getName() 返回 ' . $probe->getName() . ',两者必须一致)',
$this->getAliasList()
);
}
}
}
}