View Re-Use in CakePHP
I have a controller that creates a sidebar. In the middle of the sidebar is a small section of patient data that needs to be refreshed via ajax from time to time. So, I created an element and a function for that specific area. I use a requestAction to get the patient data for the element when I'm rendering the entire sidebar. But, when I'm doing an ajax request, I call the patient data function directly and return it's view. Ajax then loads the div with the data from the view.
My dissatisfaction is that I now have the same exact view code in two places. Once In the view and once in the element. Ideally, I'm sure that I should be using the element for both. I guess I could create another function for the ajax request to call, that would simply do a requestAction to get the element data. But, that seems like an unnecessary extra layer.
In Xaraya, I would have avoided this all by simply using the开发者_开发知识库 patient data view within the sidebar view.
How should I be handling this to most efficiently re-use the same code?
You are right be be bothered by duplicate code. Move everything to the element. Call the element from ALL locations where you need it. Configure it to work in both circumstances. So basically, replace the view instance to call the element as well. You are right about that.
It appears your hangup is the "unnecessary extra layer." However, if it keeps the code clean (by removing duplicate code) is it really an unnecessary extra layer? I would say no. It make it reusable in multiple locations, therefore very much necessary.
Sounds like you should trust your instincts. ;)
Happy coding!
精彩评论