Edit, seeing that this post has attracted so much attention, and mine is at the top, the best way to get the root directory is to pass it to your class as an argument to the constructor. You would use services.yml for this and in the arguments:
serviceName: class: Name\Of\Your\Service arguments: %kernel.root_dir%
Then the following code will have the root directory assigned to it when the environment creates it:
namespace Name\Of\Your; class Service { public function __construct($rootDir) {
The rest of the answer below is the old, bad way to do this without using dependency injection.
I want everyone to know that this is a Locator , which is an anti-pattern . Any developer should be able to see which class or controller should function only from the method signature . Putting the whole โcontainerโ is very common, difficult to debug, and not the best way to do things. You should use the Contentioner Injection Dependency container, which allows you to specifically specify what you want anywhere in the application. Be specific. Check out the seriously awesome recursive instance of the dependency injection container called Auryn . If your infrastructure allows your controller / action, put it there and use the container to create the controller and run this method. Boom! Instant SOLID code.
You are right, access to the service container is done using $this->get('service') .
However, to use $this->get() , you will need access to the get() method.
Controller access
You gain access to this and many other convenient methods by making sure that your controller extends the base controller class that Symfony uses.
Make sure you reference the correct base controller class:
use Symfony\Bundle\FrameworkBundle\Controller\Controller; class HelloController extends Controller { $root = $this->get('kernel')->getRootDir(); }
Access to services
If you want to access the container from a service, you need to define your controller as a service . You can find more information in this post , this post and this post on how to do this. Another useful link . In any case, you now know what to look for. This post may also be helpful:
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(); } }
In your config.yml, define your new type:
myclass: class: ...\MyClass arguments: ["@service_container"]
For more information on service container, see.