2

I'm fairly new to Magento, coming from a Symfony/Laravel background. Magento's ORM implementation seems a bit confusing at first. Most resource/collection classes only seem to have a _construct() method available. I am mainly wondering which methods typically are defined in the collection/resource classes and why?

E.g. Why is the method loadByEmail() in the Customer resource class and not just in the Model?

3

First of all, there is a method loadByEmail in the customer model (or Magento 2) that is just a proxy to the one in the resource model.
As a general idea (but this does not happen always), the resource model is used to do db operations. All queries should be inside the resource models.
The models are (should be) just implementations of the Active record design pattern.
And there are a lot of methods in the models that are proxies (or almost proxies) to the resource model methods.
For example load, save, delete (these are deprecated in M2 where the trend is to move these to repository classes instead of the active records).
When in doubt, if your code needs to be linked to some tables, put them in the resource model, otherwise put them in the model.

Collections are located under the resource models.
These communicate directly with the database.
They are basically lists of items.
You can apply filters, orders and limits on them, just like you do for a query, because they basically return a list of objects of a certain type based on a query you build.

  • What about collections? How do resources and collections typically work together? They both work with the database, right? – Maarten Troonbeeckx Jul 29 '16 at 13:07
  • @shineability. I edited my answer. It's easier to read like that than in a comment. – Marius Jul 29 '16 at 13:27
0

This might be helpful. If you want to specifically see the methods for the various models or whatever, rather than a general understanding of "why", you could use this bit of code to show all the methods of a Model (or whatever)

<?php
define('MAGENTO_ROOT', getcwd());
define("DIRECT_OUTPUT",true);
define("ADMIN_STORE_ID",1);

include_once("app/Mage.php");
Mage::app();
Mage::setIsDeveloperMode(true);


$myCategory = Mage::getModel("catalog/category")->load(11); //id would be some valid category id
$className = get_class($myCategory);  //this will get the actual class name - easier that looking it up yourself :)
echo "<h1>".$className." Methods</h1>";
echo "<ul>";
foreach(get_class_methods($myCategory ) as $method){
    $r = new ReflectionMethod($className,$method); 
    $params = $r->getParameters();
    echo "<li>";
    echo $method."(";
    $count=0; 
    foreach($params as $param){
        $count++;
        if($count>1){
            echo ",";
        }
        echo $param->getName();
    }
    echo ")</li>";
}
echo "</ul>";
?>

In this example you would get something like this:

Mage_Catalog_Model_Category Methods
getUrlInstance()
getUrlRewrite()
getTreeModel()
getTreeModelInstance()
move(parentId,afterCategoryId)
getDefaultAttributeSetId()
getProductCollection()
getAttributes(noDesignAttributes)
getProductsPosition()
getStoreIds()
getLayoutUpdateHandle()
getStoreId()
setStoreId(storeId)
getUrl()
getUrlModel()
getCategoryIdUrl()
formatUrlKey(str)
getImageUrl()
getUrlPath()
getParentCategory()
getParentId()
getParentIds()
getCustomDesignDate()
getDesignAttributes()
getAllChildren(asArray)
getChildren()
getPathInStore()
checkId(id)
getPathIds()
getLevel()
verifyIds(ids)
hasChildren()
getRequestPath()
getName()
getAnchorsAbove()
getProductCount()
getCategories(parent,recursionLevel,sorted,asCollection,toLoad)
getParentCategories()
getChildrenCategories()
getChildrenCategoriesWithInactive()
getParentDesignCategory()
isInRootCategoryList()
getAvailableSortBy()
getAvailableSortByOptions()
getDefaultSortBy()
validate()
afterCommitCallback()
lockAttribute(attributeCode)
unlockAttribute(attributeCode)
unlockAttributes()
getLockedAttributes()
hasLockedAttributes()
isLockedAttribute(attributeCode)
setData(key,value)
unsetData(key)
getResourceCollection()
loadByAttribute(attribute,value,additionalAttributes)
getStore()
getWebsiteStoreIds()
setAttributeDefaultValue(attributeCode,value)
getAttributeDefaultValue(attributeCode)
setExistsStoreValueFlag(attributeCode)
getExistsStoreValueFlag(attributeCode)
isDeleteable()
setIsDeleteable(value)
isReadonly()
setIsReadonly(value)
getIdFieldName()
getId()
setId(id)
getResourceName()
getCollection()
load(id,field)
afterLoad()
save()
isObjectNew(flag)
getCacheTags()
getCacheIdTags()
cleanModelCache()
delete()
getResource()
getEntityId()
clearInstance()
__construct()
_addFullNames()
_initOldFieldsMap()
_prepareSyncFieldsMap()
isDeleted(isDeleted)
hasDataChanges()
setIdFieldName(name)
addData(arr)
unsetOldData(key)
getData(key,index)
_getData(key)
setDataUsingMethod(key,args)
getDataUsingMethod(key,args)
getDataSetDefault(key,default)
hasData(key)
__toArray(arrAttributes)
toArray(arrAttributes)
_prepareArray(arr,elements)
__toXml(arrAttributes,rootName,addOpenTag,addCdata)
toXml(arrAttributes,rootName,addOpenTag,addCdata)
__toJson(arrAttributes)
toJson(arrAttributes)
toString(format)
__call(method,args)
__get(var)
__set(var,value)
isEmpty()
_underscore(name)
_camelize(name)
serialize(attributes,valueSeparator,fieldSeparator,quote)
getOrigData(key)
setOrigData(key,data)
dataHasChangedFor(field)
setDataChanges(value)
debug(data,objects)
offsetSet(offset,value)
offsetExists(offset)
offsetUnset(offset)
offsetGet(offset)
isDirty(field)
flagDirty(field,flag)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.