I have a person object.
class Person {
private $name;
...
}
I need to be able to change how they are displayed on the front-end ( visitors have control ). They can choose list view, grid view, photo view for example.
class PersonDisplay {
public function displayList() {
// Query database
// Output html to display in list mode
}
public function displayPhoto() {
// Query database
// Output html to display in photo mode
}
}
Is this an acceptable way to handle the presentation of the items on the front-end or is there a specific design pattern I should 开发者_开发知识库be researching to help me with this task? Does anyone have any suggestions or ideas where this could go wrong or if this could potentially make maintenance a nightmare?
The Person object was just an example very similiar to what I am using.
I feel like a lot of folks get swept up in the "best practice wave" where it's always best to go by what the elite programmers say. Here's my opinion:
If it works and it's pretty elegant, go with it.
As long as your solution isn't "hackish" and will scale as the volume of usage your app sees increases, whatever you come up with is fine.
In terms of which will be most maintainable, you've got two fundamentally different views: grid and list. If you assume that you're going to need two separate chunks of HTML for each, as long as you're not duplicating code up and down, then it's fine. If you do see that you're duplicating a lot of code, make a private function in PersonDisplay
and centralize the logic there.
Frankly, it seems like this bit of code isn't going to grow much farther past, say, a thousand lines of code (max). Use some common sense and take a reality check every now and then. If you see that you're creating too many functions, merge some functions. If you're writing duplicate code, move that code out into a separate function. You really can't screw this one up too much.
As the saying goes, "don't sweat the small stuff." You can afford to have marginally imperfect code every now and then.
It seems like what you want (and are using) is the Observer pattern. http://en.wikipedia.org/wiki/Observer_pattern#PHP
In this pattern, one class holds the data that you want to store and another class holds the implementations of the different ways you could display the data.
精彩评论