if i have 1 service, i can load my service through dependency injection like:

class MyForm extends FormBase {

  protected $coreService;

   * Class constructor.
  public function __construct($coreService) {
    $this->coreService = $coreService;

   * {@inheritdoc}
  public static function create(ContainerInterface $container) {
    return new static( $container->get('arm_core.core_service') );

but now let say i have 2 services, how i load the service through dependency injection rather than globally?

class MyForm extends FormBase {

  protected $coreService
  protected $mainService;


Thank you

1 Answer 1


The key idea here is that if the class you are using implements the ContainerInjectionInterface, you get passed a container object from which you can get any service you like. Since FormBase implements this, your form will already be able to do this.

Here's some code from D8's file example, from the Example Module, as an example:

   * Constructs a new FileExampleReadWriteForm page.
   * @param StateInterface $state
   *   Storage interface for state data.
   * @param FileSystemInterface $file_system
   *   Interface for common file system operations.
   * @param StreamWrapperManagerInterface $stream_wrapper_manager
   *   Interface to obtain stream wrappers used to manipulate a given file
   *   scheme.
   * @param ModuleHandlerInterface $module_handler
   *   Interface to get information about the status of modules and other
   *   extensions.
   * @param RequestStack $request_stack
   *   Access to the current request, including to session objects.
  public function __construct(
    StateInterface $state,
    FileSystemInterface $file_system,
    StreamWrapperManagerInterface $stream_wrapper_manager,
    ModuleHandlerInterface $module_handler,
    RequestStack $request_stack
  ) {
    $this->state = $state;
    $this->fileSystem = $file_system;
    $this->moduleHandler = $module_handler;
    $this->requestStack = $request_stack;
    $this->streamWrapperManager = $stream_wrapper_manager;
    $this->sessionSchemeEnabled = $this->moduleHandler->moduleExists('stream_wrapper_example');

   * {@inheritdoc}
  public static function create(ContainerInterface $container) {
    $state = $container->get('state');
    $file_system = $container->get('file_system');
    $module_handler = $container->get('module_handler');
    $request_stack = $container->get('request_stack');
    $stream_wrapper_manager = $container->get('stream_wrapper_manager');
    return new static($state, $file_system, $stream_wrapper_manager, $module_handler, $request_stack);

Your create() function calls your constructor, and since you've received a services container, you can ask for whatever and however many services you want.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.