Difference between InputFilterAwareInterface and InputFilterProviderInterface in ZF2

元气小坏坏 提交于 2019-12-08 03:12:03

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!