Accessing Files Relative to Bundle in Symfony2
As a matter of fact, there is a service you could use for this, the kernel ($this->get('kernel')
). It has a method called locateResource()
.
For example:
$kernel = $container->getService('kernel');
$path = $kernel->locateResource('@AdmeDemoBundle/path/to/file/Foo.txt');
access static file within bundle controller/service etc
This will help you: https://stackoverflow.com/a/16498845/1353837
I think you should execute app/console assets:install
before
Access a Static File Located in Symfony Bundle
Controller Access
You can access to the root dir thanks to this :
$this->get('kernel')->getRootDir();
It will place into app/
directory and then you can navigate as you want
So in your case I think this will be work:
$fileToYourPath = $this->get('kernel')->getRootDir().'/../src/C2Educate/ToolsBundle/Stripe/c2/c2.html'
Service Access
You can access to the root dir by injecting container (dependency injection pattern)
use Symfony\Component\DependencyInjection\ContainerInterface;
class MyClass
{
private $container;
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function doWhatever()
{
$root = $this->container->get('kernel')->getRootDir();
$fileToYourPath = $root.'/../src/C2Educate/ToolsBundle/Stripe/c2/c2.html'
}
}
In your services.yml, define your new service:
myclass:
class: ...\MyClass
arguments: ["@service_container"]
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.
Related Topics
Keeping Url Parameters During Pagination
PHP - Merge Two Arrays (Same-Length) into One Associative
Saving Images in Database MySQL
PHP Datetime Round Up to Nearest 10 Minutes
Mysql_Real_Escape_String Is Undefined
File_Get_HTML Displays Fatal Error Call to Undefined Function
PHP - Add Link to a Url in a String
Process Mathematical Equations in PHP
What Does the MySQLi_Error() Expects Parameter 1 to Be MySQLi, Null Given Mean
Send Email with Attachment Using PHP