Good practice? PHP MVC Controller Ajax - php

Is this a good practice to handle normal and ajax calls with one controller:
<?php
class SomeController extends Controller {
function index() {
if(!$this->input->is_ajax_request()) {
// load model
// create form
// pass data to view
// ...
} else {
// validate input
// load model
// write data to database
// return with some json string
}
}
}
What are the advantages and disadvantages?

Short answer: it depends.
Only real difference between XHR (what marketing people call "AJAX") and ordinary browser request is that XHR expects a different form of response.
In the MVC-inspired patterns for web the part that is responsible for generating response are the view instances. The view should recognize, which kind of response it has to produce, and act accordingly. Controllers role in this scenario would only be to change the state of current view.
Alternatively, you can, at the bootstrap stage, detect the Accept HTTP header, and based on that initialize a different view instance.
With "fully implement view" I mean an instance, which contains UI logic in the MVC triad and can decide which for to respond. This response can be HTML document, composed from multiple templates, a JSON/XML file or just a simple HTTP header.
Pros: proper separation of concerns, easier to maintain
Cons: have to implement full MVC
.. but most of people do not use full MVC implementations.
If you are one of people, who, instead of MVC-inspired patters, uses Rails-like variation about page controller pattern, then you will be force to create a separate controller for handling XHR.
In this scenario the is no real view. It is replace by dumb template, while UI logic has been merged in the page controller. In this situation the only pragmatic option is to create a separate controller to deal with XHR.
Pros: simpler to implement in small projects
Cons: possible code repetition, harder to maintain

