Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Leff7's avatar
Level 4

Php - making a class instance that has dependencies in the constructor

I have a class, that has a constructor that looks like this:

use App\Libraries\Content\ContentInterface;
use EllipseSynergie\ApiResponse\Laravel\Response;

class ImportController extends Controller
{
    private $indexable;

    function __construct(Response $response, ContentInterface $contentInterface) {
        $this->indexable        = \Config::get('middleton.wp.content.indexable_types');
        $this->response         = $response;
        $this->contentInterface = $contentInterface;
    }

    public function all() {
        $include      = array_diff($this->indexable, ['folder']);
        $importResult = $this->import($include);
        $this->deleteOldContent($importResult['publishedPostsIDs']);

        return $importResult['imported'];
    }

How can I instantiate this class from another class and call the method all() from it? I have tried with something like this:

use EllipseSynergie\ApiResponse\Laravel\Response;
use App\Libraries\Content\ContentInterface;

class ContentImport extend Command {

public function handle() {

    (new ImportController(new Response, new ContentInterface))->all();
}

But, that doesn't work, I get the error that I should pass the arguments to the Response class too:

 [Symfony\Component\Debug\Exception\FatalThrowableError]                                                                    
  Type error: Too few arguments to function EllipseSynergie\ApiResponse\AbstractResponse::__construct(), 0 passed in /home/  
  vagrant/Projects/middleton/app/Console/Commands/ContentImport.php on line 43 and exactly 1 expected  

What is the correct way of doing this?

0 likes
1 reply
martinbean's avatar

What is the correct way of doing this?

@Leff7 To use the service container to resolve your dependencies. You shouldn’t be instantiating a controller from anywhere in your code though.

Instead, wrap your import logic into a class of its own, and then pull that class into where you need it:

class Importer
{
    public function __construct(Importable $data)
    {
        $this->data = $data;
    }
}
class ImportController extends Controller
{
    public function __construct(Importer $importer)
    {
        $this->importer = $importer;
    }
}
class ImportCommand extends Command
{
    public function __construct(Importer $importer)
    {
        $this->importer = $importer;
    }

    public function handle()
    {
        // Use $this->importer
    }
}
1 like

Please or to participate in this conversation.