Rewrite a native magento Model

Here is a small article until the next which is a little longer to write on Events and Observers in Magento .

Modify an existing model

In the last tutorial I taught you how to change the behavior of a native magento block. Sometimes it is necessary to change a behavior in a Model class, we'll see how to do this in this tutorial.

How to rewrite a model?

We will use the MyProduct module previously created and extend the class of Model that represents the customer, the Mage_Customer_Model_Customer to change the getName() function.
On magento, when an object has an attribute, you can call it with the getXXX method (or XXX is your attribute). For example the customer with an attribute "firstname", we can do getData('firstname') or getFirstname () .. it's the same thing. The difference is that by using getData ('firstname') it directly recovers the name value of the object, without treatment. If I use getName(), I can turn this if necessary as our next overload:

class Pfay_Myproduct_Model_Customer extends Mage_Customer_Model_Customer
  public function getName()
	$name = '';
	if ($this->getPrefix()) {
	    $name .= $this->getPrefix() . ' ';
	$name .= $this->getFirstname();
	if ($this->getMiddlename()) {
	    $name .= ' ' . $this->getMiddlename();
	$name .=  ' ' . $this->getLastname();
	if ($this->getSuffix()) {
	    $name .= ' ' . $this->getSuffix();
	return $name.'22222222';

Like the rewrite of a block, you must create a Model that will extend the class you want to modify : Mage_Customer_Model_Customer. To tell magento this file exist, and he must take your new model class rather than the former one, you must declare in <global> in your config.xml:

        <product> Pfay_Myproduct_Model_Customer</product>
Now, if you use your method getName() on a Customer object type, you will have the string "22222222" after the name. It takes your new method instead of the former, you are good :) This is an example to show you how to make a change to a Model easily, this example is useless because puting 222 at the end means nothing but it is easy to understand the way to do it. Now you can override model behaviours, you can do it with every magento model you want.

There you go ! Congrats, You now know how to rewrite a Model. As usual, feel free to leave your questions in the comments and download the code of this tutorial if it doesn't work for you to compare my code with your and see where there are differences.
Available documents for this article :
Books that can help you :
  • Livre Magento Developer's Guide by Alan Mc Gregor
  • Livre Magento Performance Optimization
  • Livre Grokking Magento Vinai
Questions about this lesson
No questions for this lesson. Be the first !

You must be logged in to ask for help on a lesson.