HiveBrain v1.2.0
Get Started
← Back to all entries
patternphplaravelMinor

Laravel model and controller interaction

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
interactioncontrollerandmodellaravel

Problem

I want to know if I'm going about creating and calling two functions from my model to my controller in the simplest and cleanest way.

Model:

public function getPosts()
{
    $post = $this->paginate(4);
    return $post;
}

public function getMonth($post)
{
    $post->month = date('M', strtotime($this->created_at));
    $post->month = strtoupper($post->month);
    return $post->month;
}

public function getDay($post)
{
    $post->day = date('d', strtotime($this->created_at));
    return $post->day;
}


Controller:

public function index()
{
    $post = $this->post->getPosts();
    $post->month = $this->post->getMonth($post);
    $post->day = $this->post->getDay($post);

    return View::make('posts.index', compact('post'));
}


I am unsure about if my controller is acting in a strict MVC way, being that I thought it's only job is to direct traffic, but it's doing more by calling functions from my model. Is this the best way to go about this?

Solution

PHP is not my area of expertise, so just some generic notes:

-
4 is a magic number here:

$post = $this->paginate(4);


Why is it 4? What the purpose if this number? A named constant or local variable would be readable with a descriptive name.

-

public function getMonth($post)
{
    $post->month = date('M', strtotime($this->created_at));
    $post->month = strtoupper($post->month);
    return $post->month;
}


Using a local variable with a proper name, like lowercase_month, in the first line would be readable and more descriptive.

-
These methods violates Command Query Separation since they return some data and modify the $post too.


Functions should either do something or answer something, but not both.

Source: Clean Code by Robert C. Martin, Chapter 3: Functions, Command Query Separation p45

-

$post->month = date('M', strtotime($this->created_at));
$post->month = strtoupper($post->month);


I'd consider moving these calls to the Post class since it seems data envy. (Pseudocode.)

class Post {
    ...
    public void setMonth($created_at) {
        $lowercase_month = date('M', strtotime($created_at));
        $post->month = strtoupper($lowercase_month);
    }
    ...
}

Code Snippets

$post = $this->paginate(4);
public function getMonth($post)
{
    $post->month = date('M', strtotime($this->created_at));
    $post->month = strtoupper($post->month);
    return $post->month;
}
$post->month = date('M', strtotime($this->created_at));
$post->month = strtoupper($post->month);
class Post {
    ...
    public void setMonth($created_at) {
        $lowercase_month = date('M', strtotime($created_at));
        $post->month = strtoupper($lowercase_month);
    }
    ...
}

Context

StackExchange Code Review Q#40651, answer score: 9

Revisions (0)

No revisions yet.