fideloper / Implementing-Laravel

Companion application to the e-book Implementing Laravel
173 stars 40 forks source link

Question about EloquentArticle / Article Repository #7

Closed rydurham closed 11 years ago

rydurham commented 11 years ago

Hello,

A question for you about the Impl\Repo\Article\EloquentArticle->create() method.

Are there any disadvantages to doing this instead?

public function create(array $data)
    {
        // Create the article
        $this->article = \Article::create(array(
            'user_id' => $data['user_id'],
            'status_id' => $data['status_id'],
            'title' => $data['title'],
            'slug' => $this->slug($data['title']),
            'excerpt' => $data['excerpt'],
            'content' => $data['content'],
        ));

        ....

        return $this->article->id;
    }

The benefit would be easy access to the newly created Article's Id, which I am trying to get to the controller for other purposes.

Thoughts?

Thank you! Your book is fantastic. ~Ryan

fideloper commented 11 years ago

Any reason not to do this?

    public function create(array $data)
    {
        // Create the article
        $article = \Article::create(array(
            'user_id' => $data['user_id'],
            'status_id' => $data['status_id'],
            'title' => $data['title'],
            'slug' => $this->slug($data['title']),
            'excerpt' => $data['excerpt'],
            'content' => $data['content'],
        ));

        ....

        return $article->id;
    }

That way you get the $id immediately but don't confused your repository "article" object with a business entity "article" which should (ideally) be separate.

To be clear, I think it could get confusing if you use $this->article as a business entity "article" rather than the method of data retrieval.

This is yet another place where using ORMs gets weird. They are both a business logic entity (an article, in this example) AND a data-retrieval mechanism.

The more architecture I attempt to apply to code, the more I dislike ORMs....

rydurham commented 11 years ago

Yes - I see. That makes sense. I agree it is important to keep the repository "article" and the business entity "article" separate.

Thanks!