Objects with properties

There is also a way to use normal objects with properties as encapsulation. Setting values, getting values and adding values will call your setter- getter- or adder-method if available.

use Dustin\Encapsulation\PropertyEncapsulation;

class Product extends PropertyEncapsulation 
{
    /**
     * @var string
     */
    protected $name;

    /**
     * @var int
     */
    protected $stock;

    /**
     * @var float
     */
    protected $price;

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

    public function setName(string $name)
    {
        $this->name = $name;
    }

    public function getStock(): ?int
    {
        return $this->stock;
    }

    public function setStock(int $stock)
    {
        $this->stock = $stock;
    }

    public function getPrice(): ?float
    {
        return $this->price;
    }

    public function setPrice(float $price)
    {
        $this->price = $price;
    }
}

That's all. Now you can use your Product-class like any other encapsulation.

$product = new Product([
    'name' => 'My cool product',
    'stock' => 100
]);

$product->set('price', 59.99);

$data = $product->toArray();
$stockUpdateData = $product->getList(['name', 'stock']);

Last updated