V
V
Vasyl Fomin2016-10-28 15:34:10
Design patterns
Vasyl Fomin, 2016-10-28 15:34:10

What is the pattern and can it be used in real projects?

Couldn't find an answer to my previous question here. . Therefore, I want to start by learning how to classify the service layer between controllers and models, which I implemented below in the example, and is it realistic to use such a concept in further projects?
Controller:

class PostController extends Controller
{
    protected $post;

    public function __construct(PostService $post)
    {
        $this->post = $post;
    }

    public function index()
    {

        $posts = $this->post->getAll();
        return view('admin.posts.posts', compact('posts'));
    }
}

Model:
class Post extends Model
{
  protected $table = 'posts';

  protected $fillable = ['slug','title', 'img', 'description', 'content', 'category_id'];
  
  public function category()
  {
    return $this->belongsTo('App\Models\Category');
  }
}

Service or Repository:?
class PostService
{
  protected $post;

  public function __construct(Post $post)
  {
    $this->post = $post;
  }

  public function getAll()
  {
    return $this->post->all();
  }
}

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
Fractal Zombie, 2016-10-28
@fomvasss

You answered the question normally and at that time. If the application is complex, then it makes sense to hide requests in the repository and logic in services in order to unload controllers and avoid code duplication.
And if it is very complex, maybe Doctrine ORM is better? There just the use of Repository, Services is encouraged.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question