is it good to declare a function in views?
i got situation where i have to work on legacy code. One thing, i 开发者_如何学Gohave to do to have quick result is to define a function in views. Is it good ? how to avoid them ?
If it's view logic: just create the function in the view. If used from multiple views: consider putting the function in a library.
If it's business logic: create the function in the appropriate place like a model.
If you are referring to a view template file, which is used to generate a user interface element, I would personally say that is not ideal to define functions within it. Imagine the things that you may with to do with this view in the future:
- split it up into smaller UI elements
- include it within other UI elements
- unit-test it
- render it multiple times in one request
- reuse those functions within other views
All of these will be problematic if there are functions defined (PHP does not allow you to re-define functions). It's much better to separate concens as much as possible. For example, you can put your view-related functions in a view helper and associate it with the view in the controller.
All the best!
精彩评论