Php 在JMS序列化程序中混合访问器和SkipWhenEmpty

Php 在JMS序列化程序中混合访问器和SkipWhenEmpty,php,jms-serializer,Php,Jms Serializer,我正在一个项目中使用,我正在努力解决一件事 我使用@Accessor注释(在DateTime属性上)只回显日期而不回显时间。但是在我的一些对象上,我没有任何信息,也不希望在这种情况发生时输出日期键 如果没有@Accessor,我可以轻松地使用@SkipWhenEmpty,它可以完美地处理其他属性。但我好像不能把他们两个混在一起 下面是我的示例代码: composer.json: { "require": { "jms/serializer": "^1.14" }

我正在一个项目中使用,我正在努力解决一件事

我使用
@Accessor
注释(在
DateTime
属性上)只回显日期而不回显时间。但是在我的一些对象上,我没有任何信息,也不希望在这种情况发生时输出日期键

如果没有
@Accessor
,我可以轻松地使用
@SkipWhenEmpty
,它可以完美地处理其他属性。但我好像不能把他们两个混在一起

下面是我的示例代码:

composer.json

{
    "require": {
        "jms/serializer": "^1.14"
    }
}
StackOverflowExample.php

<?php

declare(strict_types=1);

use JMS\Serializer\Annotation as Serializer;

class StackOverflowExample
{
    /**
     * @var \DateTime
     * @Serializer\Accessor(getter="getDate")
     * @Serializer\SkipWhenEmpty()
     */
    private $date;

    /**
     * @var string
     * @Serializer\SkipWhenEmpty()
     */
    private $title;

    public function getDate(): string
    {
        if (null === $this->date) {
            return '';
        }

        return $this->date->format('Y-m-d');
    }

    public function setDate(\DateTime $date): void
    {
        $this->date = $date;
    }

    public function getTitle(): string
    {
        return $this->title;
    }

    public function setTitle(string $title): void
    {
        $this->title = $title;
    }
}
<?php

$loader = require __DIR__.'/../vendor/autoload.php';
require_once __DIR__.'/StackOverflowExample.php';
\Doctrine\Common\Annotations\AnnotationRegistry::registerLoader([$loader, 'loadClass']);

$serializer = \JMS\Serializer\SerializerBuilder::create()->build();

$testWithDateAndTitle = new StackOverflowExample();
$testWithDateAndTitle->setDate(new DateTime());
$testWithDateAndTitle->setTitle('Example with date and title');

$testWithDateAndNoTitle = new StackOverflowExample();
$testWithDateAndNoTitle->setDate(new DateTime());

$testWithNoDateButTitle = new StackOverflowExample();
$testWithNoDateButTitle->setTitle('Example with title but no date');

echo $serializer->serialize($testWithDateAndTitle, 'json').PHP_EOL;
echo $serializer->serialize($testWithDateAndNoTitle, 'json').PHP_EOL;
echo $serializer->serialize($testWithNoDateButTitle, 'json').PHP_EOL;
执行
stackoverflow.php
时,它输出的数据如下:

{"date":"2019-05-03","title":"Example with date and title"}
{"date":"2019-05-03"}
{"date":"","title":"Example with title but no date"}
第一行是控件

在第二行,由于
@SkipWhenEmpty

但是在第三行,即使使用
@SkipWhenEmpty
,我仍然有日期键


有什么我忘了的吗?我怎么能只在日期字段被填充时才回显它呢?

根据我的研究,我认为您需要返回null而不是not

返回“”

在getDate函数中


通过我的研究,我认为您需要返回null而不是

返回“”

在getDate函数中


我很惭愧上周没看到它。谢谢你!我很惭愧上周没看到它。谢谢你!