Score:0

How to create a service for the class with constructor arguments from a vendor package class?

fr flag

I am trying to inject class from FFMpeg in my custom service of a module.

But the class has two constructor arguments. So how can I pass those arguments in my custom service.

my_module.services.yml

services:
  # FFMPEG Factory
  my_module.php_ffmpeg:
    class: FFMpeg\FFMpeg
    autowire: true

I understand that as there are two parameters in the costructor, we need to pass two arguments in service definition but the class doesn't have factory method. So, what arguments should I pass?

Score:3
in flag

Factory services are nothing more than classes that instantiate and return objects as an injectable (e.g. LoggerChannelFactory creates LoggerChannel instances as logger services). You can create a factory that instantiates FFMpeg\FFMpeg, makes it a service, and inject it to whatever needs it. This still fulfills dependency-injection duties. Your code won't be using FFMpeg directly but via the factory, and you can mock away the factory during testing.

// my_module/src/FFMpegFactory.php
class FFMpegFactory {
  public static function get() {
    $ffmpeg = /* instantiate driver */
    $ffprobe = /* instantiate probe */
    return new FFMpeg($ffmpeg, $ffprobe);
  }
}

// my_module/src/OtherService.php
class OtherService {
  public function __construct(FFMpeg $php_ffmpeg) {
    $this->ffmpeg = $php_ffmpeg;
  }
}

// my_module/my_module.services.yml
services:
  my_module.php_ffmpeg:
    class: 'FFMpeg\FFMpeg'
    factory: ['\Drupal\my_module\FFMpegFactory', 'get']
  my_module.other_service:
    class: '\Drupal\my_module\OtherService'
    arguments:
      - '@my_module.php_ffmpeg'
Score:0
id flag

The constructor arguments for the class are FFMpegDriver $ffmpeg and FFProbe $ffprobe. Those are the ones to inject. You must create those object instances as services also.

Alternatively you can create a custom factory to build the object.

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.