mardi 14 novembre 2017

Laravel: When to use a repository and when not to use a repository

I have a laravel app that is currently being powered by repositories. My question might seem simple enough but i would like to get a clearer understanding of when to use a repository vs when not to use a repository.

A working example. Create new user

I have a UserRepository that has a method called storeUser() which receives the Illuminate\Http\Request instance so it can identify the data and save it to the users table.

Within the method, i generate a verification_token for the user, so the user can verify their email address.

Here is where my above question comes in.

Example 1: TokenRepository

So my immediate thought is to use a TokenRepository that would handle the creation, storing and looking up of tokens.

 public function storeUser(Request $request)
 {
   $user = $this->model;

   // Other details...

   $user->verification_token = $this->tokens->generateToken(255);

   $user->store();
 }



 // Token repository function stored in TokenRepository

 protected function generateToken($value)
 {
   return bin2hex(random_bytes($value));
 }

Example 2: Function

In this example, it would make more sense to use laravel's str_random() function to generate a token for the newly created user for email verification

public function storeUser(Request $request)
{
  $user = $this->model;

  // Other details...

  $user->verification_token = str_random(255);

  $user->store();
}

With all that being said, would it be worth while to create a repository to handle niche specific functionality, and what would the benefits be or alternatively rather use already-existing functions to handle the same response?

I am very new to repository pattern design, with about 3 weeks experience. Im trying to learn the correct way of this type of design method. Any thoughts, ideas, suggestions and comments would be helpful.

Thanks



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

Aucun commentaire:

Enregistrer un commentaire