dimanche 7 octobre 2018

Improving code to take advantage of service container?

I am using using an Entity class to represent data retrieved from an API (using guzzle).

There will be many Entity classes such as Note, Customer, Order, etc.

I've passed the response via Guzzle to the Mapper which then create multiple objects of Entity. I've define which entity class to initiate in the map method.

There will be many methods in the NotesRepository and each method will make a API request. And there will be a few Repository classes which will do much pretty much same thing like NotesRepository.

For example:

NotesRepository

class NotesRepository
{
  protected $request;

  public function __construct(apiRequest $client)
  {
    $this->request = $client;
  }

  public function getById(int $id)
  {
    $response = $this->request->get('/notes/'.$id); //using guzzle and return via json_decode. 
    $mapper = new Mapper();

    return $mapper->map($response['data'], Note::class);
  }

  public function getByEmail(int $email) { }

}

Mapper

class Mapper
{
    protected $data;

    protected function map($data, $entityClass)
    {
        foreach($data as $entry) {
            $this->data[] = new $entityClass($entry);
        }

        return $this->data;
    }
}

And Entity class

class Note 
{
    protected $note;
    protected $id;

    public function __construct($response)
    {
        $this->id = $response['id'];
        $this->note = $response['note']?? ''; 
    }

    public function getId()
    {
        return $this->id;
    }

    public function getNote()
    {
        return $this->note;
    }
}

Is there anything this code can improved (or refactored) to take advantage of service container/providers and ability to use Laravel collection with entity classes?

Aucun commentaire:

Enregistrer un commentaire