duancui19840401 2015-11-10 19:37
浏览 261
已采纳

对象属性中的默认值(如果不存在)

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.

  • 写回答

1条回答 默认 最新

  • dq23171 2015-11-10 19:50
    关注

    The function parse_image_name is not returning anything. If you return the $image variable it will be set like you expect it to.

    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;
    
        return $image;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 用verilog实现tanh函数和softplus函数
  • ¥15 Hadoop集群部署启动Hadoop时碰到问题
  • ¥15 求京东批量付款能替代天诚
  • ¥15 slaris 系统断电后,重新开机后一直自动重启
  • ¥15 QTableWidget重绘程序崩溃
  • ¥15 谁能帮我看看这拒稿理由啥意思啊阿啊
  • ¥15 关于vue2中methods使用call修改this指向的问题
  • ¥15 idea自动补全键位冲突
  • ¥15 请教一下写代码,代码好难
  • ¥15 iis10中如何阻止别人网站重定向到我的网站