digiaonline/instance-factory

该软件包已被弃用,不再维护。未建议替代软件包。

从属性数组构建对象的工厂

1.1.0 2018-11-07 11:07 UTC

This package is auto-updated.

Last update: 2023-03-12 21:24:00 UTC


README

Build Status Coverage Status

从属性数组构建对象的工厂

安装

composer require digiaonline/instance-factory

使用方法

<?php

require_once(__DIR__ . '/vendor/autoload.php');

/**
 * A class we want to be able to instantiate. Phpdoc has been left out for brevity.
 */
class Person
{
    private $name;

    private $age;

    private $optionalInformation;

    public function __construct(string $name, int $age, ?string $optionalInformation = null)
    {
        $this->name                = $name;
        $this->age                 = $age;
        $this->optionalInformation = $optionalInformation;
    }

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

    public function getAge(): int
    {
        return $this->age;
    }

    public function getOptionalInformation(): ?string
    {
        return $this->optionalInformation;
    }
}

// Create one instance where we skip the optional information
/** @var Person $personOne */
$personOne = \Digia\InstanceFactory\InstanceFactory::fromProperties(Person::class, [
    'name' => 'John Smith',
    'age'  => 34,
]);

// Create another instance where we do supply optional information
/** @var Person $personOne */
$personTwo = \Digia\InstanceFactory\InstanceFactory::fromProperties(Person::class, [
    'name'                => 'Alice Smith',
    'age'                 => 33,
    'optionalInformation' => 'Not related to John Smith',
]);

这将打印以下内容

class Person#5 (3) {
  private $name =>
  string(10) "John Smith"
  private $age =>
  int(34)
  private $optionalInformation =>
  NULL
}

class Person#2 (3) {
  private $name =>
  string(11) "Alice Smith"
  private $age =>
  int(33)
  private $optionalInformation =>
  string(25) "Not related to John Smith"
}

如果由于任何原因实例化失败,将抛出\RuntimeException异常。

许可证

MIT