jeudi 14 octobre 2021

Symfony - Use DI to get the right instance of object into controller [closed]

I'm usin Symfony 5.3 and I have an obect Media which can be an image, a video or even PDF. The only difference (for now) is the way to display them. So I decided to create a AbstractMedia class.

abstract class AbstractMedia {
  public function getName()
  {
    // return media name
  }
  public function getPath()
  {
    // return media path
  }
  // ...so on common methods
  
  abstract public function displayMedia();
}

class MediaImage extends AbstractMedia
{
  public function displayMedia()
  {}
}

class MediaVideo extends AbstractMedia
{
  public function displayMedia()
  {}
}

Problem I need some dependency into these classes like and I would like to avoid a lot of dependencies into controller action

// controller
public function myAction(dependency1, dependency2, dependency3){
  if ($media === 'video')
    $mediaObject = new MediaVideo(dependency1, dependency3);
  else if ($media === 'image')
    $mediaObject = new MediaImage(dependency2);  
}

How use symfony DI to get the right class as service into controller action ?

Aucun commentaire:

Enregistrer un commentaire