Car*_*ton 6 console command symfony laravel
我正在尝试使用Laravel / Symfony作为控制台的一部分提供的“选择”功能,并且在涉及数字索引时遇到问题。
我正在尝试模拟HTML select元素的行为,即您显示了字符串值,但实际上却获得了关联的ID,而不是字符串。
示例-不幸的是$ choice始终是名称,但我想要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'
]);
}
}
Run Code Online (Sandbox Code Playgroud)
解决方法-如果我在人员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'
]);
}
}
Run Code Online (Sandbox Code Playgroud)
这可能是也可能不是最好的选择,但如果你正在做一些非常简单的事情,那么:
$options = [
1 => 'Dave',
2 => 'John',
3 => 'Roy',
];
$choice = array_search(
$this->choice('Choose person', $options),
$options
);
Run Code Online (Sandbox Code Playgroud)
我有同样的问题。我将实体列为选择,以ID为键,标签为值。我认为这将是非常普遍的情况,因此很惊讶地发现没有太多有关此限制的信息。
问题在于,控制台将根据$choices数组是否为关联数组来决定是否将键用作值。它通过检查choices数组中是否至少有一个字符串键来确定这一点-因此,抛出一个伪造的选择是一种策略。
$choices = [
1 => 'Dave',
2 => 'John',
3 => 'Roy',
'_' => 'bogus'
];
Run Code Online (Sandbox Code Playgroud)
注意: 您不能将键转换为字符串(即使用"1"代替1),因为当用作数组键时,PHP始终会将一个整数的字符串表示形式转换为一个真正的整数。
我采用的解决方法是扩展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);
}
}
Run Code Online (Sandbox Code Playgroud)
这种解决方案有点冒险。它假定Question::isAssoc()将仅用于确定如何处理选择数组。
我遇到过同样的问题。图书馆里似乎没有这个选项。我通过将索引或 id 与数组中的值连接起来解决了这个问题。例如
$choices = [
1 => 'Dave-1',
2 => 'John-2',
3 => 'Roy-3'
];
$choice = $this->choice('Choose',$choices);
Run Code Online (Sandbox Code Playgroud)
然后在 '-' 之后得到那部分,就像
$id = substr( strrchr($choice, '-'), 1);;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1066 次 |
| 最近记录: |