2016-10-03 68 views
2

我正在尝试使用Laravel/Symfony作为控制台的一部分提供的“选择”功能,并在涉及到数字索引时遇到问题。Laravel选择命令数字键

我试图模拟HTML选择元素的行为,因为您显示字符串值但实际取回关联的ID而不是字符串。

例子 - 不幸的是$选择总是名字,但我想要的ID

<?php 

namespace App\Console\Commands; 

use App\User; 
use Illuminate\Console\Command; 

class DoSomethingCommand extends Command 
{ 
    protected $signature = 'company:dosomething'; 

    public function __construct() 
    { 
     parent::__construct(); 
    } 

    public function handle() 
    { 
     $choice = $this->choice("Choose person", [ 
      1 => 'Dave', 
      2 => 'John', 
      3 => 'Roy' 
     ]); 
    } 
} 

解决方法 - 如果我前缀的人ID,然后它工作,但希望能有另一种方法或者这只是一个限制图书馆的?

<?php 

namespace App\Console\Commands; 

use App\User; 
use Illuminate\Console\Command; 

class DoSomethingCommand extends Command 
{ 
    protected $signature = 'company:dosomething'; 

    public function __construct() 
    { 
     parent::__construct(); 
    } 

    public function handle() 
    { 
     $choice = $this->choice("Choose person", [ 
      "partner-1" => 'Dave', 
      "partner-2" => 'John', 
      "partner-3" => 'Roy' 
     ]); 
    } 
} 
+0

'$ this'是什么? –

回答

2

我有同样的问题。我将实体列为选项,ID为键和标签为值。我认为这将是非常常见的情况,所以很难找到关于这个限制的很多信息。

问题是控制台会根据$choices数组是否是关联数组来决定是否将该键用作值。它通过检查在选择数组中是否至少有一个字符串键来确定这一点 - 所以抛出一个虚假选择是一种策略。

$choices = [ 
    1 => 'Dave', 
    2 => 'John', 
    3 => 'Roy', 
    '_' => 'bogus' 
]; 

注:你不能施放的钥匙串(即使用"1"代替1),因为使用时,PHP会一直投int类型的字符串表示,以一个真正的INT一个数组键。


我所采用的解决办法是延长ChoiceQuestion类和属性添加到它,$useKeyAsValue,迫使某个键被用作值,然后重写ChoiceQuestion::isAssoc()方法来履行这一属性。

class ChoiceQuestion extends \Symfony\Component\Console\Question\ChoiceQuestion 
{ 
    /** 
    * @var bool|null 
    */ 
    private $useKeyAsValue; 

    public function __construct($question, array $choices, $useKeyAsValue = null, $default = null) 
    { 
     $this->useKeyAsValue = $useKeyAsValue; 
     parent::__construct($question, $choices, $default); 
    } 

    protected function isAssoc($array) 
    { 
     return $this->useKeyAsValue !== null ? (bool)$this->useKeyAsValue : parent::isAssoc($array); 
    } 
} 

该解决方案有点冒险。它假定Question::isAssoc()将永远只用于确定如何处理选择的数组。