How to Get the Server Path to the Web Directory in Symfony2 from Inside the Controller

How to get the server path to the web directory in Symfony2 from inside the controller?

There's actually no direct way to get path to webdir in Symfony2 as the framework is completely independent of the webdir.

You can use getRootDir() on instance of kernel class, just as you write. If you consider renaming /web dir in future, you should make it configurable. For example AsseticBundle has such an option in its DI configuration (see here and here).

Can I reach /web path from within a container in Symfony2?

we use this configuration to do just this.

in parameters.yml

upload_path: "/images/uploads"
upload_dir: "%kernel.root_dir%/../web%upload_path%"

we split path from dir just for simplicity of reading.

in the controller:

$work_dir = $this->container->getParameter('upload_dir');

How to get web directory path from inside Entity?

You shouldn't use entity class as a form model here. It's simply not suitable for that job. If the entity has the path property, the only valid values it can stores are: null (in case lack of the file) and string representing the path to the file.

  1. Create a separate class, that's gonna be a model for your form:

    class MyFormModel {
    /** @Assert\File */
    private $file;

    /** @Assert\Valid */
    private $entity;

    // constructor, getters, setters, other methods
    }
  2. In your form handler (separate object configured through DIC; recommended) or the controller:

    ...
    if ($form->isValid()) {
    /** @var \Symfony\Component\HttpFoundation\File\UploadedFile */
    $file = $form->getData()->getFile();

    /** @var \Your\Entity\Class */
    $entity = $form->getData()->getEntity();

    // move the file
    // $path = '/path/to/the/moved/file';

    $entity->setPath($path);

    $someEntityManager->persist($entity);

    return ...;
    }
    ...

Inside form handler/controller you can access any dependencies/properties from DIC (including path to the upload directory).


The tutorial you've linked works, but it's an example of bad design. The entities should not be aware of file upload.

Symfony 4, get the root path of the project from a custom class (not a controller class)

In Symfony AppKernel class is handling the project root directory under method getProjectDir(). To get it in the controller you can do:

$projectRoot = $this->get('kernel')->getProjectDir();

it will return you a project root directory.

If you need the project root directory in one of your classes you have two choices which I will present to you. First is passing AppKernel as dependency:

class Foo 
{
/** KernelInterface $appKernel */
private $appKernel;

public function __construct(KernelInterface $appKernel)
{
$this->appKernel = $appKernel;
}
}

Thanks to Symfony 4 autowiring dependencies it will be autmomaticaly injeted into your class and you could access it by doing:

$this->appKernel->getProjectDir();

But please notice: I don't think it's a good idea, until you have real need and more to do with AppKernel class than getting the project root dir. Specially if you think later on creating about unit tests for your class. You would automatically increase complexity by having a need to create mock of AppKernel for example.

Second option and IMHO better would be to pass only a string with path to directory. You could achieve this by defining a service inside config/services.yaml like this:

services:
(...)
MyNamespace\Foo:
arguments:
- %kernel.project_dir%

and your constructor would look like:

class Foo 
{
/** string $rootPath */
private $rootPath;

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

Symfony2 How to get the Web or MyBundle directory from inside a controller?

The realpath function (http://php.net/manual/en/function.realpath.php) can clean up all the dot dot stuff if it bothers you.

// From a controller
$resourceDir = realpath(__DIR__ . '/../Resources');

Of course this only works if the controller is in a fixed directory and never moves.

I like to set a parameter using the dependency injection extension.

class CeradProjectExtension extends Extension
{
public function load(array $configs, ContainerBuilder $container)
{
$configuration = new Configuration();
$config = $this->processConfiguration($configuration, $configs);

$container->setParameter(
'sportacus_project_resources_dir',
realpath(__DIR__ . '/../Resources')
);

The path can be injected or retrieved from the container.

Symfony2 get root directory path from command class

By extending ContainerAwareCommand you can access the root directory path using:

$this->getContainer()->get('kernel')->getRootDir()

See http://symfony.com/doc/current/cookbook/console/console_command.html#getting-services-from-the-service-container

Symfony: get file in controller from web folder

Try this -

Append this to autoload.php

define('APPLICATION_PATH', realpath(__DIR__) . '/');
define('WEB_PATH', APPLICATION_PATH . '../web/');

also you can add another folders

Then

file_get_content(WEB_PATH . 'your_file.pdf');

Another way -

$path = $this->getParameter('dir.downloads');

But don't forget to declare it on parameters.yml like this

parameters:
....
dir.downloads: var/www (your folder)
....

How to get the absolute path of a file in Symfony2?

$path = realpath($this->get('kernel')->getRootDir() . "/../doc/" . $filename . '.pdf');

http://php.net/manual/en/function.realpath.php

EDIT: realpath also check if path exists. So it could be used only on existing part of path.

How to directly access an image from web directory using FOSREST

/web/ directory is you (public) document root, so it's the place where your domain points.

Assuming e.g. you have virtual host example.lc which points to /path/to/project/web/, then instead of requesting:

http://example.lc/web/uploads

You should try with:

http://example.lc/uploads

When you're trying to access:

http://example.lc/web/uploads

Webserver really looks for /path/to/project/web/web/uploads, and since this path doesn't exist, it rewrites the URL to app.php which is Symfony application entry point.

How to get current relative URL in Symfony2 service?

This was actually a lot simpler than I thought. All I had to use was:

$request->getRequestUri();

And it returns exactly what I was looking for.



Related Topics



Leave a reply



Submit