Mateusz Kaleta
Mateusz Kaleta

Reputation: 137

Laravel clean code

I am writing system for players where I use Laravel freamwork (just for learn) and I have question for more experience developer. I have one function which return me some data to view. I use this function in 3 controllers (but i copy and paste this function to each Controller files) and can I just put this function in one file and then use it in these 3 controllers? How can I use the same function in diffrent controller without copy and past?

Upvotes: 0

Views: 1235

Answers (3)

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

You can create Base Controller:

<?php

namespace App\Http\Controllers;

class BaseController
{
    protected $playersRepository;

    public function __construct(PlayersRepository $playersRepository)
    {
        $this->playersRepository = $playersRepository;
    }
}

Which is injected with a repository object:

<?php

namespace App\Http\Controllers;

class PlayersRepository
{
    public function getPlayers()
    {
        return Player::all();
    }
}

Which has a common method, that can be used in more than one extended controller:

Games

<?php

namespace App\Http\Controllers;

class Games extends BaseController
{
    public function index()
    {
        return view('games', ['players' => $this->playersRepository->getPlayers()]);
    }
}

Matches

<?php

namespace App\Http\Controllers;

class Matches extends BaseController
{
    public function show()
    {
        return view('matches', [
           'matches' => $matches,

           'players' => $this->playersRepository->getPlayers()
       ]);
    }
}

Upvotes: 1

bear
bear

Reputation: 11615

You can also use Traits to share methods, however, traits are more usually for describing characteristics and types.

You should create a utility class, or use consider an abstract controller class if this is desired.

Upvotes: 2

mitch
mitch

Reputation: 2245

Create module (util) or override main Controller class.

Upvotes: 0

Related Questions