3

我正在使用操纵图像的第三方包。对于基本转换,它接受一个值:

$image = $this->addMediaConversion('thumb');
$image->width(100);
$image->height(100);

我正在构建的系统有一个抽象级别,我需要在配置文件中定义这些值。我将配置文件作为数组加载。然后我可以遍历配置文件中的值并生成我的各种转换。

我的配置文件:

return [
  'thumb' => [
    'width' => 100,
    'height' => 100,
  ],
];

从该配置定义这些转换的代码:

$definitions = config('definitions');

foreach($definitions as $name => $keys) {
  $image = $this->addMediaConversion($name);

  foreach($keys as $key => $value) {
    $image->$key($value);
  }
}

这适用SINGLE值。

但是,该包具有针对一个方法采用多个属性的方法,例如:

$image = $this->addMediaConversion('thumb');
$image->fit(Manipulations::FIT_FILL, 560, 560);

有多种方法可用,它们具有各种不同的可接受属性。我正在寻找一个*ELEGANT*解决方案。我可以通过在我的配置文件中包含一个值数组、检查类型、检查该数组的长度,然后传递正确的数字来实现它,但这不是可扩展的、易于维护的或优雅的。

配置:

return [
  'thumb' => [
    'fit' => [Manipulations::FIT_FILL, 560, 560]
  ]
];

代码:

foreach($image_definitions as $name => $keys) {
  // Generate the conversion
  $conversion = $this->addMediaConversion($name);
  // Loop through and define the attributes as they are in the config, things like ->width(), ->height()
  foreach($keys as $key => $value) {
    if(is_array($value))
    {
      // LOOKING FOR A MORE ELEGANT WAY TO DO THE BELOW
      switch(count($value)) 
      {
        case 2:
          $conversion->$key($value[0], $value[1]);
          break;
        case 3:
          $conversion->$key($value[0], $value[1], $value[2]);
          break;
        case 4:
          $conversion->$key($value[0], $value[1], $value[2], $value[3]);
          break;
        case 5:
          $conversion->$key($value[0], $value[1], $value[2], $value[3], $value[4]);
          break;
        case 6:
          $conversion->$key($value[0], $value[1], $value[2], $value[3], $value[4], $value[5]);
          break;
      }
    } else 
    {
      $conversion->$key($value);
    }                
  }
}

什么是最好和最优雅的解决方案?

4

2 回答 2

2

您必须使用 call_user_func_array,如下所示:

foreach($image_definitions as $name => $keys) {
  // Generate the conversion
  $conversion = $this->addMediaConversion($name);
  // Loop through and define the attributes as they are in the config, things like ->width(), ->height()
  foreach ($keys as $key => $value) {
    if (is_array($value)){
      call_user_func_array(array($conversion, $key), $value);
    } else {
      $conversion->$key($value);
    }                
  }
}
于 2018-02-27T11:11:52.393 回答
0

查看call_user_func_array()

于 2018-02-27T10:58:37.620 回答