Search code examples
apisymfonyservicedependenciesinject

Symfony - Create Service object with parameters


I created a new service in my symfony application:

namespace AppBundle\Service;

class CustomService {

    public function __construct($username, $password) {
        // stuff
    }

    public function getItems() {

    }

}

and configured in config.yml:

services:
    custom_service:
        class:          AppBundle\Service\CustomService

My question is, how to create an object from this service with multiple arguments?

Like:

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class CustomController extends Controller {

    public function listAction() {

        $custom_service = $this->get('custom_service'); //how to pass multiple arguments here?

        // Next i would use my custom service, like:
        $items = $custom_service->getItems();

    }

}

Anybody knows how to solve this issue?

Thanks and Greetings!


Solution

  • Basically you don't. The container supports injecting dependencies. Doing what you propose kind of defeats the purpose of using a dependency injection container.

    One work around is to add an init method to your object.

    $custom_service = $this->get('custom_service')->init($additional_arguments);