Laravel - difference between Controller & Model - php

I'm learning Laravel and I'm watching many tutorials, but I dont really get it, what's the difference between the controller and model, because you can put in both a function.

Controllers in Laravel are used to determine how to handle http requests.
When you have anything to do with the DB, its better to place those function in the model, and call them from the controller.
In clear terms:
Model performs all operations on data from DB.
Controller call necessary model methods and ready the data.
View take care of displaying the data.
I hope this is clear enough.

You will be familiar with all of this soon.
model methods is for relationships mainly , or to make some thing for every object of this model (database table) every column in db is an object and every table is a model.
but in controller you set your app functionality that you want , and its an intermediator between model and view .
i hop this makes you good in this point.
good luck

You can write functions anywhere, you are perfectly right.
But is not an efficient way to do things.
The answers for those questions can be easily find out. Search about MVC pattern. In few words, remember brief:
MODEL => working with relational databases / storing the data
CONTROLLER => working with the logic(taking inputs, calculus etc) / general functionalities
Combining them is more efficient than working with those together, that is the reason why using a pattern is more great than writing code in a old style mode reinventing the wheel again.

Related

Why separate Model and Controller in MVC?

I'm trying to understand the MVC pattern in Phalcon.
In my current application I only need ONE template file for each table. The template contains the datagrid, the SQL statement for the SELECT, the form, add/edit/delete-buttons, a search box and all things necessary to interact with the database, like connection information (of course using includes as much as possible to prevent duplicate code). (I wrote my own complex framework, which converts xml-templates into a complete HTML-page, including all generated Javascript-code and CSS, without any PHP needed for the business logic. Instead of having specific PHP classes for each table in the database, I only use standard operation-scripts and database-classes that can do everything). I'm trying to comply more with web standards though, so I'm investigating alternatives.
I tried the INVO example of Phalcon and noticed that the Companies-page needs a Companies model, a CompaniesController, a CompaniesForm and 4 different views. To me, compared to my single file template now, having so many different files is too confusing.
I agree that separating the presentation from the business logic makes sense, but I can't really understand why the model and controller need to be in separate classes. This only seems to make things more complicated. And it seems many people already are having trouble deciding what should be in the model and what should be in the controller anyway. For example validation sometimes is put in the model if it requires business logic, but otherwise in the controller, which seems quite complex.
I work in a small team only, so 'separation of concerns' (apart from the presentation and business logic) is not really the most important thing for us.
If I decide not to use separate model and controller classes,
what problems could I expect?
Phalcon's Phalcon\Mvc\Model class, which your models are supposed to extend, is designed to provide an object-oriented way of interacting with the database. For example, if your table is Shopping_Cart then you'd name your class ShoppingCart. If your table has a column "id" then you'd define a property in your class public $id;.
Phalcon also gives you methods like initialize() and beforeValidationOnCreate(). I will admit these methods can be very confusing regarding how they work and when they're ran and why you'd ever want to call it in the first place.
The initialize() is quite self-explanatory and is called whenever your class is initiated. Here you can do things like setSource if your table is named differently than your class or call methods like belongsTo and hasMany to define its relationship with other tables.
Relationship are useful since it makes it easy to do something like search for a product in a user's cart, then using the id, you'd get a reference to the Accounts table and finally grab the username of the seller of the item in the buyer's cart.
I mean, sure, you could do separate queries for this kind of stuff, but if you define the table relationships in the very beginning, why not?
In terms of what's the point of defining a dedicated model for each table in the database, you can define your own custom methods for managing the model. For example you might want to define a public function updateItemsInCart($productId,$quantity) method in your ShoppingCart class. Then the idea is whenever you need to interact with the ShoppingCart, you simply call this method and let the Model worry about the business logic. This is instead of writing some complex update query which would also work.
Yes, you can put this kind of stuff in your controller. But there's also a DRY (Don't Repeat Yourself) principle. The purpose of MVC is separation of concerns. So why follow MVC in the first place if you don't want a dedicated Models section? Well, perhaps you don't need one. Not every application requires a model. For example this code doesn't use any: https://github.com/phalcon/blog
Personally, after using Phalcon's Model structure for a while, I've started disliking their 1-tier approach to Models. I prefer multi-tier models more in the direction of entities, services, and repositories. You can find such code over here:
https://github.com/phalcon/mvc/tree/master/multiple-service-layer-model/apps/models
But such can become overkill very quickly and hard to manage due to using too much abstraction. A solution somewhere between the two is usually feasible.
But honestly, there's nothing wrong with using Phalcon's built-in database adapter for your queries. If you come across a query very difficult to write, nobody said that every one of your models needs to extend Phalcon\Mvc\Model. It's still perfectly sound logic to write something like:
$pdo = \Phalcon\DI::getDefault()->getDb()->prepare($sql);
foreach($params as $key => &$val)
{
$pdo->bindParam($key,$val);
}
$pdo->setFetchMode(PDO::FETCH_OBJ);
$pdo->execute();
$results=$pdo->fetchAll();
The models are very flexible, there's no "best" way to arrange them. The "whatever works" approach is fine. As well as the "I want my models to have a method for each operation I could possibly ever want".
I will admit that the invo and vokuro half-functional examples (built for demo purposes only) aren't so great for picking up good model designing habits. I'd advise finding a piece of software which is actually used in a serious manner, like the code for the forums: https://github.com/phalcon/forum/tree/master/app/models
Phalcon is still rather new of a framework to find good role models out there.
As you mention, regarding having all the models in one file, this is perfectly fine. Do note, as mentioned before, using setSource within initialize, you can name your classes differently than the table they're working on. You can also take advantage of namespaces and have the classes match the table names. You can take this a step further and create a single class for creating all your tables dynamically using setSource. That's assuming you want to use Phalcon's database adapter. There's nothing wrong with writing your own code on top of PDO or using another framework's database adapter out there.
As you say, separation of concerns isn't so important to you on a small team, so you can get away without a models directory. If it's any help, you could use something like what I wrote for your database adapter: http://pastie.org/10631358
then you'd toss that in your app/library directory. Load the component in your config like so:
$di->set('easySQL', function(){
return new EasySQL();
});
Then in your Basemodel you'd put:
public function easyQuery($sql,$params=array())
{
return $this->di->getEasySQL()->prepare($sql,$params)->execute()->fetchAll();
}
Finally, from a model, you can do something as simple as:
$this->easyQuery($sqlString,array(':id'=>$id));
Or define the function globally so your controllers can also use it, etc.
There's other ways to do it. Hopefully my "EasySQL" component brings you closer to your goal. Depending on your needs, maybe my "EasySQL" component is just the long way of writing:
$query = new \Phalcon\Mvc\Model\Query($sql, $di);
$matches=$query->execute($params);
If not, perhaps you're looking for something more in the direction of
$matches=MyModel::query()->where(...)->orderBy(...)->limit(...)->execute();
Which is perfectly fine.
Model, View and Controller were designed to separate each process.
Not just Phalcon uses this kind of approach, almost PHP Frameworks today uses that approach.
The Model should be the place where you're saving or updating things, it should not rely on other components but the database table itself (ONLY!), and you're just passing some boolean(if CRUD is done) or a database record query.
You could do that using your Controller, however if you'll be creating multiple controllers and you're doing the same process, it is much better to use 1 function from your model to call and to pass-in your data.
Also, Controllers supposed to be the script in the middle, it should be the one to dispatch every request, when saving records, when you need to use Model, if you need things to queue, you need to call some events, and lastly to respond using json response or showing your template adapter (volt).
We've shorten the word M-V-C, but in reality, we're processing these:
HTTP Request -> Services Loaded (including error handlers) -> The Router -> (Route Parser) -> (Dispatch to specified Controller) -> The Controller -> (Respond using JSON or Template Adapter | Call a Model | Call ACL | Call Event | Queue | API Request | etc....) -> end.

Symfony2: Transformation of database records for displaying

I have rather theoretical question about proper approach of using Symfony though I believe the approach is to be same for any other PHP framework.
I have tariff objects stored in database. I want to provide a cost model for each tariff basing on user input.
My initial approach was to create an array, one's each element would contain data from corresponding tariff object and calculated data. All of that was done in controller's action method.
Later I have created another class CostModel and then created an array CostModel[], which than was passed to $this->render() method. Again it's done in controller.
This approach works well enough. However, since I have not much experience with Symfony, I have doubts that this approach - performing calculations in controller - is good one.
Is there any better way for this?
Well, your question could have more than one answer as it is very opinion-based.
What I can say without any doubt about controller's code is that the less it is the more is good. Why I said that? Because controller code isn't reusable, because controllers are made to "connected" views and business logic (keep attention: connect, not encapsulate) and a general rule that I follow when I develop with Symfony2, is to write, into controller, lines of code for "objects" that are directly accessible from controller (form, request, views, and so on); all code that isn't related to these concepts should be migrated elsewhere.
Your solution is a good starting point but we cannot judge as we haven't more details and we don't know the architecture of your software. What can I say - and I hope you already know - is that you can pass to render (so to view templating system; I suppose you are using twig) directly the ArrayCollection you've obtained querying the database (so basically you don't neeed CostModel[] array). So, maybe, your approach is good but not the best: maybe you can take advantage of Repository facility, write a good query that can extract and calculate data for you (in a more optimized way) and use repository directly into controller. That way you could at the same time, migrate code where it should stay, write less number of code lines, do some optimitazion (or better, let Doctrine do for you) and you don't need to create a brand new class (model).

