An Overview of Magento’s Get and Set Methods

Magento handles its get and set methods in a way that if you do not understand how it works it can be confusing to you. In the beginning of this article you have to take a leap of faith and believe in magic.

In Magento you can take nearly any model and get all the information about it with a simple function call. See the example below:

$product = Mage::getModel('catalog/product')->load(1500);
print_r($product->debug());

This code will return an array of all the basic information about the product. For this example lets say that it only returned two elements to the array “name” and “meta_description”.

Now in order to get this information you will have to take the information and camel case it to create the function. So to get the information you would write the following:

echo $product->getName();
echo $product->getMetaDescription();

Do you see how the Meta Description function was formatted? The first letter of the words are capitalized (or camelized) to create the function. So lets say you had an attribute called this_really_important_long_attribute you would call $product->getThisReallyImportantLongAttribute()

Now that you understand that, in order to set the attributes value, you simply replace “get” with “set” and pass the variable as a parameter of the function. So to set the name you would make the following function call:

$product->setName($new_name);

Ok remember when I said that you had to believe in magic? That is because if you look at the Product model, you will not find these functions defined anywhere. In fact if you are hardcore you can follow the class all the way to the top and you will not find these functions defined.

Ok now that you believe in magic, let’s take the curtain away and show you how Magneto accomplishes this. Nearly every class in Magento extends from the Varien Object (which is located in the /lib/Varien/Object.php file). You will see there is a getData() and setData() functions. These look like they could do the actual setting and getting but this is not the magic we are looking for.

Farther down in the file you are going to find the __call() function. This is the magic. This magic here is actually from PHP. The __call() function gets called anytime you call a function on a class that does not exist. The __call() function takes two parameters. The first one is the name of function that was called, the second one is the data that was passed to the function.

Now what Magento does is take the function that was called, determine if the function is a get or set function. Then it parses the string to find the attribute and then it makes the appropriate function call to get or set the data.

Once you see how this works you can see how awesome this functionality actually is.

Leave a Reply

Your email address will not be published. Required fields are marked *