I want to learn OOP to get my controllers more clean. So on my website, I get some products with their image_name
from database. When a image_name
is not set I want to set a default one. I don't want to make any if else in my view or model to check if image is set so I made a new class with some property and models. Here I check what I need and so my controller is more clean.
In my view I use the $product->image_name
where image_name
is the name of column in database, but using my class I want image_name
to be the imagefromdb.jpg
or defaultimage.jpg
if is not set. How can I call this class in my controller to work?
This is my class:
class Product
{
private $_product;
private $_resolution;
public function __construct($product, $resolution){
$this->_product = $product;
$this->_resolution = $resolution;
}
public function products() {
foreach($this->_product as $product){
$product->nume_imagine = $this->parse_image_name($product);
}
return $this->_product;
}
public function product() {
$this->_product->nume_imagine = $this->parse_image_name($this->_product);
return $this->_product;
}
private function parse_image_name($product)
{
if($product->nume_imagine):
$image = base_url('assets/uploads/'.$product->id_produs.'/'.$this->image_resolution($product->nume_imagine, $this->_resolution));
else:
$image = base_url('assets/images/no-product-image-available.png');
endif;
}
private function image_resolution($image_name, $resolution) {
$image = explode('.', $image_name);
return $image[0].'_'.$resolution.'.'.$image[1];
}
}
And controller:
$best_offer = new Product($this->products->best_offer(), 270);
but I get empty on image_name property.