问题
Can someone explain me the difference between both interfaces InputFilterAwareInterface and InputFilterProviderInterface? Both seem to serve to the same purpose, to get an InputFilter, but I know they cannot be the same... And when do they get called?
Thanks
回答1:
Both interfaces exist for different purposes. The InputFilterAwareInterface guarantees that implemented classes will have a setInputFilter()
and getInputFilter()
methods which accept and return an InputFilter instance when necessary. On the other hand, the InputFilterProviderInterface guarantees only that implemented classes will have a getInputFilterSpecification()
method which returns a filter specification (configuration array) which is ready to use as argument in various input factories.
For example; the snippet below came from Zend\Form\Form.php
class:
if ($fieldset === $this && $fieldset instanceof InputFilterProviderInterface) {
foreach ($fieldset->getInputFilterSpecification() as $name => $spec) {
$input = $inputFactory->createInput($spec);
$inputFilter->add($input, $name);
}
}
As you can see, the Form class creates inputs and binds them to related filter using given specification which is returned by getInputFilterSpecification()
method of the implementing class ($fieldset int this case).
Using Traits
Zend Framework 2 also provides lot of traits for commonly used interfaces. For example InputFilterAwareTrait for InputFilterInterface. This means, you can easily implement that interface if you have PHP >= 5.4
namespace MyNamespace;
use Zend\InputFilter\InputFilterInterface;
MyClass implements InputFilterInterface {
// Here is the trait which provides set and getInputFilter methods
// with a protected $inputFilter attribute to all MyClass instances.
use \Zend\InputFilter\InputFilterAwareTrait;
// Your other methods.
...
}
Now anywhere in your code, you can do this:
$myClass->setInputFilter($AnInputFilterInstance);
$myClass->getInputFilter(); // Returns an inputfilter instance.
As you can imagine, no trait exists for InputFilterProviderInterface because its responsibility is only returning a valid config spec. It doesn't deal with any instance or class attribute like is forced in InputFilterInterface.
来源:https://stackoverflow.com/questions/24726440/difference-between-inputfilterawareinterface-and-inputfilterproviderinterface-in