aurimasniekis / doctrine-json-object-type
Doctrine Json Object Type
1.0.0
2017-05-16 10:29 UTC
Requires
- php: ^7.0
- doctrine/dbal: 2.6.x-dev
Requires (Dev)
- phpunit/phpunit: ~6.1
This package is auto-updated.
Last update: 2024-09-14 03:00:32 UTC
README
Doctrine Json Object Type 允许序列化和反序列化实现了 JsonObject 接口的对象到 JSON 格式及其反向操作。
安装
通过 Composer
$ composer require aurimasniekis/doctrine-json-object-type
配置
Symfony
doctrine: dbal: url: '%env(DATABASE_URL)%' types: json_object: AurimasNiekis\DoctrineJsonObjectType\JsonObjectType
普通 Doctrine
<?php use Doctrine\DBAL\Types\Type; Type::addType('json_object', 'AurimasNiekis\DoctrineJsonObjectType\JsonObjectType');
用法
值对象应实现 JsonObject
接口。
<?php use AurimasNiekis\DoctrineJsonObjectType\JsonObject; class ValueObject implements JsonObject { private $name; public function setName($name) { $this->name = $name; } public function getName() { return $this->name; } public static function fromJson(array $data) { $inst = new self(); $inst->setName($data['name']); return $inst; } public function jsonSerialize() { return [ 'name' => $this->getName() ]; } }
实体
<?php use Doctrine\ORM\Mapping as ORM; /** * @ORM\Entity * @ORM\Table(name="entity") */ class Entity { /** * @var int * * @ORM\Column(type="integer") * @ORM\Id * @ORM\GeneratedValue(strategy="AUTO") */ private $id; /** * "json_object" is extended "json" type * * @var ValueObject * * @ORM\Column(type="json_object) */ private $value; /** * @return int */ public function getId(): int { return $this->id; } /** * @return ValueObject */ public function getValue() { return $this->value; } /** * @param ValueObject $value */ public function setValue(ValueObject $value) { $this->value = $value; } }
用法
<?php $value = new ValueObject(); $value->setName('foo_bar'); $entity = new Entity(); $entity->setValue($value); $em->persist($entity); $em->flush(); // INSERT INTO `entity` (`id`, `value`) VALUES (1, '{"name": "foo_bar", "__class": "ValueObject"}'); $findResult = $repo->find(1); /// $findResult->getValue() === $value;
测试
$ composer test
贡献
请参阅 CONTRIBUTING 和 CONDUCT 以获取详细信息。
许可证
请参阅 许可证文件 以获取更多信息。