Skip to content

Instantly share code, notes, and snippets.

@yourwebmaker
Created January 23, 2016 03:57
Show Gist options
  • Save yourwebmaker/533499f19026697b93f6 to your computer and use it in GitHub Desktop.
Save yourwebmaker/533499f19026697b93f6 to your computer and use it in GitHub Desktop.
Showing how to use Value Objects to get better code maintenance and better design.
<?php
declare(strict_types = 1);
namespace App
{
class Status
{
const ACTIVE = 1;
const INACTIVE = 2;
const SOLD = 3;
private $value;
private $labels = [
self::ACTIVE => 'Active',
self::INACTIVE => 'Inactive',
self::SOLD => 'Sold',
];
/**
* Status constructor.
* @param $value
*/
public function __construct(int $value)
{
if (!in_array($value, array_keys($this->labels))) {
throw new \InvalidArgumentException('Invalid status');
}
$this->value = $value;
}
public function __toString()
{
return $this->labels[$this->value];
}
}
class Product
{
private $id;
private $name;
private $status;
/**
* Product constructor.
* @param $id
* @param $name
* @param $status
*/
public function __construct(int $id, string $name, Status $status)
{
$this->id = $id;
$this->name = $name;
$this->status = $status;
}
}
$status = new Status(Status::SOLD);
var_dump(new Product(1, 'Chess board', $status));
echo "\n\n\n\n{$status}";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment