If you do not know the category names before they are created, you can use the __ call to make the creation dynamic.
An example:
class Categorias
{
protected $name;
private $prod;
public function __construct($name, $prod)
{
$this->name = $name;
$this->prod = $prod;
}
public function add($value)
{
$this->prod->categorias[$this->name][] = $value;
}
}
class Produtos
{
public $categorias = array();
public function __call($name, $arguments)
{
return (new Categorias($name, $this));
}
}
$p = new Produtos();
$p->tvs()->add("teste");
$p->pcs()->add("nome do pc");
var_dump($p->categorias);
In the code above, we created a class called categorias
, which basically will be responsible for filling the category vector of class produtos
.
The __call
method is used when some non-existent method of the object is called. That is, when categories, which you do not know yet, are called, the __call
method is invoked and then we pass the call to a new instance of the categorias
class.
If you know which categories can be used, the second @WallaceMaxters option would work fine: Sending the existing categories in the constructor of the produtos
class and adding a check within __call
to check if the category exists before forwarding the responsibility.
Translating to form I wrote:
class Categorias
{
protected $name;
private $prod;
public function __construct($name, $prod)
{
$this->name = $name;
$this->prod = $prod;
}
public function add($value)
{
$this->prod->categorias[$this->name][] = $value;
}
}
class Produtos
{
public $categorias = array();
public function __construct($categorias = [])
{
foreach ($categorias as $categoria) {
$this->categorias[$categoria] = [];
}
}
public function __call($name, $arguments)
{
if (!array_key_exists($name, $this->categorias)) {
// retorna erro.
}
return (new Categorias($name, $this));
}
}
$p = new Produtos(["tvs", "pcs"]);
$p->tvs()->add("teste");
$p->pcs()->add("nome do pc");
var_dump($p->categorias);
The categorias
class receives the instance of the produtos
class as its second argument in its constructor, because if it needs to use some product property to execute the actions inside the add
, it will have the object available to it. p>