0

原帖:https ://github.com/symfony/symfony/discussions/43960

我想使用QueryParam属性将查询字符串读入控制器方法参数。

一个示例控制器类。

#[Route("/posts")]
class PostController extends AbstractController{
    //... other methods.

    #[Route(path: "", name: "all", methods: ["GET"])]
    function all(#[QueryParam] string $keyword,
                 #[QueryParam] int $offset = 0,
                 #[QueryParam] int $limit = 20): Response
    {
        $data = $this->posts->findByKeyword($keyword || '', $offset, $limit);
        return $this->json($data);
    }
}

然后我尝试创建一个QueryParam属性和一个自定义ParamConverter来归档目的。

#[Attribute(Attribute::TARGET_PARAMETER)]
final class QueryParam
{
    private string $name;

    /**
     * @return string
     */
    public function getName(): string
    {
        return $this->name;
    }

    /**
     * @param string $name
     * @return QueryParam
     */
    public function setName(string $name): QueryParam
    {
        $this->name = $name;
        return $this;
    }
}

的源代码QueryParamParamConverter

class QueryParamParamConverter implements ParamConverterInterface, LoggerAwareInterface
{
    public function __construct()
    {
    }

    private LoggerInterface $logger;

    /**
     * @inheritDoc
     * @throws ReflectionException
     */
    public function apply(Request $request, ParamConverter $configuration): bool
    {
        $param = $configuration->getName();
        $this->logger->debug("configuration name: " . $param);
        $className = $configuration->getClass();
        $reflector = new ReflectionClass($className);
        $attrs = $reflector->getAttributes(QueryParam::class);
        $attr = $attrs[0];
        $name = $attr->getArguments()[0] ?? $param;
        $value = $request->attributes->get($param);
        $this->logger->debug("set request attribute name: " . $name . ", value: " . $value);
        $request->attributes->set($name, $value);
        return true;
    }

    /**
     * @inheritDoc
     * @throws ReflectionException
     */
    public function supports(ParamConverter $configuration): bool
    {
        $className = $configuration->getClass();
        $this->logger->debug("class name:" . $className);
        if ($className) {
            // determine this method argument is annotated with `QueryParam`?
        }

        return false;
    }

    public function setLogger(LoggerInterface $logger)
    {
        $this->logger = $logger;
    }
}

总是返回空字符串而 $className = $configuration->getClass();不是类名。

我不确定使用QueryParam.

4

0 回答 0