I would like have access to controller methods from my custom service. I created class MyManager and I need to call inside it createForm() and generateUrl() functions. In controller I can use: $this->createForm(...) and $this->generateUrl(...), but what with service? It is possible? I really need this methods! What arguments I should use?
- You can pass your controller to your service as parameter, then call $controller->createForm(...)rogeriolino– rogeriolino2015-04-01 18:44:40 +00:00Commented Apr 1, 2015 at 18:44
2 Answers
If you look to those two methods in Symfony\Bundle\FrameworkBundle\Controller\Controller class, you will see services name and how to use them.
public function generateUrl($route, $parameters = array(), $referenceType = UrlGeneratorInterface::ABSOLUTE_PATH) { return $this->container->get('router')->generate($route, $parameters, $referenceType); } public function createForm($type, $data = null, array $options = array()) { return $this->container->get('form.factory')->create($type, $data, $options); } Basically, you class need services router and form.factory for implementing functionality. I do not recommend passing controller to your class. Controllers are special classes that are used mainly by framework itself. If you plan to use your class as service, just create it.
services: my_manager: class: Something\MyManager arguments: [@router, @form.factory] Create a constructor with two arguments for services and implement required methods in your class.
class MyManager { private $router; private $formFactory; public function __construct($router, $formFactory) { $this->router = $router; $this->formFactory = $formFactory; } // example method - same as in controller public function createForm($type, $data = null, array $options = array()) { return $this->formFactory->create($type, $data, $options); } // the rest of you class ... } 1 Comment
assuming you are injecting the service into your controller , you can pass the controller object to your service function
example
class myService { public function doSomthing($controller,$otherArgs) { $controller->generateForm(); } } class Mycontroller extends Controller { public function indexAction() { $this->get("my-service")->doSomthing($this,"hello"); } } 3 Comments
$controller->get() method. At worst you could inject the @service_container and then use that ($this->container->get()) but then even that isn't best practice.