Mike Moore
Mike Moore

Reputation: 7478

To include methods in a model or not?

I have a class which serves as a model for an image:

class Image
{
    public $imageId;
    public $title;
    public $description;
    public $filename;
    public $enabled;
    public $galleryId;
    public $galleryName;
    public $orderNum;
}

I also have a class, ImageMapper which grabs the information about the image from the DB and fills the Image object up with the appropriate data. I'm not going to show you ImageMapper because it's a really nasty piece of code :-)

Here is an example of how I do that:

$image = new Image();
$image->imageId = $previouslyRetrievedId;
$imageMapper = new ImageMapper();
$image = $imageMapper->find($image->imageId);

My question is: where should I include methods for converting info about the image. For example, the $enabled property of the Image class is represented in the database by a 0 or a 1. When I display that property on a page that is to be read by humans, I would rather it display "No" or "Yes", respectively. Should I include a function to translate the values in the Image class, the ImageMapper class, on the page which displays the Yes or No to the user, or somewhere else?

I have heard that it is bad to include functions in a data object, which is what I am calling the Image object.

Here is an example of the method I am referring to:

public function getEnabledAsText()
{
    if(!$this->enabled) {
        return 'No';
    }
    return 'Yes';
}

Upvotes: 1

Views: 68

Answers (2)

dnagirl
dnagirl

Reputation: 20446

I'd probably write an ImageDataPresenter class and use it to "translate" ugly Image properties into pretty human readable text.

$presenter=new ImageDataPresenter($imageobj);
echo $presenter->enabled; //'yes'

Upvotes: 2

Shakti Singh
Shakti Singh

Reputation: 86416

Model should be only for interact with the data source only and return the data source result to the controller.

You should either create function in the controller or it should be created as helper and translate values to display format.

Helper is nothing but helps views to use minimal logics.

Upvotes: 1

Related Questions