简体   繁体   中英

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

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?

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 ...
}

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");
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM