Blog in CodeIgniter : Where Does the Model start, and the Controller End? - php

I'm testing CodeIgniter, and trying to create a simple blog. The video tutorial on the CodeIgniter site is nice, but very incomplete. I'm not too familiar with the MVC structure, and I am wondering exactly how a model is used. For instance, I'm currently doing the "admin" portion of my blog, which allows you to create, delete, and modify entries. The view only contains xhtml, and the controller takes care of the rest. What should be in the model? Does everything database related occur in the model (i.e. inserts, updates, selects, etc.)?

Depends who you ask.
Some people like to put as much as possible in the model (validation, data retrieval, etc), and have the controller just poke it to get the data it needs, which it then hands over to the view.
Think about it like this: if you have more than one controller accessing a single model, then shouldn't common things between them be in a common place (as long as that common thing actually has something to do with the model)?

The Model should contain everything database related, and perform all of the basic CRUD operations (Create, Get, Update, Delete).
The Controller should handle all communication between the model and the view. So for example, if you have a form for adding a new post, you should have a view for that form, which is called from a controller. The Controller would check to see if anything has been submitted, and if something has, call the create/insert method from the Post Model.

For me, model is a where I do all 'dirty' work for my data. I fetch, insert, update data to database, all in a model. I create 1 model for 1 table in the db.
Controller will be logic central for a page that I build. It need as slim as possible. If a function go beyond 1 screen, then it's too long (except if it do form validation which is must be done in controller). This is where Model come to play. Controller just pass the data into model. I do checking, processing, and formatting the data in model. My controller then fetch processed data from model, pass it to view, finish.

model = is object that "talking with your database"
view = is object that building user interface
controller = is the commander .. he got command from user and then he pass it on the model and serve to the user through view.
to create a simple blog, try to read Codeigniter getting started. it will help you a lot after you watch the video. the codeigniter references are good documented and well explained. try that first.

Related

Isn't Controller and Model is the same in php MVC

I am learning PHP programming and came across MVC (Model View and Controller). Can anyone explain more about Model and Controller?
In the following stack overflow question What is the best definition of MVC?, there was an answer that Model is responsible for databases. But isn't it controller which process and use database?
No, they're not the same. The Model contains everything your app can "do".
Classes which describe your data structures? Part of the Model.
Function/method/service for creating new users? Part of the Model.
Sending email notification? Part of the Model.
Complex database queries? Part of the Model.
Everything else? Part of the Model.
What the Controller is is an "interface between your Model and the outside world." The Controller takes input from outside world, like an HTTP request, or a command line input, or an event on an event bus, and decides based on that input what action should be triggered in the Model and perhaps with what kind of View to respond. You may have different Controllers for different scenarios (web server, command line interface, cron job) which adapt those different scenarios to actions in the underlying Model.
for MVC in PHP, i've found Codeigniter to be very useful! Altough it differs a little from MVC in other Languages...
here from theyr definition:
The Model represents your data structures. Typically your model classes will contain functions that help you retrieve, insert, and update information in your database.
The View is the information that is being presented to a user. A View will normally be a web page, but in CodeIgniter, a view can also be a page fragment like a header or footer. It can also be an RSS page, or any other type of “page”.
The Controller serves as an intermediary between the Model, the View, and any other resources needed to process the HTTP request and generate a web page.
https://codeigniter.com/user_guide/overview/mvc.html
No, controller and model is not the same in MVC architecture. The model is being used to keep track of all the business data. The controller tells it what to do, and the model knows how to do it.
Controllers orchestrate the application. Controllers receive events from the
outside world (normally, user input), interact with the model, and display an
appropriate view to the user.
The model is responsible for maintaining the state of the application. A model is more than data; it enforces all the business rules that apply to
that data.
To learn how the concepts fit together, see the
following figure:

What does $model->save() do in PHP Yii?

