R – Widgets inside Zend Framework – Where should they go

widgetWordpresszend-framework

I've been working with Zend Framework (using Doctrine as the ORM) for quite a while now, and done a few projects with it.

In a few upcoming projects I am requiring the need for widgets similar to how WordPress does them. You have a post/page, which could look like:

Subscribe to my newsletter:
[subscribe/]

View my events
[events limit=5 sort=date/]

View this page's comments
[comments/]

Where say the subscribe widget would be replaced with Blog::subscribeWidget, and the events could be replaced with Events::eventsWidget, etc.

Now it has done my head in the past few weeks about how on earth do I do this??? I've come up with the following options:

  1. I could place the widgets within controllers, and then call them like actions. Problem here is that code could be flying between controllers, and I have read this is expensive due to the amount of dispatches.

  2. I could place the widgets as view helpers. So within the view I could have $this->renderPage($Page), which would then attend to all the widgets. Problem here is that what if the widgets need to do some business logic, like for example posting a new comment, that really shouldn't be within the view, should it?

  3. The other option is to place widgets within the model? But then how on earth do they then render content for display?

Extra complications come when:

  1. Say the comments widget would also handle posting, deleting of comments etc.

  2. Say for the events listing, if I want to do an ajax request to the next page of events, using method #2 (view helpers) how would this work?

Best Answer

If I understand you correctly your widgets will need their own action controllers, which is where their logic for fetching data to be displayed, parsing form submissions, etc. should go. The difference between a widget and a page in this case is in how it's rendered, i.e. as an HTML fragment instead of as a whole page; you can use the Action View Helper to achieve this.

If your widget includes a form it should probably use AJAX to submit the form data back to the server, so that using the widget doesn't cause the user to accidentally navigate away from the page. You can inject the required JavaScript into the page you've included the widget into by using the Head Script Helper in your widget's view and/or action.

Related Topic