Inject service in FOSRest Controller - symfony

I am new at symfony and trying to create REST api using FOSRest Bundle. Also i want to use flysystem library as service in my controllers. It is simple as that
class FileController extends FOSRestController
{
public function getFilesAction()
{
$filesystem = $this->container->get('oneup_flysystem.application_filesystem');
...
}
}
This works fine, but my idea is to Inject this service into FileController so i can use $filesystem service in every method in my controller.
I read about it, that I have to make my controller as service, but then something went wrong. What is the proper way to make this injection.

We use something like this:
YourBundle/Resources/config/services.yml
controller.file:
class: YourBundle\Controller\FileController
arguments:
- #yourFileService
- #service_container
YourBundle/Controller/FileController.php
/**
* #Route("/file", service="controller.file")
*/
class FileController extends Controller
{
/**
* #var Filesystem
*/
private $filesystem;
/**
* #param Filesystem $filesystem
* #param $container
*/
public function __construct(
Filesystem $filesystem,
$container
) {
$this->filesystem = $filesystem;
$this->container = $container;
}

Related

(Symfony 4) How can I get the base URI of my project (the http://www.yourwebsite.com/) from within a non-controller class?

How can I get the "http://www.yourwebsite.com" from my repository class in Symfony 4?
The reason why I need to do this is because I'm using the Liip image service which returns the entire url, and I only need the url relative to the root, so I have to strip out the "http://www.yourwebsite.com" from the path returned.
I have used KernelInterface and that only returns the path from within your machine (i.e. the var/www/... in your machine).
I've tried injecting http foundation's Request object so I can call the getPathInfo() method, here is what I have in my repository class:
use Symfony\Component\HttpFoundation\Request;
class PhotoRepository extends ServiceEntityRepository
{
/**
* #var Request
*/
protected $request;
public function __construct(Request $request){
$this->request = $request;
}
But I just get the error Cannot autowire service "App\Repository\PhotoRepository": argument "$request" of method "__construct()" references class "Symfony\Component\HttpFoundation\Request" but no such service exists.
Here is what I have under "services" in my services.yaml:
App\Repository\PhotoRepository:
arguments:
- Symfony\Component\HttpFoundation\Request
Here is the full path to my file generated:
"http://www.mywebsite.com/media/cache/my_thumb/tmp/phpNbEjUt"
I need to parse out the get the http://www.mywebsite.com and just get the /media/cache/my_thumb/tmp/phpNbEjUt from the path.
As Cerad already wrote in the comments, you can inject the Symfony\Component\HttpFoundation\RequestStack:
App\Repository\PhotoRepository:
arguments:
- Symfony\Component\HttpFoundation\RequestStack
- Doctrine\Common\Persistence\ManagerRegistry
Your constructor for the PhotoRepository will then look something like:
class PhotoRepository extends ServiceEntityRepository
{
/**
* #var RequestStack
*/
protected $requestStack;
public function __construct(RequestStack $requestStack, ManagerRegistry $managerRegistry)
{
parent::__construct($managerRegistry, Photo::class);
$this->requestStack = $requestStack;
}
...
}
You can then determine the current URL using something like this:
private function getCurrentUrl(): string
{
$request = $this->requestStack->getCurrentRequest();
return $request->getBaseUrl(); // or possibly getUri()
}

Symfony3 Use Entity Manager in Custom Container

I want to create HelperController for my project. I generate a controller with doctrine:generate:controller and I need to use entity manager in it.
I enjected to services.yml but it is giving an error like this:
Argument 1 passed to CampingBundle\Controller\HelperController::__construct() must be an instance of Doctrine\ORM\EntityManager, none given ...
My Controller Code :
namespace CampingBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Doctrine\ORM\EntityManager;
class HelperController extends Controller
{
protected $manager;
public function __construct(EntityManager $manager)
{
$this->manager = $manager;
}
My Services.yml :
services:
camping.helper_controller:
class: CampingBundle\Controller\HelperController
arguments: ["#doctrine.orm.entity_manager"]
Why it doesn't work ? Shoudl I clear cache or something else or is there anything wrong in definition ?
Thanks
Try to use EntityManagerInterface and remove extends Controller.
Check this link if you need CAS (Controllers as Services).
Change protected $manager; to private $manager;
namespace CampingBundle\Controller;
use Doctrine\ORM\EntityManagerInterface;
class HelperController
{
/**
* #var EntityManagerInterface $entityManager
*/
private $entityManager;
/**
* #param $entityManager
*/
public function __construct(EntityManagerInterface $entityManager)
{
$this->entityManager = $entityManager;
}
}
I'll leave my two cents here as I had same issue and fixed it by adding tags to service.
something.validate.some_service:
class: Path\To\Some\Validator
arguments:
- '#doctrine.orm.entity_manager'
tags:
- { name: validator.constraint_validator, alias: some_validator_alias }
How to Work with Service Tags by Symfony

Symfony2, use getDoctrine and em in class

I have a Timesheet.php class in Symfony2, and i need, in this class, use for example :
$this->getDoctrine()->getRepository()->find();
$this->getDoctrine()->getManager()->remove();
How can i do that ? I have try to call the class as a service, manually add variable in constructor and other but no effect...
Do you have a good solution ?
This is because $this->getDoctrine() is method of Symfony\Bundle\FrameworkBundle\Controller class. When you check this method there is $this->container->get('doctrine') so what you need is having doctrine available in your Timesheet class. To do so, define your Timesheet class as a service:
your.service_id:
class: Acme\DemoBundle\Timesheet
arguments: [#doctrine]
Then your Timesheet class:
use Doctrine\Bundle\DoctrineBundle\Registry;
class Timesheet
{
/**
* #var Registry
*/
private $doctrine;
/**
* #param Registry $doctrine Doctrine
*/
public function __construct(Registry $doctrine)
{
$this->doctrine = $doctrine;
}
public function yourMethod()
{
//this is what you want to achieve, right?
$this->doctrine->getManager()->remove();
$this->doctrine->getRepository()->find();
}
}

Create a Base-Controller Class which implements the ContainerAwareInterface

I followed the tutorial of Fabien Potiencier, about how to create your own Framework on top of the Symfony Components. Now i need a way. And I want to inject the Dependency Container to all my Controllers, without defining every single Controller as a Service.
In the orginal Symfony2 Framework all Controllers extends the Controller Class located in Symfony\Bundle\FrameworkBundle\Controller\Controller.php:
namespace Symfony\Bundle\FrameworkBundle\Controller;
class Controller extends ContainerAware
{
// ...
}
The Controller Class extends the ControllerAware Class, so you can do something like this in your Controller:
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class MyController extends Controller
{
public function someAction()
{
$this->container->get('dependencie_xyz);
}
}
So my question is: How can I accomplish the same in my Framework?
It took me a while, but i finally figured out how the Symfony2 Framework does it.
In the SymfonyFrameworkBundle is a custom ControllerResolver, which call the setContainer Method on the resolved controller. The controller has to be a instance of the ContainerAwareInterface.
Simplified version:
class ContainerAwareControllerResolver extends ControllerResolver
{
private $container;
public __construct(ContainerInterface $container)
{
$this->container = $container;
parent::__construct();
}
public function getController(Request $request)
{
$controller = parent::getController($request);
if($controller instanceof ContainerAware ){
$controller->setContainer($this->container);
}
}
}
Source:
https://github.com/symfony/symfony/blob/master/src/Symfony/Bundle/FrameworkBundle/Controller/ControllerResolver.php
It is too simply. The next code will help you
namespace Symfony\Bundle\FrameworkBundle\Controller;
use Symfony\Component\DependencyInjection\ContainerInterface as Container;
use Symfony\Component\DependencyInjection\ContainerAware as ContainerAware;
class TestService extends ContainerAware
{
public function __construct(Container $container) {
// in your example from official doc 'dependencie_xyz' is a name of service
$this->setContainer($container); // call parent setContainer() method, for identifying container variable, from now you can access to ServiceContainer using $this->container variable
$test_param = $this->container->getParameter('test_param'); // get test_param from config.yml
}
}
in service.yml
write smthing like this
services:
test_service:
class: Symfony\Bundle\FrameworkBundle\TestService
arguments: ['#service_container']
and post service container as argument
If you are not implementing any interface on controller you can add the this way and it will work. This is a small modification to c4pone implementation.
/**
* Description of ContainerAwareControllerResolver
*
* #author sbc
*/
use Psr\Log\LoggerInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\HttpKernel\Controller\ControllerResolver;
class ContainerAwareControllerResolver extends ControllerResolver {
private $container;
public function __construct(LoggerInterface $logger = null, ContainerInterface $container = null) {
parent::__construct($logger);
$this->container = $container;
}
protected function instantiateController($class) {
$new_class = new $class();
$new_class->setContainer($this->container);
return $new_class;
}
The Controller Class extends the ControllerAware Class, so you can do something like this in your Controller:
Well, this is not true. If we take a look at the signature of the ContainerAware class, we see that this added a setContainer method so we can set the container. Symfony2 has created the Controller::get method to make some live easier.
We can see how they do it in the source code:
/**
* Gets a service by id.
*
* #param string $id The service id
*
* #return object The service
*/
public function get($id)
{
return $this->container->get($id);
}
You can put this in your own Controller class and let all your controllers extend that controller class.

Lookup route in symfony 2

I've defined a route in my app routing file:
RouteName:
pattern: /some/route
defaults: { _controller: MyAppBundle:Controller:action }
In a controller I can use:
$this->get('router')->generate('RouteName');
How would I simply access that from a fresh class I create, for example a view class that doesn't extend anything:
namespace My\AppBundle\View;
class ViewClass {
public function uri()
{
return getTheRoute('RouteName');
}
}
You need to inject "router" service into your ViewClass. Eg. in place where your define your ViewClass service:
viewclass.service:
class: Namespace\For\ViewClass
arguments:
router: "#router"
and then in your constructor:
public function __construct(\Symfony\Bundle\FrameworkBundle\Routing\Router $router)
{
$this->router = $router;
}
The clue is in how the $this->generateUrl() method works in Controllers. See:
/**
* Generates a URL from the given parameters.
*
* #param string $route The name of the route
* #param mixed $parameters An array of parameters
* #param Boolean $absolute Whether to generate an absolute URL
*
* #return string The generated URL
*/
public function generateUrl($route, $parameters = array(), $absolute = false)
{
return $this->container->get('router')->generate($route, $parameters, $absolute);
}
So you'll need to define your class as a service and inject the #router service. Either that or have your class implement ContainerAwareInterface, but the first method would definitely be better.
You should register your class as a service and insert the router as a dependency.
See the chapter on the service container in the excellent symfony2 docs.
If you're not familiar with the concepts of the service container and dependency injection, you might feel a bit overwhelmed. However, try your best to understand it because it is a essential part of the symfony2 architecture.
You could pass the entire container from your controller to your view class on instantiation. This is NOT BEST PRACTICE and not recommended.
class View
{
protected $container;
public function __construct(\Symfony\Component\DependencyInjection\Container $container)
{
$this->container = $container;
}
}
Then in your code you could use
$this->container->get('router')->generate($route, $parameters, $absolute);

Resources