Call createForm () and generateUrl () from a service in Symfony2

I would like to access controller methods from my user service. I created the MyManager class, and I need to call the createForm() and generateUrl() functions inside it. In the controller I can use: $this->createForm(...) and $this->generateUrl(...) , but what about the service? Maybe? I really need these methods! What arguments should I use?

+6
source share
2 answers

If you look at these two methods in the Symfony\Bundle\FrameworkBundle\Controller\Controller class, you will see the service 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 need router and form.factory to implement the functionality. I do not recommend passing the controller to your class. Controllers are special classes that are used mainly by the framework itself. If you plan to use your class as a service, just create one.

 services: my_manager: class: Something\MyManager arguments: [@router, @form.factory] 

Create a constructor with two arguments for the services and implement the necessary 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 ... } 
+20
source

Assuming you enter a service in 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"); } } 
0
source

Source: https://habr.com/ru/post/984579/


All Articles