Even if it's an AJAX request, you still have to validate the input. It's not you sending your app the input (via AJAX), it's the browser, which you cannot trust.
As a general design principle, avoid special cases (here: ajax vs. non-ajax). In general, you want to treat all cases equally, so you end up with an orthogonal approach.
And as you can see
class SomeController extends Controller {
function index() {
if(!$this->input->is_ajax_request()) {
// validate input <-- XXX here we need to validate it too
// load model
// create form
// pass data to view
// ...
} else {
// validate input
// load model
// write data to database
// return with some json string
}
}
}
this leads to duplicate code (hard to maintain and keep in sync).
Your code, orthogonal approach:
class SomeController extends Controller {
function index() {
// load model (takes care of his own validation, the self-containment principle of OOP)
// coordinate same business logic done by different models
// return models/data to the view, the framework will decide whether it uses the html or the json view file
}
}
Instead, the model (it could be the same model class, or a Form model like there is in Zend Framework, or a hydrating approach like there is in ZF2 could do most of the jobs (together with a Table Gateway, DAO (like in Doctrine 2), or similar classes for models), and you could create two sepparate views for HTML and JSON.
In Zend Framework 2 for instance, the right view is chosen transparently for you, so there really wouldn't be any if/else regarding "is this AJAX or not?".
You should try out a modern PHP framework (5.3+) to get a feel of how to approach the design of your app in PHP.

I think this is developer choice, consider this:
I think this is developer choice, consider this. Development of a client Mobile site I have seen. They have a store for web and a model store:
/store/model/order.php
/store/controller/order.php
/store/view/order.php
Rather than
/store/model/order_mobile.php
/store/controller/order_mobile.php
/store/view/order_mobile.php
The management is a nightmare. Seperate images, css, multiple coding duplicates for mobile clients. The solution for them now is to convert the entire site into a responsive design
/new-dev-store-responsive/model/order.php
/new-dev-store-responsive/controller/order.php
/new-dev-store-responsive/view/order.php
Same code but cleaner. And I would have AJAX calls inside my templates with the PHP structure on some code and others not. Again it can be difficult to manage. It would better to handle using JSON or external static files - so the PHP is driven using GET, POST etc.. and if they have JavaScript the AJAX works WITH the PHP.. PHP code should stay PHP IMO..
/new-dev-store-responsive/model/order.php
/new-dev-store-responsive/controller/order.php
/new-dev-store-responsive/view/order.php
//new-dev-store-responsive-cdn.com/assets/js/order.js
//new-dev-store-responsive-cdn.com/assets/css/order.css
//new-dev-store-responsive-cdn.com/assets/imgs/order/checkout.jpg

There are a few advantages and disadvantages in your method.
For Posting public data there is no problem.
For Getting public data I usually prefer to do it in separate controller, many time I don't even put ajax check, because my data is public and I want it to go as far as it can..
For Posting/Getting private data I prefer not to use this two sides method because its better to have good and clean (secured) Code...
How ever.. all depends on your choice. Everything is possible! And there aren't constants which is right and which is not..

Related

PHP - Functions from the controller in view

I'm trying to learn MVC pattern, (but without the models because I don't see for what I can use them when I have the controllers).
So I want to display some content in my view. How do I do that?
This is my controller that takes care of index:
<?php
class Index extends Controller {
function __construct() {
parent::__construct();
$this->view->render('mainpage/index');
}
public function wynik($arg) {
echo $arg;
}
}
$klasa = new Index();
?>
And I want to call the function wynik($arg) in my view. How can I do this? My Controller library looks like this:
<?php
class Controller {
function __construct() {
$this->view = new View();
}
}
?>
And in views/mainpage/index.php I'm trying something like this:
<?php
echo $klasa->wynik('abc');
// tried this too:
$this->wynik('abc');
?>
But it doesn't work:
Notice: Undefined variable: klasa in C:\wamp\www\lvc\views\mainpage\index.php on line 2
and
Fatal error: Call to a member function wynik() on a non-object in C:\wamp\www\lvc\views\mainpage\index.php on line 2
This is View library:
<?php
class View {
function __construct() {
}
public function render($name, $noInclude = false) {
if ($noInclude == true) {
require 'views/' . $name . '.php';
} else {
require 'views/header.php';
require 'views/' . $name . '.php';
require 'views/footer.php';
}
}
}
?>
I was thinking - yeah, it searches for wynik() function in View() class, that's why it errors. I want the view to search through functions in my controller. How can I do this?
This code example is not working because the variable $klasa does not exist when you are trying to reference it. The initialization of the object done by calling "new Index()" must be completed first, then that value will be assigned to $klasa. Thus, your code is trying to access $klasa before it exists.
That said, I wouldn't continue to debug this problem. You are missing the point of MVC entirely, and until you understand it, you will not be able to code a controller and view that work well together. Spend time understanding MVC, not by implementing it yourself, but by using another system as an example.
If PHP is your flavor, try the Yii, CodeIgniter or Symphony Frameworks. If you like Python, try Django. If you like Ruby, try Rails. If you like C, learn Objective-C and try iOS.
The MVC model is very simple:
Model- This is where your data is stored.
View- This is how your data is represented to a user.
Controller- This is what your view talks to, so that it can act on the model.
Let's use a simple ice cream vending machine as an example. Assume the vending machine is one of those machines is like this one, where you can't see the items:
Model- The ACTUAL ice creams stored in the back. Lets say, 4 chocolate, 1 strawberry, 3 vanilla. The view and controller don't care how much of each ice cream are there. It is the model's job to keep track of that and make sure we don't have negative ice creams in slots, or other things that don't make sene, for example.
View- These are the little buttons showing what ice creams exist as choices. The view doesn't know or care how many ice creams are in the back, or what ice creams even exist. It simply shows the user something relating to the model, and it doesn't care what is in the model or how the model is structured.
Controller- When a user interacts with the view (that is, they push a button) the controller will take that input and run it by the model. The controller doesn't care how the model is structured, it doesn't know what is back there. All it knows is "When a user presses a button, I need to use the data in the model to make a decision based on that input". For example, when the user presses on a valid item that is in stock, the controller takes that input, runs it by the model, sees that it is ok and dispenses an ice cream. When the user presses on an invalid item that is not in stock, the controller takes that input, runs it by the model, sees that it is out of stock, and tells the view to display an error.
If you get this basic concept down, MVC as a whole will make a lot more sense and speed up dev time dramatically. Understanding MVC is probably one of the more important things for a budding web/mobile developer right now, as most popular web frameworks are based on it (Django, Rails, Yii/CodeIgniter/Symphony), as well as iOS.
MVC is a design patter which combines two layers:
Model layer
Presentation layer
If your application does not have model layer (which contains all the domain business logic), then there is no MVC.
Presentation layer is made mostly from two groups of structures: views and controllers.
controllers : responsible for reacting to user's input and, based on that, changing the state of model layer and view.
views : responsible for the display(or presentation) logic, based information, that view has received from model layer. Based on this information views choose to appropriate response - it can be either just a HTTP header or HTML file, rendered from multiple template or formated JSON/XML data.
But you do not really have Views either. What you call "view" is actually are simple PHP templates.
As for the view accessing controller's methods, it is against all the principles in MVC and MVC-inspired patterns. View is a separate entity, which acquires data from model layer and has the state changed by controllers.
In classical MVC and Model2 MVC patterns the view is active. It requests the information directly from the model layer. Whereas in MVP and MVVM patterns the view is passive and information from model layer is provided by controllers (though in these patterns they are called "presenters" and "viewmodels" respectively).
Views do not use controllers.
Please, do some research before you start throwing terms around just because you think, that it is the latest thing.
Read the following materials:
GUI Architectures
MVC in PHP part 1: Hello World
Model-View-Confusion part 1: Why the model is accessed by the view in MVC
A Description of the Model-View-Controller User Interface Paradigm in the Smalltalk-80 System
How should a model be structured in MVC?
Instead of MVC and not really knowing why and so on, I suggest you another concept called Transaction Script that also work very well with a Frontend Controller or an Application Controller.
Working with Transaction Scripts allows you to get more familiar with OOP while you also benefit from some application structure without the overhead and problems that a misunderstood MVC does carry.
For example within a transaction script object, everything can access the functions of that a transaction. Your libraries, your view and everything else (the model).
Then you will see things growing. But forget Codeigniter and similar, write this from scratch (don't mimic things), you'll learn more and you will have more efficient code.
And you will have it your way, which is great for learning.
For the libraries, just fetch stuff from the Packagist and Pear repositories you will not have many wishes left.
I am not going to add code samples here, but I hope what I say will help you look in the right direction. LVC (Library, View, Controller) is just you changing one name(Model) to another (Library) Doesnt really matter at all, you are still using MVC, you just happen to call your Model a Library. This is a vast topic, but I am only trying to make you see the use of having models and offloading code into that instead of in controllers.
The way to look at it is like this:
Typically controllers should only perform following - check requests, invoke Model(In your case Library) methods, which process those requests, and take those results and pass to the view to render. Think of each function in a controller to be an endpoint URL that the user can type in the address bar and access.
Think you have a function like profile($user_id) in a controller called user, to show user profile and the user accesses it using the url www.mydomain/user/profile/1234.This is all very fine. But what happens if you start throwing in all kinds of utility functions inside this controller like say, strip_all_zeroes(). It becomes bad if the user can access this using mydomain.com/user/strip_all_zeroes, right? It might start throwing all kinds of warnings,errors, or even expose sensitive data..That is where models come in. They can be used to create all kinds of helper functions, whole data classes as required..
Of course this is very broad, over-simplified and not totally accurate, but I hope you get the idea..

MVC calling another controller's action from another controller's action

Let's imagine that we have OrderController controller with three actions/pages: orderDetailsAction, orderHistoryAction, orderCustomerDetailsAction
Each of these actions are returning some piece of HTML.
Now I want to have page containing all 3 html pieces in same time, but I don't want to make 3 ajax calls to get this done.
I'm creating additional controller's action method (orderSummaryAction, for example). This method should contain something like this.
public function orderSummartyAction {
ob_start();
Application::factory()->run('/order/details');
Application::factory()->run('/order/history');
Application::factory()->run('/order/customer_details');
$out = ob_get_clean();
$this->getResponse()->setHtml($out);
}
Is there any framework doing such things or maybe it is bad practice (what is better practice then)?
Thank you!
UPD: Or we can pass not string url, but Route to create new Application instance. It would be much better, imho.
I would say , that the cause of your problem is invalid MVC implementation.
It is not the controller's responsibility to generate HTML. Instead, the output should be created by view instance - an object which deals with presentation logic and juggles with multiple templates. Contrary to what RoR has been trying to feed us - view is not a template.
In proper MVC, controller's are responsible for changing state of model layer and selected view, based either directly on user input or some sort of Request instance.
Also, two side note:
please, do not use factory method pattern [1] [2]. IMHO, this is an antipattern, because it causes tight coupling between classes and attracts complexity (they tend to grow uncontrollably).
it might be useful, instead of returning large blocks of HTML, respond to XHR call with data in JSON format. And then generate the HTML on the client-side.
Symfony2 uses sub-request to invoke multiple controllers.
You can find more details under 'Embedding Controllers' here http://symfony.com/doc/current/book/templating.html

Do I finally get MVC?

Given the URL http://www.example.com/products.php
products.php contains:
<?php
include ('model.inc');
$controller = new Controller;
class Controller
function __construct()
{
$model = new Model;
$this->model->model_methods();
include ('view.inc');
}
}
?>
model.inc contains:
<?php
class Model {
// methods that return data
}
?>
view.inc contains:
<html>
<head>
</head>
<body>
<!-- html plus php output -->
</body>
</html>
So products.php creates the controller. The controller creates the model, figures out what to do and manipulates data only through the model's methods, and finally turns things over to the view. The only php in the view is to output data or to loop through an array to output data.
I've been playing around with a few lightweight php frameworks that implement MVC, but so much of the magic gets done backstage that I don't know if I finally get it or not. :)
Have a look at this MVC article on Coding Horror.
If you think about what a model represents - a "model" of the data, or a subset of the data - and about what the view represents - a particular "representation" of the data - then it's easy to understand that these two entities require something to route the information between them. Hence, the controller. The flow should be M -> C -> V
A good test if you "understand" MVC (and thus, if your application is MVC) is "Can I skin my application?" If you can think of an easy way to apply different skins and styles to your data seamlessly, then you have succeeded in separating the model from the view, and your controller is effective at what it does.
Although I don't know how it's actually implemented, I'd argue that StackExchange is a great example of the MVC idea. There are multiple sites dealing with multiple topics, but they all have very similar kinds of "models" - very similar data. The presentations - the views - are free to change as they please, and the controller is there doing all the logical heavy-lifting. This may be kind of a contrived example, but I think it works conceptually, if not technically.
Personally, I think your Controller is responsible for too much. Instantiating the Model and View inside the Controller "feels" wrong. The Controller should only be responsible for getting data from Model and giving it to View. Right now the Controller is responsible for creating the Model AND it is effectively acting as the View by including the HTML.
The important part here is that each object has, ideally, a singular responsibility.
Model = the data holding your app (this is really a layer instead of an object)
View = the final output sent to the user
Controller = give stuff to View from Model
I recommend you create some kind of "front controller" type object that handles the appropriate instantiation of objects and is the one responsible for setting up all the different pieces.
Ah, ok, but how does the controller "give" the data to the view?
Well, this is really gonna be dependent upon the precise architecture your particular implementation uses. MVC goes far beyond a simple design pattern and can be interpreted in a variety of ways. I prefer something that looks like...
class Controller {
protected $viewData = array();
public function index() {
$data = $this->Model->getData();
$this->giveToView('data', $data);
}
public function getViewData() {
return $this->viewData;
}
protected function giveToView($key, $value) {
$this->viewData[$key] = $value;
}
}
So, the Controller is still getting the data from Model but now instead of including a view file we just store the data and let a different class take care of actually rendering the output.
class View {
protected $viewData;
public function setViewData(array $data) {
$this->viewData = $data;
}
public function renderViewFile($filePath) {
// from example the variable $data is now available in this scope
// to include the $filePath
extract($this->viewData);
include $filePath;
}
}
Obviously this is a simplified example but the basic premise stays the same.
The idea of the MVC is to separate your application logic (business logic, business tier, middle layer or middle tier), input (url, post data, get data) and output (UI - the html in your case).
It is an determined as architectural pattern (software architecture). It is not matter of code but of ideologic for building applicaions.
Read here: MVC in Wikipedia
I would prefer CodeIgniter - a very static collection of functions, some named Model other Controller and there are Views plus a lot of utilities, allowing you to concentrate on the application logic and the layout, without loosing coding freedom in PHP (seems you use PHP). Unless you find out that it's not fitting, but that can happen with any framework.
Yes. This is more or less MVC. The basic gist of MVC is as follows:
Controllers tie your models and views together and normally take care of passing model data to the view.
Models handle your business logic.
Views handle presentation and presentation related logic.
I'd definitely take time to learn PHP MVC framework such as Kohana, Lithium, Symfony, or Cake as they all provide a ton of utilities to make your life easier. They can also handle automatic routing wich makes your URLs cleaner, and helps abstract URLs from their direct connections to controllers.
Kohana: http://kohanaframework.org/
CodeIgniter: http://codeigniter.com
Lithium: http://li3.me/
Symfony: http://www.symfony-project.org/
Cake: http://cakephp.org/
Not quite yet!
The /products.php portion is generally abstracted. The file name is matched in a router during execution, which matches it to a corresponding controller. In this case, you could have a Products controller by name, but you could match (via routing) a things.php request to the Products controller.
There's generally some more execution/initialization "magic", which calls the pertinent model/view based on the request - for example, it would take /products.php, change to Product, and look for a model, controller, and view named Product.inc
Yes, that is the essential basis of the MVC pattern. The controller can be thought of as the brain which figures out what action to take. Depending on that action, it may communicate with models to get the necessary data to render the view. It then makes the necessary data available to the view and renders the HTML for the browser.
MVC at it's most basic definition requires that you split the navigation logic, the data logic and the presentation logic into 3 parts. There is no special structure to observe as long as you have the parts split so that you can easily interchange and isolate your code.
Obviously, there are many more topics to cover if you want to be an hardcore MVC layout.
For example
Splitting your application into folders called controllers, views and models
Creating a good data layer to simplify your models as much as possible
Integrating a helper/widget logic so you can reuse visual components
Integrating a routing engine with mod_rewrite to create clean urls
Those are just a few of the items you should cover to get a real good MVC layout. But then again... MVC is a design pattern, it's a way of doing things without being something totally concrete or concise.

