From inside a controller I need to get the path of one directory inside a bundle. So I have:
class MyController extends Controller{
public function copyFileAction(){
$request = $this->getRequest();
$directoryPath = '???'; // /web/bundles/mybundle/myfiles
$request->files->get('file')->move($directoryPath);
// ...
}
}
How to get correct $directoryPath
?
There is a better way to do it:
$this->container->get('kernel')->locateResource('@AcmeDemoBundle')
will give an absolute path to AcmeDemoBundle
$this->container->get('kernel')->locateResource('@AcmeDemoBundle/Resource')
will give path to Resource dir inside AcmeDemoBundle, and so on...
InvalidArgumentException will be thrown if such dir/file does not exist.
Also, on a container definition, you can use:
my_service:
class: AppBundle\Services\Config
arguments: ["@=service('kernel').locateResource('@AppBundle/Resources/customers')"]
EDIT
Your services don't have to depend on kernel. There is a default symfony service you can use: file_locator. It uses Kernel::locateResource internally, but it's easier to double/mock in your tests.
service definition
my_service:
class: AppBundle\Service
arguments: ['@file_locator']
class
namespace AppBundle;
use Symfony\Component\HttpKernel\Config\FileLocator;
class Service
{
private $fileLocator;
public function __construct(FileLocator $fileLocator)
{
$this->fileLocator = $fileLocator;
}
public function doSth()
{
$resourcePath = $this->fileLocator->locate('@AppBundle/Resources/some_resource');
}
}
Something like this:
$directoryPath = $this->container->getParameter('kernel.root_dir') . '/../web/bundles/mybundle/myfiles';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With