I have 4 objects (Novel, Short Story, Non-Fiction, Sci-Fi), all of which extend from a Book base class. The user can view a book details page, which should show a 开发者_开发问答different set of details based on the type of book. So, ideally, I could have 4 diff view scripts which would be invoked according to the type of book selected. How would I do this? Should I store a link to the view script within each object? Should I have a switch statement within the controller action to determine the proper view?
give name to the views scripts/files as your objects with details suffix (e.g. novel_details.php).
So when you display/render a view, you parse the name of the object with details sufix
$this->render( $object->name."_details.php");*
Edit: *It all depends though which MVC framework you're using.
Are you implementing MVC on your own, or using a pre-existing framework? Rails-type frameworks will typically have a nice mapping between classes/methods and requests, e.g.:
GET /book/view/id/1 --> Book::view(1)
Depending on the structure of your models, this could map to a book GUID; alternatively, if you insist on such a type hierarchy, you might prefer something like:
GET /book/view/type/novel/id/3 --> Novel::view(3)
Where id refers to a novel, rather than a book, id. Also:
GET /novel/view/id/3 --> Novel::view(3)
would work identically.
Maybe more pertinently, you should favor composition over inheritance; is there any reason to have 4 types of books? How do they really differ? If they're only differing on the type of meta-data they contain, you might consider encapsulating that difference in some way other than movement down a type hierarchy (for example; if the methods affecting the various types of books are similar, you might simply factor out any algorithm which applies to specific book types and use object composition to include that functionality in your classes). I think this would also allow you to simplify your view structure which, indirectly, would give you a cleaner solution to this problem.
You could have...
$bookTypeToView = array(
'novel' => 'novel.php',
'short_story' => 'short.php'
...
);
And then do something similar to...
$this->view = isset($bookTypeToView[$book['type']]) ? $bookTypeToView[$book['type']] : 'default';
精彩评论