Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

symfony

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?

like image 448
ZaquPL Avatar asked Apr 01 '15 18:04

ZaquPL


1 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 ...
}
like image 188
kba Avatar answered Nov 16 '22 19:11

kba