Answer the question
In order to leave comments, you need to log in
How to “beautifully” initialize an object property?
I apologize in advance for the stupid question, but I am tormented by vague doubts that I am doing something wrong, there is such a case:
class Product {
//Some properties
//....
// \Models\OptionsInterface
protected $options;
// \Models\PriceInterface
protected $price;
protected $type;
public function setOptions($options)
{
if($this->type == ...some_condition_a && ...next_condition_a...)
{
$this->options = $this->factory->make('OptionsA', $options);
}
elseif($this->type == ...some_condition_b && ...next_condition_b ..)
{
//Some options logic
$options = ....
$this->options = $this->factory->make('OptionsB', $options);
}
//Также объект может и не иметь опций, в этом случае
//$this->options = null по-дефолту
}
public function setPrice($price)
{
$this->price = $this->factory->make('Price', $price);
}
}
class ConcreteProduct extends Product {
public function setOptions($options)
{
if($this->type == ...some_condition_a && ...next_condition_a...)
{
//Some options logic
$options = ....
$this->options = $this->factory->make('ConcreteOptionsA', $options);
}
elseif($this->type == ...some_condition_b && ...next_condition_b...)
{
//Some options logic
$options = ....
$this->options = $this->factory->make('ConcreteOptionsB', $options);
}
}
public function setPrice($price)
{
if($this->type == ...some_condition_a)
{
//Some price logic
$price = ...
$this->price = $this->factory->make('ConcretePriceA', $price);
}
elseif($this->type == ...some_condition_b)
{
$this->price = $this->factory->make('ConcretePriceB', $price);
}
else
{
$this->price = $this->factory->make('Price', $price);
}
}
}
//Работа с объектом осуществляется в таком роде
$product = new ConcreteProduct();
$product->setOptions($data['options']);
$product->setPrice($data['price']);
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question