Preload data in the view a good idea?

I am doing an API application and I was thinking if I preload the needed data in the view instead of having to preload it every time in the controller is that a good idea?

In my opinion, absolutely not! The View should handle only view related things, it should never absolutely ever access the database or any other data store. ^.^

1 Like

I’ll disagree only because sometimes there are view related things that involve accessing the database.

Specifically layout related items like menus, footers, sidebars. The actual database code shouldn’t be in the view, but there isn’t anything wrong with having a view call a function that gets data from somewhere rather than depending on it to be passed in every time.

99% of the time I agree with @OvermindDL1 but “never” is a strong word.

I handle those by just tossing in a bulk of data to my render functions for them. If something is conditional and expensive (a database lookup that is used in, say, a global view but only ‘sometimes’) then I pass in a function instead that can be called or not as necessary. Regardless I know everything that a view could potentially access by passing it through it’s render function, and I consider that very important for reliability (no surprising database hits for example).

1 Like

I do consider in the view acceptable under circumstances, but would never ever do it in the template.

I’d think long and hard before putting any side-effect code in the views though. It is tempting and perhaps initially easier to do this but if you know that any complicated layout and view code is pure it is so much easier to deal with.

I am not saying there are exceptions and that it is sometimes warranted. Just don’t make it a habit :smiley:

The problem is the view doesn’t know if you’re rendering one item or many items, so it might be doing queries for each item individually rather than in bulk.

3 Likes