Magento:Describe the basic concepts of models, resource models, and collections, and the relationship they have to one another [closed] - magento

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I'm trying to understand Magento and I was wondering if someone can give me any insight on this topic
Describe the basic concepts of models, resource models, and collections, and the
relationship they have to one another

Resource Models are objects that contain code which fetches data from a datastore. In practice, this means a resource model is the object which contains the SQL building and fetching code, as well as references to objects which connects to the main Magento database.
Models are objects which contain database agnostic code for interacting with a "type" of data. In traditional data modeling terms your model objects contain the business logic for a particular kind of object (kind of object meaning Product, Customer, etc.).
Important: In addition to the above definition, parts of Magento code use "Models" as generic object that contain business logic unrelated to data. These "models" should be thought of as plain old objects, just instantiated through Magento factory pattern. Models that inherit from Mage_Core_Model_Abstract are the former — models which do not are the later. This post assumes "model" refers to the former. I've also started referring to these as Magento's CRUD models.
A Collection is an object which contains code that fetches a group (collection, array, list, etc.) of model objects. Since it generates SQL to do this, it's also considered a resource model and is instantiated with the Mage::getResourceModel method, (Although collection objects inherits from a different chain of classes than the normal resource models. These are not the design patterns you are looking for). Collection objects also implement certain standard PHP interfaces, and may be used in foreach loops to iterate over their results.
A Magento model object contains a reference to a resource model, which is uses to load its data. There's an individual resource model object for each model object. i.e. A Product Model has a Product resource model.
A Magento model object may also be used to instantiate a collection object. Collection objects are also typed to match their model objects. A Product model may be used to instantiate a Product collection object.
A collection object creates SQL to fetch a group (collection, array, list, etc.) of objects, and it also contains code to assign data to the main model object. Because this code is slightly different than the code in a model's resource model object, there are often slight discrepancies between models loaded directly or via a collection. For example, a collection does not call each model's _afterLoad method, or an EAV collection will not load all attribute data by default (unless addAttributeToCollection('*') is used). A lot of Magento development is tracking down and account for these discrepancies.
Finally, there are places in the Magento source code that deviate from the above. For example: Report collection object are free standing — they are not ties to a specific model class. Keep the above in mind, but be ready for specific Magento modules to surprise you.

Too much to type :) Alan Storm wrote great article about magento model basics

Related

How to map SQL queries to in-memory model objects?

Let's say we are structuring an application with MVC (also, Stores/Services). SQL is used as the persistence mechanism. And memory efficiency is a major concern.
Obviously, we should take advantage of SQL queries and only ask for fields of our Model in theory object when they are needed.
For example, an mobile app may need to display a list of title for articles, while the body of the article doesn't get displayed until user taps on a specific title. In this case, we ask SQL for just the titles first.
The question is, what should the model object look like?
The solutions I can think of are:
Enhance the model with some states that indicate which fields are populated. This could also be archived by using nil/NULL/None values on unpopulated fields of the model object.
Split the theoretical model to multiple classes. Following the previous example, we could have an Article class and an ArticleDetail class, with a one-to-one relation.
Forget the Store object, let each model object lazy evaluate it's costly fields. The model would have to know about its persistence mechanism.
This should be a common problem. How do the ORM in your favorite frameworks/libraries resolve it? Any best practices?

CodeIgniter MVC Model Logic

I have programmed in Rails, Django, Zend, and CakePHP. Also, Wordpress and Drupal.
Now, I am "catching up to speed" in as fairly large application in CodeIgniter.
Typically, my experience with MVC frameworks, has led me to believe that Models represent business logic in reference to actual database tables. In the CodeIgniter docs and in the code base I'm dissecting I see models created that represent something as vague as a page. A lot of the business logic is written directly into those models and they incorporate other actual data models. I'm not sure this is ideal and following MVC.
Should models be created beyond data models?
Also, lets say I have a data model representing a user (user table in DB). In that user table there is a column called gender of the type enum('male', 'female'). Now I want to populate a dropdown with the gender options from the enum column.
Where is it most appropriate to put this logic?
The user model is an object used to represent a single user or row in the db... right? So it doesn't seem fitting to include a function in the user model/class called "get_gender_options", because, while the function is related to the user table, it is NOT relevant to a single user object. In Zend this kind of logic could be built into the form object itself.
There is not "right" answer, just one we can consider the most appropriate...
I would probably just put the "get_gender_options" in the model, rather than sticking it in the view for the form. To keep it DRY but not put it in the model, I would create a helper to hold this.

how to use codeigniter database models

I am wondering how the models in code ignitor are suposed to be used.
Lets say I have a couple of tables in menu items database, and I want to query information for each table in different controllers. Do I make different model classes for each of the tables and layout the functions within them?
Thanks!
Models should contain all the functionality for retrieving and inserting data into your database. A controller will load a model:
$this->load->model('model_name');
The controller then fetches any data needed by the view through the abstract functions defined in your model.
It would be best to create a different model for each table although its is not essential.
You should read up about the MVC design pattern, it is used by codeigniter and many other frameworks because it is efficient and allows code reuse. More info about models can be found in the Codeigniter docs:
http://codeigniter.com/user_guide/general/models.html
CodeIgniter is flexible, and leaves this decision up to you. The user's guide does not say one way or the other how you should organize your code.
That said, to keep your code clean and easy to maintain I would recommend an approach where you try to limit each model to dealing with an individual table, or at least a single database entity. You certainly want to avoid having a single model to handle all of your database tables.
For my taste, CodeIgniter is too flexible here - I'd rather call it vague. A CI "model" has no spec, no interface, it can be things as different as:
An entity domain object, where each instance represents basically a record of a table. Sometimes it's an "anemic" domain object, each property maps directly to a DB column, little behaviour and little or no understanding of objects relationships and "graphs" (say, foreign keys in the DB are just integer ids in PHP). Or it can also be a "rich (or true) domain object", with all the business intelligence, and also knows about relations: say instead of $person->getAccountId() (returns int) we have $person->getAccount(); perhaps also knows how to persist itself (and perhaps also the full graph or related object - perhaps some notion of "dirtiness").
A service object, related to objects persistence and/or general DB querying: be a DataMapper, a DAO, etc. In this case we have typically one single instance (singleton) of the object (little or no state), typically one per DB table or per domain class.
When you read, in CI docs or forums, about , say, the Person model you can never know what kind of patter we are dealing with. Worse: frequently it's a ungly mix of those fundamentally different patterns.
This informality/vagueness is not specific to CI, rather to PHP frameworks, in my experience.

MVC3 (Models) ...what is the right way to display complex data on the view?

I’m having a philosophical problem with understanding how to use Models on MVC3.
I believe the problem lies from the fact that I come from WebForms :--)
Let's say I have 10 tables on my DB and as expected when I get them into my EF4, I get those Entity classes that represent the tables (and all their FK integer values).
When I want to display data on the View, I cannot display a select * from table because those FK integers means nothing to my users …and also because some data lies on related tables.
So my understanding is that I can create a Stored Proc, create a Complex Type that represent the actual data to display, coming from separate tables via different SQL joins.
QUESTION 1:
On the view, id MVC compliant to use as #model ..that Complex Type?
or shall I always use Models that are created on the Models folder? And if so, does that mean that I have to replicate the Complex Type on a new model inside the Models folder?
Question 2:
Is this the right way …to create specific SP to collect data that will be displayed or ..is it better to use linq and lambda to be applied to the EF4 Types that come from importing the DB into the EMDX designer.
Thoughts ??
FP
The correct way is to always define view models. View models are classes which are specifically tailored to the needs of a given view and would be defined in the MVC application tier. Those classes would contain only the properties that would be needed to be displayed by the view. Then you need to map between your domain models (EF autogenerated classes?) and the view models.
So a controller action would query a repository in order to fetch a domain model, map it to a view model and pass this view model to the view. Top facilitate this mapping you could use AutoMapper. A view shouldn't be tied to a domain model and always work with a view model. This works also the other way around: a controller action receives a view model from the view as action argument, maps it to a domain model and passes this domain model to the repository in order to perform some action with it (CRUD).
So a view model could be a class that is mapped from multiple domain models or multiple view models could be mapped to a single domain model. It all depends on how your domain looks like and how do you want to represent the information to the user.
As far as validation is concerned, I distinguish two types: UI validation and business validation. As an example of UI validation is: a field is required, or a field must be entered in a given format. A business validation is : the username is already taken or insufficient funds to perform wire transfer. UI validation should be done on the view models and business validation on the domain models.
I'm not sure why you need to use a stored proc, LINQ to Entities is able to generate complex types without needing to create stored procs (in most cases). You select subsets of data, just like you would with regular SQL.
As Darin says, the use of a View Model is appropriate for situations where you have a lot of complex data that isn't represented by a single entity. This View Model would contain multiple entities, or even multiple collections of entities. It all depends on how your data needs to be consumed.