PHP MVC: Do i really need a Controller?

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.

What should go in CodeIgniter models?

I've always used the model as something to more or less store and execute database queries. I have heard about the fat model, thin controller concept.
The way I setup my models right now causes a lot of junk in controllers for things like validating forms, formatting data. Does form validation, file uploading and data formatting belong in the controller or the model?
I realize this question is subjective, which should create some good discussion rather than a concrete answer.
Form Validation should definitely be part of the model. I generally represent each form as one model and pass it the sanitized post/get paramaters. The model can then take whatever action is necessary based on the input and use a property (optionally with a getter) to signal success or failure. In psuedo code you want it to look something like:
class Controller
{
function action()
{
$input = new Input();
$form = new FormModel($input);
if ($errors = $form->errors())
{
//load the appropriate view for the errors
}
else
{
//load the appropriate view for success with an optional redirect
}
}
You have two main roads to go. Thin controller/fat model or fat controller/thin model. Basicly is were you put most of the interaction. I prefer to keep at the model the major portion of the code. That way, the code is available in virtually every controller and/or lib. If the code remain at controller, it's hard (but not impossible) to use it in other controllers.
Things lije validations and other common tasks should be in a lib or helper. You can produce a set of "workers" (this is the name I give to them) to do the heavy lifting. Also, CI has a LOT of ready made libs and helpers both from the CI team and the community. Mess around the wiki to find the wealth of information available.
Hope this helps
Vx
The model is what interacts with the data (most often a database). Controllers use the models to access the data.

Categories