I'm developing a site using ZF2. One of the section in footer contains tweets. I can fetch tweets but I am not sure how to display them in the layout. I have following ideas but not sure which approach to use
- Create a controller plugin and use it on each request.
- Create a ViewHelper which fetches the tweets from the
ServiceLocator
and call the helper in the layout - Attach an event to the
MvcEvent::EVENT_RENDER
in the module.php which sets the html to a layout variable.
If there is anyother better approach, please let me know.
What you are refering to completely is the task of a ViewHelper. So your second approach would be correct. You have two layers here
ServiceLayer - fetching the tweets from a DB / Twitter / DataSource
ViewLayer - displaying whatever the ServiceLayer give you
Now the thing is what do you want to do? Do you want to have a ViewHelper that simply renders a number of given Tweets? Then you'd not need access to the
TweetService
itself, but rather the given Data. Something like this:But most commonly such a thing isn't really that handy. You'd probably want to be able to at least change the username of the Tweets to render. So you'd need to inject the actual
TweetService
into your ViewHelper and then use the__invokable()
function of the ViewHelper to set the parameter for the Renderer:And that's the basics there are :)