变量方法的变量属性

Variable properties on a variable method

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

$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);
    }                
  }
}

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

查看 call_user_func_array()

你必须使用 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);
    }                
  }
}