Reputation: 4678
In my ZF2 application, I am trying to write a plugin to provide a wrapper around PHP Date utilities. I have planed this plugin would have apis to initialize, convert and retrieve date values.
I know how to write a plugin for Controller by extending
Zend\Mvc\Controller\Plugin\AbstractPlugin class
and also know hot to write a plugin for View by extending
Zend\View\Helper\AbstractHelper class.
But how we can write a single plugin which would be used both in Controller and View?
Upvotes: 1
Views: 2203
Reputation: 1576
If you're using php 5.4, consider creating a trait that is used in a plugin and view helper.
Upvotes: 0
Reputation: 2251
I would write an class (factory or invokable) that can be retrieved from the ServiceManager and let both plugin types access this class. This allows you to keep your logic and functionality in a single class, Zend Navigation takes a similar approach with data for the navigation being stored within a factory class shared between the helpers.
A very hacky alternative is to create a Controller plugin and then request your controller plugin through the controller plugin manager, which is available from the ServiceManager. Of course the View plugin would need to be of ServiceManagerAwareInterface
to access the ServiceManager.
$plugin = $this->getServiceManager()->get('ControllerPluginManager')->get('myplugin');
Then pass the __invoke()
parameters to the plugin. Whilst this is doable the first approach is much better.
Upvotes: 6
Reputation: 3379
You can't. As you've stated correctly, controller plugins and viewhelpers extend different classes which makes them incompatible to each other.
Also, it doesn't really make sense to mix controller plugins with view helpers because they both fulfill completely different purposes. Controller plugins are used to perform commonly used portions of business logic, viewhelpers, however, provide reusable view logic.
I'd suggest to create a class which is capable of date conversion (or whatever you need) and create an atomic view helper to render dates in the desired format (using this class). However, I wouldn't necessarily create a controller plugin for this, because you can easily retrieve the instance of this class using the service manager.
Note: I consider my answer to be rather general -- I haven't really taken into account what exactly you're trying to do (with other words: I didn't think about if it makes sense to create a wrapper for Date functions). If my answer doesn't fit your problem, please, feel free to state your question more closely.
Upvotes: 1