Best practice to initiate object

Posted 1 year ago by longestdrive


I'm after some best practice to initiating objects to try and refactor some code.

In my Laravel app I generally have followed this approach to structure a class:


namespace app\Libraries\Generators;

use App\Models\Fixture;
use App\Libraries\Repositories\FixtureRepository;

class FixtureMatrixGenerator
    protected $fixture;
    protected $fixtureRepository;

     * FixtureMatrixGenerator constructor.
     * @param $fixture
    public function __construct(Fixture $fixture, FixtureRepository $fixtureRepo)
        $this->fixture = $fixture;
        $this->fixtureRepository = $fixtureRepo;


But then if in say a controller I try to initiate the object like this:

$leagueMatrixGenerator = new FixtureMatrixGenerator();

I get an error Too few Arguments to function Which I expect.

So what's the best practice for loading dependancies into a class? In some of my controllers for example I end up with 6-7 dependcies (generally models or repositories) which seems to bloat the __constructor method. Is there a better method for creating new objects only when I need them?

Sorry, likely a basic oop question but I've got stuck down one route that now seems messy

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.