PHP MVC (no framework), should I be calling a lot of methods in my controller or model?

I've been working on creating my own MVC app in PHP and I've seen a lot of differing opinions online about how exactly this should be set up. Sure, I understand there seems to be a general "It's MVC, it is what you make of it" approach, but I'm running into 2 seemingly conflicting viewpoints.
A little background on my app: I'm using smarty as my presenter and an object-oriented approach. Seems simple enough, but I'm trying to figure out the ubiquitous "what is a model" question.
If I take a look at some tutorials and frameworks, they seem to view the model as strictly a class that inherits DAL methods from an abstract class, with a little bit extra defined in the class itself as your data needs differ from object to object. For example, I might see something like $productModel->get(5) that returns an array of 5 products from the database. So what if I need to query multiple models? Do I store all of the data in the controller or an array and pass that to the view? Then if I'm dynamically calling my controller, how can I persist the data unique to the controller necessary to render the view? This seems bad, especially because I then have to pass in things like "controllerName", "controllerData", and my View::render() method gets hugely bloated with parameters, unless I pass in the controller itself. Maybe I'm missing something here.
Let's say I want to make a login that queries a users table. Login is a model or a controller, depending on certain implementations I've seen online. Some implementations (I'll call this method 1) make a LoginController with method login() that might do a comparison of $_POST and what's returned from the user model instance $user->get(1) to see if a user is validated. Or maybe login() might be a method in a default controller. On the flipside, an implementation (implementation method 2) that resembles more of a Joomla approach would make a Login model and declare all of the actions inside of that. Then any data that needs to get assigned to the view would get returned from those methods. So login->login() would actually check post, see if there's a match, etc. Also the User model would probably be instantiated inside that model method.
My feelings about 1: The controller is fat. Additionally the controller is storing data pulled from models or passing in ten thousand variables. It doesn't seem to jibe with the idea that the model should be passing data to the view that the controller should be blind to. Also, let's say I want to wrap everything that is in a specific model handled by a specific controller in an outer template. I'd have to copy this template-setting code all across my controller functions that interface with this model. It seems grossly inefficient.
My feelings about 2: It doesn't make for having actions that aren't model methods. If I want to go to my site root, I have to make an index model or something that seems like overkill in order to have a model that passes data to the view. Also, this doesn't seem to be a very popular approach. However, I do like it more because I can just do View::render(mymodel->func()) and ensure that the data is going to be passed back just the way I like it without having to crap up my controller with code merging a thousand query results together.
I've waded through far too many religious arguments about this and want to know what you guys think.
I've built my own framework in the past too so I know what you're going through. I've heard the saying "build fat models" and I agree with that -- as long as the main goal is to return data. I considered the controller to be "The Overlord" as it manipulated data and directed where it should go.
For a login controller i might create something it like...
Post URI: http://example.com/login/authenticate
LoginController extends ParentController {
public function authenticate() {
$credential_model = $this->getModel('credentials');
// Obviously you should sanitize the $_POST values.
$is_valid = $credential_model->isValid($_POST['user'], $_POST['email']);
$view = $is_valid ? 'login_fail.php' : 'login_success.php';
$data = array();
$data['a'] = $a;
// .. more vars
$this->view->render($view, $data);
}
}
In my opinion data should always flow from the model -> controller -> view as it makes the most sense (data, manipulation, output). The View should only have access to what it has been given by the controller.
As for this...
Then if I'm dynamically calling my controller, how can I persist the data unique to the controller necessary to render the view?
Well I would imagine you're building a 'base' or 'parent' controller that gets extended off of by your dynamically called controllers. Those child controllers can have properties that are needed for for the view to render -- honestly I'd need an example to go further.
Hopefully this helps a bit. If you ask more specific questions I might be able to give a better thought out opinion.
If you're writing your own app, I think the best solution is to do it yourself and find out.
Ultimately, whatever makes the most sense to you, and whatever makes it easier for you to conceptualize your app and quickly add to or change it, is going to be your best option.
If one way is "wrong", then you'll find out through experience, rather than someone else telling you. And you'll know the entire situation that much better, and know EXACTLY why one way is better.
What helped me when I was writing my own framework in PHP was, strangely enough, CherryPy. It made the concept of an object-oriented web app so simple and obvious, and I enjoyed using it so much, that I modeled the basic structure of my PHP framework to imitate CherryPy.
I don't mean to imply you should learn CherryPy. I mean that simplicity, clarity, and enjoying developing with your own web app go a LONG way.
If I were to give one piece of specific advice, I'd say try to avoid retyping code; write your code to be reusable in as many situations as possible. This will not only be good for your app, but for future apps you may write or work on.
You might check out Eric S. Raymond's Rules for Unix Programming. I think they're definitely applicable here.

Which Code Should Go Where in MVC Structure

My problem is in somewhere between model and controller.Everything works perfect for me when I use MVC just for crud (create, read, update, delete).I have separate models for each database table .I access these models from controller , to crud them . For example , in contacts application,I have actions (create, read, update, delete) in controller(contact) to use model's (contact) methods (create, read, update, delete).
The problem starts when I try to do something more complicated. There are some complex processes which I do not know where should I put them.
For example , in registering user process. I can not just finish this process in user model because , I have to use other models too (sending mails , creating other records for user via other models) and do lots of complex validations via other models.
For example , in some complex searching processes , I have to access lots of models (articles, videos, images etc.)
Or, sometimes , I have to use apis to decide what I will do next or which database model I will use to record data
So where is the place to do this complicated processes. I do not want to do them in controllers , Because sometimes I should use these processes in other controllers too. And I do not want to put these process in models because , I use models as database access layers .May be I am wrong,I want to know . Thank you for your answer .
Just a short comment (no solution) AFAIK that is an eternal question - MVC is just a pattern, and as such, is in theory implementable cleanly. In practise, due to limitations set by available tools (such as programming language library contents and UI component interface design..) you have to make local decisions. The important thing is that you aim to separate these...and not have everything in one mess. I take my comment off the air and am left to see if someone has a "final solution".
For simple tasks I would write action helpers (e.g. sendNewsletter).
For sophistocated tasks I woud create services (eg. email, auth etc.).
In MVC, you should place those things in the model (for reuse reasons for one).
However, in HVMC, you could place them wherever (such as in a controller) and call the controllers from within your application.
I would make your controllers simple.
In many ways the model allows you to offload a lot of the complexity that would otherwise occlude your controller code. Its this division of complexity which will make your code more easily understood, and easier to maintain.
personally I try to keep my models resembling real world objects, not databases tables or rows. It makes it much easier if you have made things speak in more readable terms. A single real world object might involve 5 or 6 database tables... And it would be a rather large hassle to speak with 5 or 6 models, when all you want to do is turn on a switch, or pick a flower, or paint an icon, or send a message.
What's wrong with a controller using multiple models? Isn't the point of MVC to make the model reusable? In your first scenario, it's perfectly fine to send emails and manipulate other model objects from wherever the "register user" controller code is.
In regard to your second scenario, why can't SearchController use ArticleModel, ImageModel and VideoModel? It's fine to have a controller without a model. SearchController doesn't need a SearchModel class, it just uses the other model classes.
I'm trying not to get into a rant about MVC in web apps, but basically, IMHO the controller is just a high-level list of steps to complete an operation. As a rough example, the "register user" controller code should do each of the following steps in roughly one or two lines of code:
Validate the input
If not valid, redisplay the form with an error
Create the new UserModel object from the form input
Insert the new UserModel object into the database
Create/edit whatever other model objects are necessary
Send off an email to the new user
Display a "registration successful" page
How those steps are coded largely depends on whatever framework/architecture you're using.
Keep your controllers clean. For backend processing use Manager classes like MailManager etc..

Best way to organize applications?.... (MVC design pattern)

When building applications, whats the best way to decide what goes where. How do you know what functions to put in what controllers and models. For example, I'm building an application that is based highly on location. Users can post different things, that will in turn be shown to other users within a certain distance. Also, each user will have their own profile page that will show everything posted by that user regardless of location.
So I have models like this
class UserModel extends BaseM{
get_user($uid);
get_all_users();
edit_user($new_data);
delete_user($uid);
add_user($new_user);
get_user_articles($uid);
get_user_reviews($uid);
get_user_foo($uid);
}
class ArticleModel extends BaseM{
get_article($aid);
get_all_articles();
add_article($new_article);
delete_article($aid);
}// similar to ReviewModel, and other models
class LocalModel extends BaseM{
get_local_articles($zip_code, $range);
get_local_reviews($zip_code, $range);
get_local_foo($zip_code, $range);
}// holds all location related functions
As you can see, I lumped everything dealing with a user (needs a userID) in the userModel, everything dealing with location (needs a zip-code) in the localModel, and then everything else has its own model.
I was wondering whats the best way to figure out what goes where, is there like a rule of thumb for this kind of stuff?
Well you're 80% there already. You've got your models broken out and that is a big battle. Next design the app that you want. If you end up with a lots of repetitive "elements" on multiple pages, then each element should be a view. Otherwise each page should be a view. Or some combination of the two.
Once you have you pages defined and you know the data flow of the app, all that remains is the controller.
It may be practical in a small app to have a single controller. Or for really complex apps, you may have multiple controllers - no more than one per "page" though.
Just keep in mind - the Model should be view agnostic (you can retool the UI without impacting the model). The views should be blind to where the data comes from or where it's going - everything gets filtered through the controller.
See my previous answer to a similar question here:
I normally use this approach: try to put it somewhere. if after a while you use it, it feels awkward, then it's not in the right place.
In general every model class should have methods that make sense for itself, and eventually return other models. Refrain from putting too much computational intelligence in your models. If there's something that feels strange in either classes, there's probably a third class in between to be discovered.

Categories