变量方法的变量属性

问题描述 投票:3回答:2

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

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

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

php laravel-5 php-7 variable-variables spatie
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);
    }                
  }
}

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.