question about If File Exists, controller or view?

Hi There

I’m learning Yii and MVC and building my first app to teach myself.

I have a DB table called "projects", it lists all the projects by name and some can have a logo attached to them.

when i’m displaying the projects, i need to check:

1- if they have a logo attached

2- if so, display the logo

3- if not, display a default image.

I’m a little unsure how to go about this, i’ve achieved it by using the “view” but i’m not happy with having the logic for this in there. Can someone point me in the right direction.

I currently have this for my controller




public function actionIndex()

	{

		$dataProvider=new CActiveDataProvider('Projects', array(

		    'criteria'=>array(

		        'condition'=>'deleted=0',

		        'order'=>'	created_on DESC',

		    ),)

		);

		$this->render('index',array(

			'dataProvider'=>$dataProvider,

		));

	}



and this for my view




<div class="project_logo">

<?php

$theLoc=$this->logoUploadPath.'th_';

if (!file_exists($theLoc.CHtml::encode($data->logo_file)))

	{

	$data->logo_file='logo_50x50.gif';

	}

$fileLoc=$theLoc.CHtml::encode($data->logo_file);

?>

<?php echo CHtml::link('<img width="60" height="60" src="'.$fileLoc.'" />', array('view', 'id'=>$data->id)); ?>

</div>



thanks

You could create a static method in the Projects model and move the logic there. That way it would make it reusable elsewhere in the application;




public static function getLogo()

{

    if (file_exists($this->filename)) {

       $src = 'url/path/to/logo';

    } else {

       $src = '/path/to/default/image';

    }


    return CHtml::link //.. etc

}



Call the method;




Projects::getLogo()



I have a better idea for you :)




class Projects extends CActiveRecord

{

    // ...

    public function getLogosPath()

    {

        // returns the path to all logos

    }


    public function getLogosUrl()

    {

        // returns the url of logos directory

    }


    public function getLogoFileName()

    {

        return 'th_'.CHtml::encode($this->logo_file);

    }


    public function getLogoExists()

    {

        return is_file($this->getLogosPath().'/'.$this->getLogoFileName());

    }


    public function getLogoUrl()

    {

        return $this->getLogosUrl().'/'.($this->getLogoExists() ? $this->getLogoFileName() : 'logo_50x50.gif');

    }


    public function getLogoPath()

    {

        return $this->getLogosPath().'/'.$this->getLogoFileName();

    }


    protected function afterDelete()

    {

        parent::afterDelete();

        @unlink($this->getLogoPath());

    }

}


// and in you view:

CHtml::link('<img width="60" height="60" src="'.$data->logoUrl.'" />', array('view', 'id'=>$data->id));



If you think there are too many functions to handle logos in your model, then you can merge some of them, but they can be useful separately in some situations.

Thanks guys, exactly what i wanted :)