dgifford/property-setter-trait

Trait providing methods to set class properties with an array.

v2.0 2021-11-11 11:31 UTC

This package is auto-updated.

Last update: 2024-05-11 17:17:53 UTC


README

Provides a method to set properties of a class with an array.

class Foo
{
	Use \dgifford\Traits\PropertySetterTrait;



	public $string = '';

	public $array = [];

	public $bool = false;

	public $anything;

	protected $cannot_be_set;



	public function __construct( $properties = [] )
	{
		/*
			Set public properties from $properties array.
			Only sets properties if they are the same type.
			$anything can be set to any type because it is null.
		*/
		$this->setPublicProperties( $properties, true );
	}
}


$foo = new Foo([

	'string' 	=> 'Hello world',
	'array' 	=> ['Hello world'],
	'bool' 		=> false,
	'anything' 	=> 'Hello world',

]);

echo Foo->string; // 'Hello world'

The value in the array will only be used if it is of the same type as the default property in the class.

Automatically calling setter methods


If a method doesn't exist for setting the property, a `BadMethodCallException` is thrown.

class Foo
{
	Use \dgifford\Traits\PropertySetterTrait;



	public $string = '';

	public $array = [];

	public $bool = false;

	public $anything;

	protected $cannot_be_set;



	public function __construct( $properties = [] )
	{
		/*
			Set public properties from $properties array.
			Only set properties if they are the same type 	
			by setting the second argument to true.
			$anything can be set to any type because it is null.
		*/
		$this->setPublicProperties( $properties, 'set_' );
	}



	/**
	 * Method for setting the $string property.
	 */
	public function set_string( $value = '' )
	{
		if( is_string( $value ) )
		{
			this->string = $value;
		}
	}
}


$foo = new Foo([
	'string' 	=> false,
]);

echo Foo->string; // ''

$foo = new Foo([
	'string' 	=> 'Hello world',
]);

echo Foo->string; // 'Hello world'

Calling all setter methods

The `callAllSetters()` method retreives all properties in a class and passes them to any setter methods that exist.

This can be used for more complex manipulation of properties (e.g. after using `setPublicProperties()` )

class Foo
{
	Use dgifford\Traits\PropertySetterTrait;



	public $anything;

	protected $protected;



	public function set_anything()
	{
		$this->anything = 'anything';
	}
	


	public function set_protected()
	{
		$this->protected = 'protected';
	}



	public function getProtected()
	{
		return $this->protected;
	}
}


$foo = new Foo;

$foo->callAllSetters();

echo $foo->anything; // 'anything'
echo $foo->getProtected(); // 'protected'