Symfony - 使用参数创建服务对象

Symfony - Create Service object with parameters

我在我的 symfony 应用程序中创建了一个新服务:

namespace AppBundle\Service;

class CustomService {

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

    public function getItems() {

    }

}

并在config.yml中配置:

services:
    custom_service:
        class:          AppBundle\Service\CustomService

我的问题是,如何使用多个参数从该服务创建对象?

喜欢:

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();

    }

}

有人知道如何解决这个问题吗?

谢谢和问候!

基本上你不会。该容器支持注入依赖项。做你建议的事情违背了使用依赖注入容器的目的。

一种解决方法是向您的对象添加一个 init 方法。

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