miwal

Best if Repositories always return ->toArray() ?

Posted 9 months ago by miwal

Am I right in saying that to implement a repository effectively, I must not return any active records (models).

Reason is, a (perverse) client could do this:

// $lessons is the name of the injected repository

$lesson = $lessons->get($slug);

$any_other_mad_query = $lesson::find('some other lesson');
// this last call circumvents the repository, so if the data layer had been derouted, say, to a mock, or some other implementation of the repository than the database which the model connects to, this would break.

The above code circumvents the repository and breaks separation of concerns. It's what you risk if your repository returns a functioning active record.

To prevent this, repositories should always call ->toArray().

toArray() will unnest even the eloquent collection of models (active records). Here's a summary of the options (I checked):

  • Lesson::first() gives a single model, not a collection.
  • Lesson::all() gives an eloquent collection (extends base collection) containing models.
  • Lesson::first()->toArray() gives a flat array.
  • Lesson::all()->toArray() gives an array of arrays (both collection and models inside it are unpacked to arrays)

Taylor calls ->toArray() when returning from a repository at the start of his book.

I just wanted to get my head around the concept before attempting to implement it, the options available, what to avoid and why.

Comments / clarifications / discussion greatly appreciated.

Please sign in or create an account to participate in this conversation.

Laracasts Mascot

Hi, Have We Met Yet?

Did you know that, in addition to the forum, Laracasts includes well over 1000 lessons on modern web development? All for the price of one lunch out per month.

Sign Me Up

Channels

Reply to

Use Markdown with GitHub-flavored code blocks.