2016-10-03 66 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()將永遠只用於確定如何處理選擇的數組。