widefocus/parameters

参数包实现。

1.0.0 2017-04-27 09:53 UTC

This package is not auto-updated.

Last update: 2024-09-20 22:38:13 UTC


README

Build Status Latest Stable Version License

此包包含一个参数包的实现。

安装

使用composer安装包。

$ composer require widefocus/parameters

使用方法

创建包

该包包括一个用于创建参数包的工厂。

<?php
use WideFocus\Parameters\ParameterBagFactory;

$factory = new ParameterBagFactory();
$bag = $factory->createBag(['foo' => 'Foo']);
if ($bag->has('foo')) {
    echo $bag->get('foo');
}

添加和移除值。

包是不可变的,但提供了方法来获取添加或移除值的副本。

<?php

use WideFocus\Parameters\ParameterBagFactory;

$factory = new ParameterBagFactory();
$bag = $factory->createBag()
    ->with('foo', 'Foo')
    ->with('bar', 'Bar');

$withoutFoo = $bag->without('foo');

在主题上设置值

可以使用参数设置器在主题上设置值。默认设置器会在主题上查找设置方法。

<?php
use WideFocus\Parameters\ParameterBagFactory;
use WideFocus\Parameters\ParameterSetter;

class Subject
{
    private $foo;
    
    public function setFoo(string $foo)
    {
        $this->foo = $foo; 
    }
    
    public function getFoo(): string
    {
        return $this->foo; 
    }
}

$subject = new Subject();

$factory = new ParameterBagFactory();
$bag = $factory->createBag(['foo' => 'Foo']);

$setter  = new ParameterSetter();
$setter->setParameters($subject, $bag);
echo $subject->getFoo(); // Foo