zf2尝试将输入过滤器注入服务中

I'm attempting to create a custom filter and inject it into a service via factory.

use Zend\InputFilter\InputFilter; 
class WSRequestFilter extends InputFilter{

    protected $inputFilter;

    public function init(){
        $this->add( array(
            'name' => 'apiVersion',
            'required' => true,
            'filters' => [
                array('name' => 'Real'),
...

In Module.php...

public function getServiceConfig(){
    return array(
        ...
        'factories' => array(
            'Puma\Service\WebServiceLayer' => function($sm) {
                $wsRequestFilter = new Filter\WSRequestFilter();
                $wsRequestFilter->init();
                $wsl = new Service\WebServiceLayer($wsRequestFilter);
                return $wsl;
            },
        ),
    );
}

But I get service not found exception when executing $wsRequestFilter->init();. I have also tried to initialize the filter using the InputFilterManager similar to here but I got a service not found trying to access the manager via $serviceManager->get('InputFilterManager'). I think I am missing something fundamental here.

The init() method invoked automatically by InputFilterManager just after the filter object created. You don't need to invoke manually.

Add this to your module configuration:

'input_filters' => array(
    'invokables' => array(
        'ws-request-filter' => '\YourModule\Filter\WSRequestFilter',
     ),
),

And change your service factory like below:

public function getServiceConfig(){
    return array(
        ...
        'factories' => array(
            'Puma\Service\WebServiceLayer' => function($sm) {
                $filter = $sm->get('InputfilterManager')->get('ws-request-filter')
                $wsl = new \YourModule\Service\WebServiceLayer($filter);
                return $wsl;
            },
        ),
    );
}

It should work.