Why Two Classes, View Model and Domain Model?

I know it could be bad to use domain models as view models. If my domain model has a property named IsAdmin and I have a Create controller action to create users, someone could alter my form and get it to POST a IsAdmin=true form value, even if I did not expose such a text field in my view. If I'm using model binding then when I committed my domain model, that person would now be an admin. So the solution becomes exposing just the properties I need in the view model and using a tool like AutoMapper to map the property values of my returning view model object to that of my domain model object. But I read that the bind attribute on a class can be used to instruct the Model Binder which properties it should and shouldn't bind. So what really is the reason for making two separate classes (domain model and view model) that essential represent the same thing and then incure overhead in mapping them? Is it more a code organization issue and if so, how am I benefiting?
EDIT
One of the most important reasons I've come across for a View Model that's separate from the Domain Model is the need to implement the MVVM pattern (based on Martin Fowler's PM pattern) for managing complex UIs.
I have found that while my domain model gets me 85% of the way to having the fields I want, it has never covered 100% of the values I want on my view. Especially when it comes to permissions and whether or not a user should have access to certain portions of the view.
The design concept I attempt to follow is to have as little logic in my views as possible. This means I have fields in my view model like "CanViewThisField" or "CanEditThisField." When I first started with MVC I would have my domain model be my view model and I was always running into the scenario where I needed just one or two more fields to make my view less cluttered. I've since gone the View Model/Model Builder route and it has worked wonderfully for me. I don't battle my code any longer but am able to enhance my view model as I need to without affecting the domain model.
Another good reason to have a ViewModel is paging large sets of data. You could pass the view an array of Person ( Person[] ) but metadata such as the number of pages, the number of the current page, the size of the page would not belong on the Person class.
Therefore a PersonListViewModel would solve this issue.
A ViewModel holds only those members which are required by the View. They can usually be thought of as a simplification or a "flattening" of the underlying domain model.
Think of them like this:
ViewModel: this is the data that is appropriate to render on this
view
Domain model: this is all the information my application needs
about this entity in order to perform all it's functionality
For example, my Order class has a member called Customer which is a composition association, that is, my Order has a Customer. This Customer object has members such as Firstname, Lastname, etc... But how would I show this on a "details" view of the order or a list of Orders and the Customers who placed them?
Well, using a ViewModel I can have an OrderListItemViewModel which has a CustomerName member and I can map the combination of Firstname and Lastname from the Customer object to this. This can be done manually, or much preferably using Automapper or similar.
Using this approach, you can have multiple Order ViewModels that are specific to different views, e.g. the Order list view might render the customer name in a different way to the Order details view.
Another advantage of ViewModels is that you can cut down on extraneous data not required of the underlying domain object on a view, e.g. if I'm viewing a list of orders, do I really want to see all the customer's contact information, billing details, etc...? I guess that depends on the purpose of the list but, probably not.
Sometimes you need to display the data in a specific manner (ie, displaying a date in the format mm/dd/yyyy vs. yyyy/mm/dd) and often it is easier to make this property in the view and not in the domain model, where you would (or should) have a mapping to a column in your db.
you need to remember
that your domain model classes are only used internally; that is, they are never sent to the
client. That’s what your service model types (View Model types) are used for—they represent the data that will be going back and forth between the client and your service.

Resources