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 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器