How to get public folder absolute path in Shopware 6?
Asked Answered
B

3

6

I'm trying to get a public folder path in shopware 6 in order to create a directory inside using the filesystem. Does anyone have an idea about it?

Broadnax answered 17/8, 2021 at 15:15 Comment(1)
Do you mean the folder path or the base URL?Breezy
B
5

You could have a look at the service

shopware.filesystem.public which is defined in

vendor/shopware/core/Framework/DependencyInjection/filesystem.xml as

   <service class="League\Flysystem\FilesystemInterface" id="shopware.filesystem.public" public="true">
        <factory service="Shopware\Core\Framework\Adapter\Filesystem\FilesystemFactory" method="factory"/>
        <argument>%shopware.filesystem.public%</argument>
    </service>

When you inject this service, you can call

$publicFileSystem->createDir('folder')

to create your folder.

That does not exactly answer the question on how to get the path - but you usually don't need that, as you woult not interact directly with the filesystem, but via Flysystem classes instead.

If you really need the path, you could try something like

$publicFileSystem->getMetaData('.')['path']

This is untested by me and as written before, you might just not need the path. Also keep in mind, that the underlying filesystem might not even be a local storage.

Breezy answered 17/8, 2021 at 15:20 Comment(1)
I inject the service in the constructor but I get an error when I try to use it: $fileSystem must not be accessed before initialization. Do you know what am I missing?Mccain
R
2

Maybe not exactly bulletproof, but most of the time you can also use getcwd();

https://www.php.net/manual/en/function.getcwd.php

I mostly use it for writing debug-files like error_log(print_r($data, true)."\n", 3, getcwd().'/error.log');

Redhead answered 17/8, 2021 at 17:27 Comment(3)
Are you sure that gets the public/ folder, not the Shopware root most of the time?Breezy
It worked every time I tested it, even with console commands. I guess it's because everything is initiated by the index.php in the public folder.Redhead
This isn't reliable in my experience. Sometimes it's the root folder (scheduled tasks), sometimes the public one (flow event handlers).Palua
L
0

Instead of trying to get the public path through the file-system, you can also simply inject the according config from it via:

'%shopware.filesystem.public.config.root%'

This will give you the path to the public-directory.

Lotuseater answered 25/3 at 8:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.