InputFilter factory


#1

Hello,

How is supposed to be created a InputFilter instance ?

Within the filters I have a RecordExists (with custom Select) and I need to pass the coresponding TableGateway/dbAdapter.

Currently to pass to controller the input filter I am getting the inputfilter from Service Manager in Controller Factory like this:

$shelfInputFilter = $container->get(InputFilterPluginManager::class)->get(ShelfInputFilter::class);

But of course, I need to pass the table gateway/dbAdapter to the input filter…


#2

If you now use the InvokableFactory::class you could register your own factory class that injects the dependencies to your object. The example below is setup for zend-servicemanager 3+. If you seek help with version 2 factories, see: https://docs.zendframework.com/zend-servicemanager/migration/#factoryinterface

Register the factory in your module:

 public function getInputFilterConfig()
 {
     return [
         'factories' => [
             InputFilter\ShelfInputFilter::class => TableGatewayFactory::class,
         ],
     ];
 }

The factory class somewhere in your application:

    class TableGatewayFactory implements FactoryInterface
    {
        /**
         * {@inheritDoc}
         */
        public function __invoke(ContainerInterface $container, $requestedName, array $options = null)
        {
            return new $requestedName($container->get(TableGateway::class), $options);
        }
    }

Setup a constructor that accepts and handles your TableGateway::class and $options.

Another approach might be to create a factory for the validator class that injects the TableGateway::class into the validator directly. This way you don’t need to pass it along to the InputFilter. So when you add the validator to the InputFilter you could leave out the option and either fill it in the factory.

Why not an Initializers instead of the validator factory? I’m not a fan of that because it’s for a specific use case. Initalizers are cool and stuff but we already know by forehand that not alot of validators will receive this object, while a translator is a common case.