I have one thing I'm not sure how to solve in a good way: I'm trying to use ZF2 InputFilterManager
for fetching my input-filters, which make use of some own validators.
I added the validators to service manager config, so they can be fetched by InputFilterManager and get injected by keyword reference inside the InputFilter definition. that works fine, as far as validators doesn't need anyting to get injected or some objects, that are available from the ServiceLocator.
But one validator needs to get an array injected to do an in_array check inside. It is not possible to inject that array inside the validator factory, because it depends on business logic that runs before InputFilter isValid()
call happens.
Without using service manager I would inject that array with constructor of the validator and would initialize it after business logic was called. So the question is: If I remove injection by constructor to use InputFilterManager
I would need to inject it later by using: $inputFilter->get('element')->getValidatorChain()->plugin(Validator\ArrayCheck::class)->setPossibleValues($array)
- is this the way to go?
I quite like to have necessary dependencies getting injected into classes by using the constructor and it feels somehow dirty to rewrite validator to rely on a setter injection and add a check to verify the setter was used before running isValid()
logic.
Some code to explain my concern:
return [
'validators' => [
'invokables' => [
Validator\ArrayCheck::class => Validator\ArrayCheck::class
]
],
'input_filters' => [
'invokables' => [
InputFilter\Foo::class => InputFilter\Foo::class,
],
],
];
final class Process extends InputFilter
{
public function init()
{
$this->add(
[
'name' => 'foo',
'required' => true,
'allow_empty' => false,
'validators' => [
['name' => Validator\ArrayCheck::class]
],
]
);
}
}
class ArrayCheck extends AbstractValidator
{
/**
* @param array $possibleValues
* @param array|Traversable $options
*/
public function __construct(array $possibleValues = [], $options = null)
{
parent::__construct($options);
$this->possibleValues = $possibleValues;
}
/**
* @param array $possibleValues
*/
public function setPossibleValues(array $possibleValues)
{
$this->possibleValues = $possibleValues;
}
...
}
Any opinions on that?
isValid
it should be fine to inject it, right? – WiltisValid
call happens. But as I inject theInputFilter
by constructor into the class, where business logic is placed, the initialization of theInputFilter
already happend before the business logic kicks in. So there is no possibility to inject that array by constructor, only by using a setter and call it by using this ugly$inputFilter->get('element')->getValidatorChain()->plugin(Validator\ArrayCheck::class)->setPossibleValues($array)
call. It's more a matter of bad design, as I def like to have dependencies getting injected by constructor. – Mischosch