All the examples I've seen of what and how MVC SHOULD be have used classes as the models, classes as the controller, and HTML templates as the view. And all of them consisted of one index.php script and different requests in the url to run the entire site.
So they've all been something like...
MODEL
class User{
function getUser($userID){
$sql = mysql_query('SELECT name......');
// more code.....
return $array
}
}
VIEW
<h2><?php echo $user['name']; ?></h2>
CONTROLLER
class Controller{
$userModel = new User;
$userInfo = $userModel->getUser($id);
$template = new Template('usertemplate.tpl');
$template->setVariables($userInfo);
$template->display();
}
I understand why the model is made of classes that simply get and save data (even though I assume classes arent always necessary and functions could be used). I understand why the template consists of mainly HTML. But I dont understand why the controller is a class. I would assume the controller to be a procedural script (like userprofile.php which gets the users data from the model and sends it to the template for displaying).
Also, I was wondering why every tutorial I've read dealt with mod rewriting, and using a single page with requests in the url like "index.php?user=1", or index.php?news=3 to run the entire site. Whats wrong with having separate pages like user_profile.php?id=1, or news.php?id=3...
Can somebody please help me with a quick "tutorial" and an explanation along the way. Like...how would a registration form be implemented using MVC, what would go where and why? thankyou
PS. what other kind of design patterns are there
The big "win" of the controller in PHP's version of MVC is you get away from having a separate PHP page for each and every URL that your application responds to.
When you have a new single page being created for each URL, you're expecting your developers (or yourself) to pull in the needed libraries and initialize the template/layout engine in the same way. Even when you're a single developer, the temptation to break from the "standard" way of doing things usually ends up being too strong, which means each URL/PHP-page ends up being its own mini-application instead of each URL/PHP-page being part of the same application. When you have multiple developers this is guarantied to happen.
The end results is pages and components that don't play nice with each other and are hard to debug (with everything hanging out in the global namespace), giving an inconsistent experience for both the users and the developers who have to work on the project.
MVC frameworks also make it easier to give your site friendly URLs. There's usually enough going on in the routing system that you don't need to resort to a huge number of query string variables. Readable URLs are a plus, for SEO and for savvy users.
Finally, although this is pie in the sky with most shops, when you have a controller the methods on the controller become easily unit testable. While you can technically wrap a test harness around a non-MVC site, it's always a pain in the ass, and never works like you'd like it to.
using a single page with requests in
the url like "index.php?user=1", or
index.php?news=3 to run the entire
site. Whats wrong with having separate
pages like user_profile.php?id=1, or
news.php?id=3...
Using a single entry point makes some things easier, I suppose :
You don't have to duplicate any portion of code in user_profile.php and news.php
If you want to set up any kind of filter (like PHPIDS for security, or ACL, for instance), you only have one file to modify, and it's done for the whole application.
PS. what other kind of design patterns
are there
There are a lot of design patterns ; you can find a list on the Design pattern (computer science) article on wikipedia, for instance -- with links to the page of each one of them, for more details.
There's nothing wrong with having separate scripts for each action, and in fact you CAN create a MVC architecture this way, without using a class for the controller. I'm working on an MVC framework at the moment that supports both styles.
The important thing is really to keep separation of different concerns. Database logic goes in your models, Layout logic goes in templates, and everything else in the controller.
So for a really simple example you could have a script "register.php" with the following code
$signup_options = SignupOptions::getSignupOptions(); // Load some data
require("register_form.php"); // Pass it to the view
And this posts to register_process.php
$username = $_REQUEST['username'];
$password = $_REQUEST['password'];
$email = $_REQUEST['email'];
Users::Register( $username, $password, $email );
header( 'location: register_success.php' );
MVC is not suitable for all applications, so you should consider your architecture on a per project basis. For many sites, just having a bunch of independent scripts works fine. For larger more complex applications however, MVC has proven itself to be a reliable and scalable way of developing web applications.
Another common design pattern is "View-Helper", which is where you call a template directly, and the template calls a "Helper" object that performs business logic between the template and the models. Similar in concept, but you can skip having any extra code for templates that don't need it, while still maintaining separation of concerns like MVC. (The difference is essentially that you call the template directly, rather than calling a controller).
There are several ways to implement a good application, but I am just going to touch on a few concepts. These concepts are taken from Samstyle PHP Framework.
Firstly, you have these components: Model (Table Data Gateway), View, View Controller and Backend Controller.
This View Controller actually controls how the view is going to be like (e.g. display out the registration form). The Backend Controller processes user data on the backend and interacts with the Model (database).
So here we can easily integrate Post-Redirect-Get into it.
Say you have register.php for the View Controller which will display the form and parse the content into the template HTML file.
User uses the form, submit and will then be posted to the Backend Controller deck.php. The Backend Controller validates, check then passes the data to functions (Table Data Gateway) which will help you to interact with the database. After the interaction is done, the user is redirected either to a success page, or the registration page with an error.
In the Model (Table Data Gateway), you actually have functions which take in an array and then CRUD with the database.
Related
My question is simple but (I guess) hard to answer:
Do I really need a complete Model-View-Controller design pattern in my PHP Website / Web-App?
I can't understand how a Controller could be useful with PHP since every PHP site is generated dynamically on every request. So after a site is generated by PHP, there is no way to let the View (the generated HTML site in the Browser) interact with the controller, since the Controller is on the server side and generated once for each site request, even if the request is AJAX...
Do I understand something completely wrong?
Why should I use any kind of MVC PHP Framework like Zend or Symphony?
EDIT:
For example lets assume, there should be a website to represent a list of customers in a table:
My Model would be a simple Class Customer on the server side that queries the database.
My View would be the generated HTML code that displays the Model (list of Customers).
And the controller? Is the controller only evaluating the GET or POST to call the correct method of the model?
Do I have understand something completely wrong?
Yes.
The MVC pattern is not for the browser. The browser sees HTML anyways. Whether this HTML is generated with C++, PHP, Java or whatever it doesn't matter. The browser doesn't care what design patterns were used to generate this HTML.
MVC is a design pattern to organize and separate responsibilities in your code. So it's not for the browser, it's for the developers writing the code. It's to create more maintainable code where you have a clear separation between your business logic (Model), the communication between the model and the view (Controller) and the UI (View).
Whether you should use the MVC pattern in your web site is a subjective question that I prefer not to answer as it will depend on many factors.
Short Answer
Yes. A controller will be responsible for preparing data to display for rendering and sometimes handle GET and POST requests that originating from your client. It should leave HTML generation to the view.
Long Answer
MVC can be very helpful in keeping applications maintainable and your code base sane. The pattern helps ensure separation of concerns of your code and in most cases will steer yor clear of 'spaghetti php' where your application logic is tangled with the HTML generation. A sample MVC setup below (there are sure to be many variations of this, but it gives you the idea):
Model
Responsible for fetching data from the database and saving changes when requested. One example might be a php object that represents a user with name and email fields.
Controller
Responsible for massaging and manipulating data and preparing it for display. The prepared data is passed to a view for rendering, with the view only needing to be aware of just the data it needs to render. For example: a controller may look at a query string to determine what item to fetch to render and combine this with several additional model queries to get additional data.
Often controllers will also be responsible for handling GET and POST requests that originate from your HTML client and applying some sort of manipulation back on your database. For example - handling form submits or AJAX requests for additional data.
View
The view is responsible for actually generating the HTML for display. In PHP, a view would often be a template file with minimal logic. For example, it might know how to loop over items provided to it from the controller or have some basic conditionals.
Application MVC vs PHP/Python/etc. MVC
From your other comments it sounds like you are familiar with using MVC in the context of a desktop or mobile application.
One of the main differences between MVC in the two is the granularity at which the controller is manipulating the view and responding to events.
For example, in a traditional application the controller might listen for click events originating from a button and respond appropriately.
When your doing server side html generation however, your controller is only 'alive' for a brief moment while its preparing html to ship out over the wire. This means that it can only do so much to setup and prepare the view for display.
Instead of listening traditional events from the UI, it can instead react in different ways to future GET and POST requests. For example, you may have a "save" button on a form trigger a POST request to your server (such as yourpage.php?action=save&value=blah). While handling this request your controller might access your models and apply changes, etc.
I realise that I am answering a very old questions, however, I do not believe that any other question has answered your initial concern appropriately, and this will hopefully add something useful for others who may stumble across this question in their learning about MVC.
Firstly, I will start by saying I read an interesting article about the confusion which exists within the PHP community about MVC and it is worth a read if you are asking this type of question.
Model-View-Confusion part 1: The View gets its own data from the Model
Secondly, I do not believe you have misunderstood anything at all, rather you have a better understanding of PHP and MVC which is allowing you to ask the question. Just because something has been defined and accepted by the community at large, it does not mean you should't question its use from time to time. And here is why.
There is NO memory between requests (except for SESSION state) within a PHP application. Every time a request is received the entire application fires up, processes the request and then shuts down i.e. there are no background application threads left running in the background (at least none which you can use within your application) where you could, theoretically, maintain application state. This is neither good, nor bad, it is just the way it is.
Understanding this, you can probably start to see what you are thinking is correct. Why would a View (which is allowed to access its own data from the Model) need a Controller? The simple answer, is that it doesn't. So for the pure display of a Model, the View is perfectly entitled to fetch its own data (via the Model) and it is actually the correct way to implement MVC.
But wait. Does this mean we don't need Controllers? Absolutely NOT! What we need to do is use a Controller for its appropriate purpose. In MVC, the Controller is responsible for interpreting user requests and asking the Model to change itself to meet the users request, following this, the Model can notify it's dependencies of the change and the View can update itself. Obviously, as you know, in the context of a PHP web application, the View is not just sitting and waiting for update notifications. So how can you achieve the notification?
This is where I believe MVC got hijacked. To notify the View it's Model has changed, we can simply direct them to the URL of the View which accesses the now updated Model. Great, but now we have introduced something into the Controller. Something which says, "Hey, I'm a controller but now I have knowledge of the location of the View." I think at this point, someone thought, "why do I bother redirecting the user? I have all the data which the View needs why don't I just send the data directly to the View?" and bang! Here we are.
So let's recap.
A View CAN access the Model directly within MVC
The Model houses the business logic for the Domain Objects
A Controller is not meant to provide the View access to the Model or act as any type of mediator
The Controller accepts user requests and makes changes to it's Model
A View is not the UI/HTML, that is where a Template is used
A practical example
To explain what I have been describing, we shall look at a simple, commonly found function within most websites today. Viewing the information of a single logged in user. We will leave many things out of our code here in order to demonstrate just the structure of the MVC approach.
Firstly lets assume we have a system where when we make a GET request for /user/51 it is mapped to our UserView with the appropriate dependencies being injected.
Lets define our classes.
// UserModel.php
class UserModel {
private $db;
public function __construct(DB $db) {
$this->db = $db;
}
public function findById($id) {
return $this->db->findById("user", $id);
}
}
// UserView.php
class UserView {
private $model;
private $template;
private $userId;
public function __construct(UserModel $model, Template $template) {
$this->model = $model;
$this->template = $template;
}
public function setUserId($userId) {
$this->userId = $userId;
}
public function render() {
$this->template->provide("user", $this->model->findById($this->userId));
return $this->template->render();
}
}
And that's it! You do not require the Controller at all. If however you need to make changes to the Model, you would do so via a Controller. This is MVC.
Disclaimer
I do not advocate that this approach is correct and any approach taken by any developer at any point in time is wrong. I strongly believe that the architecture of any system should reflect its needs and not any one particular style or approach where necessary. All I am trying to explain is that within MVC, a View is actually allowed to directly access it's own data, and the purpose of a Controller is not to mediate between View and Model, rather it is intended to accept user requests which require manipulation of a particular Model and to request the Model to perform such operations.
This is a question with no real problem behind, just a product of my sick mind and drive to make things slightly weird :)
So, I have this PHP application build on top of my own MVC oriented framework (yes, I did my own instead of using existing one). And it is done by the book so we have model (data and database manipulation), view (templates filled with data and rendering output) and controller (handles requests, gets appropriate data from model, puts data into view). Classic and boring scenario with request routing done with .htaccess rules.
Yesterday I did some changes in my code, bug fixes, couple improvements, etc. And I felt strong urge to rearrange the code of controllers. They feel somewhat heavy and bloated and number of methods makes it hard to navigate through the file, and such stuff. I'm sure everybody knows what I'm talking about.
I'm thinking about breaking my controller class into many classes, each one handling only one type of request like login or register or showProfile or killMe.
Now controller class has public methods corresponding to parts of user friendly (or maybe SEO friendly) urls and routing class invokes proper controller and it's method according to url content.
Change I'm thinking about would shift a little routing mechanism into invoking specific controller and it's Execute() method.
For example, for url = "www.example.com/users/login"
now it looks like that:
$controller = new url[0]();
$method = url[1];
echo $controller->$method();
and now url would change to "www.example.com/login" and routing code would look like that:
$controller = new url[0]();
controller->Execute();
I omitted parts where I parse urls and extract routing info from them as it is irrelevant to my question.
What benefits I see in that change?
one dedicated class per one request
smaller files
smaller code
easier maintenance
limited danger of breaking working controller when adding new features(new types of request) or fixing bugs
Disadvantages?
possibly a lot of classes
possible performance hit
???
And my question is about what do you think about that idea and does it make any sense at all. And of course I'm more interested why I shouldn't do it than why I should. So if you can think of any reasons why that would be terrible idea and abomination please speak now before it will be too late :)
EDITED
Clarification of a question:
I'm asking whether I should break my single big controller which handles many types of requests by it's methods into many small controllers each of them handling only single type of request.
Now I have controller Users which handles requests like "login", "showLoginForm", "register", "activate", etc. Refactored code would consist of separate controllers for each of these requests.
A disadvantage I can think of for both the old and new methods is that you are mapping urls directly to class names. If you'd like to change the url you'd have to change the class name. If you'd like to have different urls for different languages, you'll have to add a layer that will map urls to class names anyways.
This is why I'd rather have a routing class that will map urls to class names which provides you a seam to change things.
if I have a page on my site where i have to show 4 or 5 snippets (news feeds, event feed etc), all relating to different data (in different models and db tables), then what is a sensible way to handle the generation of the snippet content and layout? i could use a single snippet controller which contains static functions which each return a view populated with the relevant data. But each function in this snippet controller will be interacting with different data/models, so i'm not sure how OOP this is. Or, I could just add a static function to each of the controllers which are dealing with each associated set of data - e.g in a News_Controller, as well as functions to show all news items, individual news items etc, i could add a static function to generate the news feed by simply returning the view I need. I think this approach might work, as i don't want to instantiate an object for these simple snippets, so having static functions in the relevant controllers makes a bit of sense. Bit of a stream of consciousness here, but am i making any sense?!
Many frameworks have some notion of "partials", which are typically used for this kind of thing.
Since these partials are generally read-only, and are often displayed on every page (or some well-defined set of pages), you can approach them without thinking in terms of controllers like you would for a page.
In other words -- remember that it's fine if your view/layout code talks directly to your models, as long as it's only interrogating them.
I do things like this all the time:
layout.php:
<div id="newsWidget">
<?PHP $news = Model_News::latest(); ?>
<?PHP foreach($news as $newsitem): ?>
<!-- output some news headlines -->
<?PHP endforeach; ?>
</div>
Model_News::latest() might implement some caching, etc, since this is layout code and I probably don't want to hit the db on every request.
No controller-bloat necessary!
You may want to look into Hierarchical Model-View-Controller (HMVC). It's especially suited to making pages with snippets. I believe Kohana implements it.
Basically, you have multiple Model-View-Controller triads each responsible for each snippet. So you could have a controller to access the News database and load a variety of small views for different types of news displays.
You can architect your MVC pattern to provide a mechanism for allowing data that has been set to be returned as an array. For instance, normally a web request to /news/feed/ would result in pertinent data being set and subsequently passed to a view. In addition to web requests, the system should also allow a controller to make such a request, i.e., $vars = $this->call('/news/feed/'); The system will recognize the internal request and return the set vars rather than invoking a view.
This allows you to keep your controllers and models cohesive.
I know normally the data is passed thru to the view with the controller. however, currently in my view I load my model ($this->load->model('Db_model');) so i can use it in a loop to retrieve a users profile picture path from a array of IDs that is passed from controller. Will loading the db model in the view to accomplish this make my site more vulnerable or bad form? To me it seems to be outside of MVC concept but its working atm. thanks
I agree, but it has everything to do with scale. If you are designing a tiny app MVC does not really matter because it is easy to oversee the whole application. However once an application starts to grow, or if you are building a bigger application MVC separation becomes more important.
For instance if you use models in your views, this implies the design team has to know about models. It may also hamper porting the views later on to another framework or swapping templates.
Well if you do something outside of MVC it doesn't mean that it will stop working the very same second. MVC is just a design pattern which should help you design and maintain your site. The basic principle is that model should communicate only with controller and view also only with controller so your idea of calling model directly from the view is not MVC way of doing things.
If you need some additional data from the model why don't fetch it in controller and pass it as another parameter to the view so it can easily use it? It will be the same amount of code probably and your code will be much cleaner. Keeping your code clean may not seem like such a big deal right know when you remember where everything is stored but in few months when you forget some of this stuff you may end up with a headache if you mess your app too much.
Look into Libraries. You should consider creating a library class helper for displaying the profile picture. You can then have the library call the model. Then, in your view, you simply do:
<?php $this->profile_helper->display_picture(); ?>
where profile_helper is your library class and display_picture() is your class function to display the users profile.
1) Where does the homepage of your website fit into "controllers"? I've seen some people use a "page" controller to handle static pages like, about, home, contact, etc., but to me this doesn't seem like a good idea. Would creating a distinct controller just for your homepage be a better option? After all, it may need to access multiple models and doesn't really flow well with the whole, one controller per model theory that some people use.
2) If you need a dashboard for multiple types of users, would that be one dashboard controller that would have toggle code dependent upon which user, or would you have say a dashboard action within each controller per user? For example, admin/dashboard, account/dashboard, etc.
3) It seems to me that using the whole simple CRUD example works like a charm when trying to explain controllers, but that once you get past those simple functions, it breaks down and can cause your controllers to get unwieldy. Why do some people choose to create a login controller, when others make a login function in a user controller? One reason I think is that a lot of us come from a page approach background and it's hard to think of controllers as "objects" or "nouns" because pages don't always work that way. Case in point why on earth would you want to create a "pages" controller that would handle pages that really have nothing to do with each other just to have a "container" to fit actions into. Just doesn't seem right to me.
4) Should controllers have more to do with a use case than an "object" that actions can be performed on? For all intensive purposes, you could create a user controller that does every action in your whole app. Or you could create a controller per "area of concern" as some like to say. Or you could create one controller per view if you wanted. There is so much leeway that it makes it tough to figure out a consistent method to use.
Controllers shouldn't be this confusing probably, but for some reason they baffle the hell out of me. Any helpful comments would be greatly appreciated.
1) I use a simple homebrew set of classes for some of my MVC stuff, and it relates controller names to action and view names (it's a Front Controller style, similar to Zend). For a generic web site, let's assume it has a home page, privacy policy, contact page and an about page. I don't really want to make separate controllers for all these things, so I'll stick them inside my IndexController, with function names like actionIndex(), actionPrivacy(), actionContact(), and actionAbout().
To go along with that, inside my Views directory I have a directory of templates associated with each action. By default, any action automatically looks for an associated template, although you can specify one if you wish. So actionPrivacy() would look for a template file at index/privacy.php, actionContact() would look for index/contact.php, etc.
Of course, this relates to the URLs as well. So a url hit to http://www.example.com/index/about would run actionAbout(), which would load the About page template. Since the about page is completely static content, my actionAbout() does absolutely nothing, other than provide a public action for the Front Controller to see and run.
So to answer the core of your question, I do put multiple "pages" into a single controller, and it works fine for my purposes. One model per controller is a theory I don't think I'd try to follow when working with Web MVC, as it seems to fit an application with state much better.
2) For this, I would have multiple controllers. Following the same methods I use above, I would have /admin/dashboard and /account/dashboard as you suggest, although there's no reason they couldn't use the same (or portions of the same) templates.
I suppose if I had a gazillion different kinds of users, I'd make things more generic and only use one controller, and have a mod_rewrite rule to handle the loading. It would probably depend on how functionally complex the dashboard is, and what the account set up is like.
3) I find CRUD functionality difficult to implement directly into any layer of MVC and still have it be clean, flexible and efficient. I like to abstract CRUD functionality out into a service layer that any object may call upon, and have a base object class from which I can extend any objects needing CRUD.
I would suggest utilizing some of the PHP ORM frameworks out there for CRUD. They can do away with a lot of the hassle of getting a nice implementation.
In terms of login controller versus user controller, I suppose it depends on your application domain. With my style of programming, I would tend to think of "logging in" as a simple operation within the domain of a User model, and thusly have a single operation for it inside a user controller. To be more precise, I would have the UserController instantiate a user model and call a login routine on the model. I can't tell you that this is the proper way, because I couldn't say for sure what the proper way is supposed to be. It's a matter of context.
4) You're right about the leeway. You could easily create a controller that handled everything your app/site wanted to do. However, I think you'd agree that this would become a maintenance nightmare. I still get the jibbly-jibblies thinking about my last job at a market research company, where the internal PHP app was done by an overseas team with what I can only assume was little-to-no training. We're talking 10,000 line scripts that handled the whole site. It was impossible to maintain.
So, I'd suggest you break your app/site down into business domain areas, and create controllers based on that. Figure out the core concepts of your app and go from there.
Example
Let's say I had a web site about manatees, because obviously manatees rock. I'd want some normal site pages (about, contact, etc.), user account management, a forum, a picture gallery, and maybe a research document material area (with the latest science about manatees). Pretty simple, and a lot of it would be static, but you can start to see the breakdown.
IndexController - handles about page, privacy policy, generic static content.
UserController - handles account creation, logging in/out, preferences
PictureController - display pictures, handle uploads
ForumController - probably not much, I'd try to integrate an external forum, which would mean I wouldn't need much functionality here.
LibraryController - show lists of recent news and research
HugAManateeController - virtual manatee hugging in real-time over HTTP
That probably gives you at least a basic separation. If you find a controller becoming extremely large, it's probably time to break down the business domain into separate controllers.
It will be different for every project, so a little planning goes a long way towards what kind of architectural structure you'll have.
Web MVC can get very subjective, as it is quite different from a MVC model where your application has state. I try to keep major functionality out of Controllers when dealing with web apps. I like them to instantiate a few objects or models, run a couple of methods based on the action being taken, and collect some View data to pass off to the View once it's done. The simpler the better, and I put the core business logic into the models, which are supposed to be representative of the state of the application.
Hope that helps.