2

What I need is the project directory or the public directory from symfony.

use App\Kernel;

class FileReader
{
    public function __construct(
       Kernel $kernel
    )
    {
        var_dump ($kernel->getProjectDir());

    }
}

The problem is I can not inject the kernel to my class.

In this post there are several strange things for me.

First, I get this error:

Cannot autowire service "App\Utils\Lotto\FileReader": argument "$kernel" of method "__construct()" references class "App\Kernel" but no such service exists. Try changing the type-hint to one of its parents: interface "Symfony\Component\HttpKernel\HttpKernelInterface", or interface "Symfony\Component\HttpKernel\KernelInterface".

Second, I have no KernelInterface from PHPStorm autocomplete, those interface is only for HttpKernelInterface what has no getProjectDirectory method.

How can I read out the /var/www/myproject or /var/www/myproject/public/?

AppyGG
  • 381
  • 1
  • 6
  • 12
vaso123
  • 12,347
  • 4
  • 34
  • 64

1 Answers1

4

You should not inject your Kernel, but instead inject only what you need. In this case it is the project directory, available through your service definition in config/services.yaml with the parameter %kernel.project_dir%:

services:
    App\Utils\Lotto\FileReader:
        arguments:
            $projectDirectory: "%kernel.project_dir%"

Then adjust your class constructor:

public function __construct(string $projectDirectory) {
    $this->directory = $projectDirectory;
}

As a bonus, you could make the directory automatically available for all of your services by defining a global "bind" parameter:

services:
    _defaults:
        bind:
            $projectDirectory: "%kernel.project_dir%"

With that definition, every Service can use the variable $projectDirectory in its __construct() without the need to define it explicit.

Kevin
  • 260
  • 2
  • 6