delolmo/valinor-console

该包的最新版本(1.7.1)没有可用的许可信息。

使用symfony/console作为Valinor数据源

1.7.1 2023-12-18 15:40 UTC

This package is auto-updated.

Last update: 2024-09-18 17:13:06 UTC


README

以下库允许使用symfony/console组件的InputInterface对象作为cuyz/valinor库的数据源。

安装

composer require delolmo/valinor-console

示例

use App\DTO\CustomObject;
use CuyZ\Valinor\Mapper\Source\Source;
use CuyZ\Valinor\MapperBuilder;
use DelOlmo\Valinor\Mapping\Source\InputSource;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;

final class CustomCommand extends Command
{
    public function execute(InputInterface $input, OutputInterface $output): int
    {
        // Create the Source using the new InputSource
        $source = Source::iterable(new InputSource($input));
        
        // Create the Mapper, using the desired configuration
        $mapper = new MapperBuilder())
            ->allowSuperfluousKeys()
            ->enableFlexibleCasting()
            ->mapper();
            
        // Map the source to whatever object makes sense
        $mapped = $mapper->map(CustomObject::class, $source);
        
        // Apply whatever business logic makes sense from here
        // ...
    }
}

最后说明

  • delolmo/valinor-console的版本将与cuyz/valinor版本匹配。同样适用于PHP版本。
  • 在创建Mapper对象时,应始终注意,默认情况下,Symfony会向InputInterface对象添加多个选项(例如,帮助或详细程度级别)。如果不使用allowSuperfluousKeys,则映射过程将抛出异常 - 除非您考虑在您要映射的对象中包含这些参数(如上面的示例中的App\DTO\CustomObject)。有关更多信息,请参阅允许多余的键
  • 尽管在同一个Symfony命令中,选项和参数不能有相同的名称,但应注意的是,从InputSource的角度来看,参数始终优先于选项。也就是说,如果有共享相同名称的参数和选项,InputSource将仅使用参数的值进行映射。
  • 考虑到Symfony命令应用程序将大多数字段转换为字符串或数组,值得注意的是,Mapper也应配置enableFlexibleCasting。有关更多信息,请参阅启用灵活类型转换