I have a couple quick conceptual questions about saving models in PHP's Yii framework. I've run into this code a couple of times $model->save() (for example if($model->save())....
but I've never quite understood what it means.
Also, I read in the MVC Tips/Handbook that we should try to save our models in the model and not the controller - could someone explain why that is? I have a friend who has told me that it doesn't matter - but, I'd like to understand the rule behind it.
Thank you for you help!
What does $model->save() do?
Just check the source, it's on github. Apply logic, and the answer is pretty predictable.
As the docs clearly state: the BaseActiveRecord represents a data object. It could be a row returned from a MySQL query, or a processed form being sent by a client, or a MongoDB document, or whatever.
Calling save on that object either inserts the data into the DB you chose, or attempts to update that record. Depending on the insert/update call being successful, it returns a boolean (true if save succeeded, false if it failed).
It's pretty intuitive, really. If you want to learn more about the tools/frameworks you are using, common sense dictates you check out their online documentation. Yii's docs seem to me to be pretty comprehensive and easy to navigate: check them here.
Why save models in the Model?
Well that's easy, but it requires some disambiguation. The term "model" is often used to refer to the data containers. The objects on which you call save in this case. They are data models, true enough, and they are used to carry data back and forth throughout your application. In Yii, what some call models are called "ActiveRecords".
In the acronym MVC (as you know Model View Controller), the Model part actually covers a lot more than mere data containers. That "Model" (with a capital M) refers to the Model layer, also known as the logic or business layer. It's the part of your application that actually will contain the bulk of the code. It's there where the more complex computation is handled, it's the layer where you'll connect and query the DB. And it's this layer that has methods that the controller will call. These methods will then return data models (lower-case m) containing the data or the result of the computation that the controller will then pass on to the view.
If you want to know what logic/jobs/classes make up the Model layer, simply ask yourself this simple question: "What doesn't this bit of do?" If it doesn't handle the raw request, and it doesn't present the data to the user (those are the jobs of the controller and the view respectively), it's part of the Model layer, with the exception of a router component, dispatcher and all that that ties an MVC framework together, of course.
Controller actions (the methods in a controller, obviously) should, therefore be quite small. All they really do, 9/10 times, is pour the request data (form submissions and the like) into a model, and call one or more methods on a service (which is part of the Model layer). These methods will receive the models created in the controller as arguments, and set to work with them.
The controller can perform some basic validation, but the Model layer will dot the i's and cross the t's.
Once the Model layer has done its job, it's back to the controller which has only two things left to do: Did the Model layer return data that it expects or not? If so, pass it on to the view. If not (an exception was thrown or nothing was returned) -> handle the error/exception and, if required, redirect the user.
So in short: The Model layer is the bulk of your code, and it communicates with the controller (and internally) through data models. The Model layer never communicates with the view directly, nor does it redirect the user or handles raw input like $_POST data.
Here's a couple of links to posts of mine where I explain this even further, complete with graphs and what not. They are code-review answers, so ignore the bits that deal with the code itself, but the background information may be relevant to you:
CodeReview: How to put XML results in the MVC pattern?
CodeReview: PHP MVC: how to do $_POST the right way
As I understand in your case $model variable it's instance of BaseActiveRecord class.
So when you call:
$model->save();
Yii run mechanism to insert/update data in data storage.
The save() method return true or false, which does mean model saved or not.
So when you write:
if ($model->save()) {
//some code will be here
}
you check saved model or not.
This tutorial describe how Yii implements MVC practices.
It will insert a new row into the table that the model represents.
i.e. If I have a model called $user that represents a table called users, then calling $user->save(); will insert a new row into the users table.
if($model->save())
Would be the same as:
//Attempt to insert row
$inserted = $model->save();
//If insert is successful.
if($inserted){
//Do this
}
Note that many frameworks will also allow you to update a table row via the save function. In those cases, a where condition is attached or the primary key of the row is passed in.
$model->save() are using for insert and update data in database.

Using models in laravel 4

Just really what the title says, does anybody have a decent explanation on how to use models properly in laravel 4? I'm fine with using the pre-existing User model. But I read somewhere that queries and such should be done in a model of your own.
So what I have is basically a form where you can make a status update (like facebook) and it stores it in a database but the query is run through the controller.
I want it to be done through a model.
Any information on this would be great! Thanks in advance
It's a broad question and right place to learn about how to use model in Laravel-4 is the laravel site itself, but anyways.
Actually, model is the the place where you should keep the business logic in any MVC framework, it could be database related or anything else that is the heart of the application and controller and View are just two parts of the application whose responsibility is only communicate to the model, fetch data and present it to the user but all the data processing should be done in the model and controller should be kept slim and view is only a mechanism to present the user a UI.
So, if you want to have a User model in your application (laravel-4) then you may extend it from Eloquent like
class User extends Eloquent{
// code goes here
}
and then call it's methods from the controller, like
$user = User::get(1);
then passing it to the view like
return View::make('viewname', $user);
That's it. But, if you think, where the find method come from then, it's because, you have extended the Eloquent model and in that model all the necessary methods (find e.t.c) are available and your User model inherited the behavior of Eloquent model, so you can use all the methods from User and it's not necessary to a single method in your User model unless you need to write some special methods for that User model, like relationship functions and so. well, the perfect place to seek help or to know the basic about it is the Laravel site, try to understand it from there and if you fail or just stuck anywhere then come here to ask with specific problem. Also, check Basic Database Usage and Query Builder.
BTW, you may check this post for a detailed answer on model of MVC.

MVC design in codeigniter PHP

When should a new model or controller be made? Should there only be controllers that go with a corresponding view 1 to 1 and like so with controllers and models? Or is it good practice to have controllers for functionality not tied up with any particular view? Take for example voting, should all voting code go in a voting controller or be spread among controllers that have views using voting. Seems likely a voting controller would be best.
First of all , you cannot actually implement classical MVC in php. The best you can do is Model2 MVC.
Model - responsible for all the business logic. Has no clue about where the data is stored or actually comes from. The storage and retrieval is responsibility of DataMappers or DAOs. Model itself should never contain SQL. Ever.
Controller - binds model(s) to the view and changes the state of both. It does not retrieve information from models for sending it to view.
View - responsible for all presentational logic. Retrieves information from models and binds it to appropriate templates. View itself is not a template.
You can wither have 1:1 relationship between views an controller or many:many. it depends on how you implement the view itself.
For example, your view can require a separate object which handles the rendering. And providing different type of objects ( this is where polymorphism matters ), you can make your view to render either xml, html or json.
Or you can do the same by changing the templates. A ListView class can render a list of articles as well as list of users, if the basic presentation logic does not change and you provide just a different template for each.
In the case of voting , it seems ok to have a single controller for all voting related operations, and you can have a single view with switching the templates for your output.
Some of this sort of thing is down to preferences and opinion; there's no single correct way. Some approaches might be more flexible, but maybe at the expense of being more complex.
With regard to your example of "voting", that may depend upon how voting is going to be used in your site. Will votes appear on different types of pages? If so, some sort of component is a good approach; the voting component view can then be used to display its data within different pages, with a Voting component controller accepting the results of votes and then maybe redirecting somewhere else (or accepting votes by an Ajax request).
Very often you'll find that a models (and controllers) map more or less 1:1 to tables in a database. So if I have a table users, I might have a corresponding User model, and UserController controller.
Remember what a controller is intended to do: respond to a request, working out which models need to be loaded, then asking them to store, manipulate and return data which is then transferred to the view for displaying. It's fine to have controllers that don't map directly to models. You might have a controller called DebugController that responds to requests to http://examples.com/debug/, and doesn't map directly to a Debug model and table, but gathers information about the system and various models (of course, there is the argument that all that stuff should be wrapped up into a Debug model, which in turn loads other models and assembles the data that the controller requests).
As for views, you will normally have more than one view for a given controller; often one view per action. So UserController::indexAction() has views/user/index.php, UserController::editAction() has views/user/edit.php etc.
The approach might be flexible, that is true.
Models - Describe the tier that is communicating directly with database, all the SQL queries.
You can have model for each table in DB that will handle all actions connected to that table (select, insert, update, delete).
You can have model for each "logical entity", modul in your application that will handle the actions for this entity. Like in your example "Voting", where you can define the logic of this modul.
(Check if the user has allready voted, getVoteCount...)
Controler - Handle the request by executing functions in the model (they should not comunicate directly in DB) and passing the processed data to appropriate View. If you need to present the same data differently on different page, the controler should decide on which view to send the data.
View - You need view for each page, form, module in you application. It is on personal experiance how you are going to organize the views.

MVC for dummies: why does controller have to send anything to views?

If I get this right than function of the Controller is processing POST data and technically making changes to the state of the application (e.g. DB) via Model.
As far as I understand, View also gets data from the Model.
So this is how I understand the workflow:
Client request --> App Front Controller --> (if method = POST --> Controller) --> View --> back to Client
Here Model is used by Controller to read and write data and by View to read data.
So controller is not used every time the page is loaded, in fact, only when app data is added/updated. Most of the times Controller is bypassed.
Thus, how come almost every resource about MVC is talking about Controller sending data to views?
I am trying to write an app using MVC-like pattern. So in my app views always get data for the page from the Model. When Model is updated, I add specific model update time to Memcache. At runtime each View looks up last update time(s) of related model(s) and last time cache for this view was generated. If model was updated before cache was saved, view reads cache, otherwise re-renders based on updated model.
The controller is responsible for presenting views based on the data that is requested. It's there so neither the model nor the view need to know about the request. Yes, the view gets data from the model, but not always directly; the controller may have to make some decisions as well depending on the request.
It's something like having waiters in a restaurant so they can take orders from and serve dishes to customers. It's not the chefs who bring out the meals after preparing them; it's the waiters. It's not the customers who go to the kitchen asking for meals; it's the waiters who take their orders then let the chefs know what to prepare for whom. In the same way, the controller is there to handle client requests, whatever their nature may be. It's a very rough comparison though, but I hope you get the picture.
Unless I misinterpreted your question: The problem is with the view accessing the model directly. That's not supposed to happen as it defeats the reason for the MVC pattern. The view shouldn't know anything about the model itself, so the model can be exchanged for something else - the controller should supply the data (at most times it a flattened or projected way) to the view.
If I did: The controller is never bypassed. Just because it doesn't do anything with the data, doesn't mean it isn't needed - it provides a layer of abstraction between model and view. The point is to be able to exchange the model without having to adjust the view.
The controller is never bypassed as it is required to instruct which views are shown and what data (if any) is used in those views. Each get or post request to an MVC site uses the controller to control what is shown or collected to/from the client.
At its core MVC is used to separate concerns. The model works with the data, the views handle presentation and the controller provides the logic between the two.
If you are a person that learn faster by getter hands dirty with codes or looking to something visual , like me ....
I will suggest you to follow the tutorial in railsforzombies.org . It pretty much explain all the basic using rails , including MVC. In the tutorial , It mention that if you put all those logic in view , It will be messy. The code will sux a little bit because the guys that want to use your code will be confused with codes. By putting all the logic in controller and output it in view. It will be very clear for the person that look into your codes.

			
				
Usually Controller uses Model, and passes proccessed data to View. View shouldn't see Model. Main goal is - to keep View separately from Model!
MVC for dummies: why does controller
have to send anything to views?
This is the main point of MVC: to create loose coupling by separating and distinguishing the application's concerns. You have the View, Model, and Controller doing specific tasks.
Why the need for separation because it's hard to debug and fix a one gigantic godzilla app. Imagine fixing a car made from stone. There are no bolts. Everything is chiseled from a big rock. How hard is fixing that if you just want to change the wheels. You will need to chisel out the rock itself.
The main job of the controller is to handle requests and display the appropriate view. That it's job. It's like asking why does the mailman need to send the mail. Because that's his job.

Categories