mrself / options

此软件包最新版本(v2.19.7)没有可用的许可信息。


README

将特性添加到类中

class ClassWithOptions
{
    use \Mrself\Options\WithOptionsTrait;
}

添加第一个选项

use Mrself\Options\Annotation\Option;

class ClassWithOptions
{
    use \Mrself\Options\WithOptionsTrait;

    /**
    * The required option to initialize the class
     * @Option()
     * @var array
     */
    private $arrayOption;

    public function getOption()
    {
        return $this->arrayOption;
    }
}

初始化类

$instance = ClassWithOptions::make(['arrayOption' => ['key' => 'value']]);

// True
$instance->getOption()['key'] === 'value';

如果选项缺失,将抛出异常

// Exception \Symfony\Component\OptionsResolver\Exception\MissingOptionsException
$instance = ClassWithOptions::make();

更多示例

类型解析

use Mrself\Options\Annotation\Option;

class ClassWithOptions
{
    use \Mrself\Options\WithOptionsTrait;

    /**
     * @Option()
     * @var array
     */
    private $arrayOption;

    public function getOption()
    {
        return $this->arrayOption;
    }
}

$notArray = 1;
// Exception
ClassWithOptions::make(['arrayOption' => $notArray]);
use Mrself\Options\Annotation\Option;

class ClassWithOptions
{
    use \Mrself\Options\WithOptionsTrait;

    /**
     * @Option()
     * @var \DateTime
     */
    private $arrayOption;

    public function getOption()
    {
        return $this->arrayOption;
    }
}

$notDate = 1;
// Exception
ClassWithOptions::make(['arrayOption' => $notDate]);

与容器一起使用(见mrself/container)

use Mrself\Options\Annotation\Option;
use Mrself\Container\Container;
use Mrself\Container\Registry\ContainerRegistry;

$service = new \stdClass();
$service->property = 'myProperty';

$container = Container::make();
$container->set('service', $service);
ContainerRegistry::add('App', $container);

class ClassWithOptions
{
    use \Mrself\Options\WithOptionsTrait;

    /**
     * @Option()
     * @var \stdClass
     */
    private $service;

    public function getService()
    {
        return $this->service;
    }
}

$instance = ClassWithOptions::make();

// True
$instance->getService()->property === 'myProperty';

此特性可以与Symfony或具有公开服务的其他框架一起使用。

暂停所有错误

$object->init(['.silent' => true]);

如果一个注释属性具有非原始类型,则只能解析为该类型

$object = new class {
    /**
     * @Option
     * @var \Reflection
     */
    public $option1;
};

// Throws since 'option1' expected a value of type '\Reflection'
$object->init(['option1' => 1]);

原始类型不会被处理,因此应在数组模式中声明

new class {
    protected function getOptionsSchema()
    {
        return [
            'allowedTypes' => ['option1' => \Reflection::class]
        ];
    }
 };

数组模式比注释模式有更高的优先级

可以将选项设置为可选

$object = new class {
    /**
     * @Option(required=false)
     * @var \Reflection
     */
    public $option1;
};

可以通过特定的键预设选项

$object = new class {

    /**
     * @Option()
     * @var string
     */
    public $option1;
};
$object::presetOptions('nameOfPreset', [
    'option1' => 'value1'
]);
$object->init(['presetName' => 'nameOfPreset']);
$object->option1 === 'value1';