Using models in laravel 4 - php

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.

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:

CakePHP: Queries in Controller or Models?

If I really go through the MVC approach, then the queries should be in the Model, in CakePHP case the Table Classes, but when I go through the tutorials and documentation that Cake Provides they simply state that queries should be in the Controller.
As you can see in the example over here on Cake's websites: https://book.cakephp.org/3.0/en/tutorials-and-examples/blog/part-two.html
But if I go through this link or many other I have come across, the query part should be in the Models: https://www.toptal.com/cakephp/most-common-cakephp-mistakes#common-mistake-3-keeping-business-logic-in-controllers-instead-of-models
It is not just about what Cake displays in the examples or some developers opinion, but what should really be the genuine way to code in Cake when dealing with database queries. I have found almost 90% people doing query related tasks in Controllers only for Cake, as they quote "Cake mentions the same in their examples". But what about the MVC way, we create Table Classes just to mention the associations then? If Cake's own website does that, then somehow it means they have done it intentionally.
It's a good programming practice that to use your database queries in your Model because you can reuse these queries(In another controller) later by calling the method using the object of the model. However, you can also write your queries in your Controller.
For example:-
//Consider this code block is in Products Model
function totalActiveProduct(){
$totalProduct=$this->find('all', ['conditions'=>['is_active'=>'Y']]);
return $totalProduct;
}
If you want to get the total active product in any controller you can do this,
$this->Categories->Products->totalActiveProduct(); //Total procuct in category controller
$this->Products->totalActiveProduct(); //Total products in Product controller.
Actually, when you are writing the query in you controller, you have to use the object of your model(That means indirectly you are using your controller). You are thinking that you are writing this in your controller but actually, you are writing it in the model(Object of Model).
$this->Products->find('all');
Simply this means you are writing this in your model object(Where Products is the model object). Directly or indirectly you are doing your each and every database operation through the Model.

MVC Implementation in Yii 1

I am currently looking to redesign a feature on my web application.
The web application utilizes Yii (version 1) for the back-end.
In this instance I have a model and controller. The model is used to store all the userTracking data and is appropriately a userTracking model however the actual logic for the model is in a controller called UserController. I have a function called actionTrackUser($id) which is used to implement various tracking logic for a particular user and create a model for that user.
I however now need to extrapolate this functionality from the UserController to a seperate trackingController which will implement tracking for various models.
I need to be able to utilize this functionality however in the new controller and old controller. I was wondering as to the best approach for this in Yii 1 that implements MVC correctly. I thought about making a trackingModel and having the userTracking model extend that but then I would have a lot of business logic in a model in order to use it in two places.
I am fairly new to MVC and Yii so I was wondering as to the best approach to take here?
I have purposely left code out of this question as it is more a theoretical question regarding the implementation of such functionality in Yii.
Any help is appreciated.
Thanks!
I am not sure that there may be a 'best' approach. However, you need to choose an approach that works best for you. Be guided by what will work for your situation, and what will make manageable code for you and others in the future.
There is nothing wrong with your current userTracking model and controller. You state that the "actual logic for the model is in a controller." You may want to relook at that to move appropriate data management, constraints and validation rules to the model at least.
You can move functions to a separate trackingController and still use the userTracking model. There is no rules that says you have to have a matching model and controller set, and it is quite possible for a controller to manage more that one model at a time.
I generally start with activeRecord models, which map against data stores (database tables in most cases). I use corresponding Form models to reflect forms that are markedly different from activeRecord models, and I use domain models to reflect complex business objects that are feature rich, and reflect lots of runtime attributes (like calculated fields) and state data (like publish state, which are calculated from other fields - for example a user could have validation status, paid status, active status, account level and so on that all work together to indicate what activity is possible for the user).

Yii: Following strict MVC rules to ensure that all the business logic is in appropriate places

Sticking to MVC basics in Yii, I am trying to embed my business rules in the model class but facing problem in implementing it. The problem at hand is to stop the user from making duplicate entries and code the function in model class that checks if the entry already exists in table. I want to write a method in my model class which would query the sames model's underlying table and if the new business entity exists, it simply returns false. If I code this in controller, I can achieve the desired functionality but I want to keep this in model so that where ever the model is used, I can access the method and also stick to MVC basics which dictates Thin Controllers and Thick Models. Thanks in advance.
The best way would be to avoid the use of active record instances (at least) directly in the controller.
Instead you should create service-like structures, which contains the interaction between your CActiveRecord and CFormModel instances. This would let you better isolate the presentation layer (views, controllers and templates) from model layer.
Such services also would be able to hold (and sometimes, react upon) errors/exceptions thrown by CActiveRecord and CFormModel instances, that it utilizes.
Cross-site Request Forgery Prevention may be what you are looking for? unless your idea of 'duplicate entries' is directly related to your business model, in which case you can override the CActiveRecord.beforeSave() and put your logic in there, if this method returns false, the record won't be saved to the database.
If you use the later method, and you want to pass the error to the view and display to the user, you can always use the CModel.addError() method, in this case in your beforeSave method.
There is another option though, which is using custom validators.
which is more appropriate? depends on your business logic.

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

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.

Categories