mardi 11 septembre 2018

Laravel: how to create resource that depends on multiple models

I need to create a resource that should collect information from multiple models.

At the moment I'm creating a regular resource:

$movieResource = new MovieResource($movie);

Inside of MovieResource::toArray():

public function toArray($request)
{
    $this->initRepos(); // initializing used repositories as static fields

    $movieData = [ // transforming model to resource
        'title' => $this->title,
    ];

    $this->attachSounds($movieData); // Uses two unrelated tables
    $this->attachUrl($movieData);    // Uses one unrelated table
    $this->attachAnotherInfo($movieData); // Uses one unrelated table

    return $movieData;
}

MovieResource class is used in a few different places in the project. In order to not duplicate logic I decided to inject repositories inside resource.

In some places MovieResource is used extensively, that's why used repositories are initialized as static properties of MovieResource class (to avoid multiple instances initialization)

Such structure however has some limitations: testing is almost impossible, because static methods can not be mocked. Resource class should be as simple as possible, but now it is overloaded.

I'm aware that current solution is far from ideal that's why I'm asking for you help, advice or experience share on how current solution can be enhanced.



from Newest questions tagged laravel-5 - Stack Overflow https://ift.tt/2x0hiEA
via IFTTT

Aucun commentaire:

Enregistrer un commentaire