Writing a custom module in Magento

In: Magento

12 Oct 2008

Time to move on to some more serious stuff concerning Magento. My last few posts were about understanding a way to use Magento functions. Functions like getModel, getData, getSingleton and so on. Most important it was a way of showing you how to find the available functions ascreend how to extract the data from objects. Not sure if I fully seceded in that but hopefully I helped a bit.

Before I start with the explanation on how to actually write a module let’s take a deeper look at the module philosophy. You can look at the module as your application (that’s the way I look at it) within the main application (Magento). Just for the consistency let’s stick to the module terminology. Each module is comprised of various parts working together for the common goal. If your module is named, let’s say, SomeCoolPaymentServiceModule then the common goal of the module parts is to achieve full integration (inner workings) of Magento system with the SomeCoolPaymentService service.

So what are the parts that make the module? In MVC architecture even the bare bone application is (mostly) written across three separate files. Model, View and Controller. Ideal case is the one where Model manages all of the database connections and queries, then passes the information to controller. Controller then reorders, maps, filters, does some logic on the data and passes it to the View. View is the thing we see. View is the file served to our browsers. In Magento case View is called Block. The same block whose name we see when we turn on System > Current Configuration Scope > Developer > Add Block Names to Hints to Enabled.

Magento is built on top of Zend framework. Since Zend is pure MVC framework so is Magento’s architecture MVC based. Open you Magento installation directory and drill down into the app/code/core/Mage/Catalog/ folder. Notice the word Catalog in this path? Well, the Catalog is one of the modules inside the Magento. And the app/code/core/Mage/ path is the path to all the Magento modules, the building blocks of Magento. Now that we know where to find modules, let’s look at the content of a module. This is the content of the Catalog module:

Block /
controller/
etc /
Helper /
Model /
sql /
Exception.php

As you might notice, there are more than three type of files here. By types I think of Model, View (Block), Controller. Magento’s structure is therefore more divided. We can see the Helper and sql folders as well. Although not every Model contains the same sub folder structure like this one you need to understand that this is somewhat of a blueprint of how Magento modules are built.

So how does one write a custom module? Presumption is that you already know how to create a custom theme. Across this walktrough I will be using paths showing mycustom as the name of my theme folder. Remember this so you don’t get confused. My module will be called ActiveCodeline (wonder why :)).

Folder /app/code/core/Mage/ is used to store default Magento modules NOT the custom created ones. User (custom) modules are to be stored inside the app/code/local/ folder. The thing with PHP is that it lacks the support for namespaces. However, this did not stop Magento guys and girls for creating them. In the default Magento module folder /app/code/core/Mage/ word (folder) Mage is actually a namespace. Why is this important? Well, as I sad I’ll create a module named ActiveCodeline. Creating a directory app/code/local/ActiveCodeline/ simply means I created a new namespace named ActiveCodeline inside the user module folder. Therefore you should look at the ActiveCodeline folder as the namespace name not the module name for now.

Under the /app/code/local/ActiveCodeline/ folder (or shall I say under the namespace ActiveCodeline) create a folder (module) named Example like

app/code/local/ActiveCodeline/Example/

Now if we were to look at the newly created folder we should look at it the same way we look at the app/code/core/Mage/Catalog/ folder. Example (in our case) and Catalog (in Magento default case) are both modules. Now we can say Example is our custom module. This however is a bit contradictory since we are most likely to say that ActiveCodeline is the name of our module. What’s important is that you know the difference and avoid getting confused by the naming.

Now, let’s go into the /app/code/local/ActiveCodeline/Example/ folder (module) and create two subfolders there, Block and etc. Our folder structure should now look like

/app/code/local/ActiveCodeline/Example/
Block/
etc/

So far, we haven’t done anything that would make Magento see our new module. In order to get our module seen by Magento we need to register it. How do we register our module in Magento? drill down into the newly created

/app/code/local/ActiveCodeline/Example/etc/

folder and create config.xml file.

What do we write into this file? If you open up the app/code/core/Mage/Catalog/etc/config.xml file and have a look inside, you’ll see the stuff it contains. For our bare bone module we need to write the following into the config.xml file:

<?xml version=”1.0″ encoding=”UTF-8″?>

<config>

<modules>
<ActiveCodeline_Example>
<version>0.1.0</version>
</ActiveCodeline_Example>
</modules>

<global>
<blocks>
<ActiveCodeline_Example>
<class>ActiveCodeline_Example_Block</class>
</ActiveCodeline_Example>
</blocks>
</global>

</config>

After we save our config.xml file we can go to Magento admin, go to System > Configuration > Advanced. There you should see the ActiveCodeline_Example on the list among other modules.

Now we need to add some logic to our module. To keep things simple, I’ll make my module simply echo some stuff to the browser. Now lets create second file that we need to make our module work. Open up the app/code/local/ActiveCodeline/Example/Block/ folder and create a View.phtml file.

Place the following content into it:

class ActiveCodeline_Example_Block_View extends Mage_Core_Block_Template {

public function doSomeAction(){
$message = ‘<p>Hello from ActiveCodeline sample module…</p>’;
return $message;
}
}

Finaly, we go to our theme folder. As I told you at the beginning of this article, my theme folder is called mycustom. Therefore, inside the app/design/frontend/default/mycustom/template/ folder you need to create the example folder like

app/design/frontend/default/mycustom/template/example/

Now you create a file called view.phtml with the following content

<?php
/*
$this is now instance of ActiveCodeline_Example_Block_View
*/
?>
<div>This is the output of the activecodeline example:</div>
<?php
echo ‘Class name: <strong>’. get_class($this) .’</strong>’;
echo $this->doSomeAction();
?>

Basically these three files conclude the creation of your bare bone module. To test if the module is working, go to Magento admin > CMS > Manage Pages > Home page then write the following somewhere on the page

<h1>Sample activecodeline message…</h1>
{{block type=”ActiveCodeline_Example/view” template=”example/view.phtml”}}

Notice the type=”ActiveCodeline_Example/view”. If you were to write it like type=”activecodeline_example/view” it wont work. Watch for the capital letters.

Now if you refresh the home page of Magento shop, you would see the result message of the new module.

As I said at the beginning, this is a bare bone module, dummy module or whatever you like to call it. My intention was show you how simple it is to create a basis for module. I haven’t mentioned sql folder here or helpers folder. I leave some things for you to do. Most of the tutorials out there on creating a custom module jump right into the fire going over trough stuff I intentionally left out but they leave the basis unmentioned. Then you end up with the tutorial on how to create something cool but you are missing few steps and you go crazy trying to figure out what’s missing.

If you truly understood this walktrough and my previous articles on Magento then you are ready to connect the dots and start making more serious modules.

Hope this was helpful. All the best…

19-01-2009
p.s. Article has missed one step. I missed adding the xml to app/etc/modules/ as descibed in comments below by Coconuts-GrG.

Comments are now closed for this article…

Interesting? Share it!
  • Digg
  • del.icio.us
  • Google
  • Technorati
  • Facebook
  • TwitThis
  • description

21 Responses to Writing a custom module in Magento

Avatar

Frank

October 17th, 2008 at 4:19 am

This is a well put together walkthrough. Thank you.

Would love to see future posts on event observers, how they work, how to code to them, etc.

Avatar

jorge

October 23rd, 2008 at 4:23 pm

Thanks man… you lighten me up…

Avatar

Arthur

October 24th, 2008 at 6:23 am

Thanks, very helpfull! I’m not a programmer at all but try to follow your explanation.
After saving the config.xml in /app/code/local/ActiveCodeline/Example/etc/ nothing shows up in the System > Configuration > Advanced. However it does show after uploading a ActiveCodeline_Example.xml file in app/etc/modules/ as explained in the Wiki ‘Custom Module with Custom Database Table’. Am I doing something wrong?

Avatar

Totti

November 11th, 2008 at 4:29 am

This tut is totally wrong !!!

Avatar

Totti

November 11th, 2008 at 4:33 am

the author has missed several steps to declare a module in Magento.,

Anyway, thx for the effort.

Avatar

branko

November 11th, 2008 at 4:55 am

That’s a nice one…

I made this tutorial not form my head but by live example. And it works. At four places in this tutorial I said it was a “bare bone” module. So sure I missed few steps irrelevant to the creation of bare bone module.

Comments like your do not help a bit. Feel free to share with the community what those missed steps are… Comments like “This tut is totally wrong !!!” just don’t cut it…

Your two comments contain exactly 124 chars… if you felt the need to comment you could have been productive… and point to mistakes (if any).

Avatar

Coconuts-GrG

November 11th, 2008 at 10:52 am

Hi Branko,
I do your tut, and it helps. Thank you.

1 step forgotten : declaring your module in app/etc/modules/ActiveCodeline_Example.xml
With the lines described here : http://www.magentocommerce.com/wiki/how-to/create-payment-method-module

Thanks to this declaration (+ the one you descibed) give the result in the admin panel you explain

;-)
GrG

Avatar

Coconuts-GrG

November 11th, 2008 at 11:59 am

Another mistake :

you wrote “that we need to make our module work. Open up the app/code/local/ActiveCodeline/Example/Block/ folder and create a View.phtml file.”

you should replace “View.phtml” with “View.php”

Avatar

branko

November 11th, 2008 at 12:08 pm

Now that’s productive comment :)

Thank you…

Avatar

jadwigo

November 12th, 2008 at 10:49 am

Thanks for this tutorial…

One tip for people trying this: don’t blindly copy/paste the code, because the quotes might be messing with your PHP strings..

Avatar

Adam

November 13th, 2008 at 12:04 pm

This tutorial was exactly what i was looking for, worked like a charm after applying Coconuts-GrG’s fixes. Thanks for the tut.

Avatar

Erich

November 19th, 2008 at 9:36 am

I’m totally confused.

I followed your tutorial, making the appropriate changes suggested by Coconuts-GrG. The module appears in the advanced configuration, but when I added the content to the home page, the block fails to output anything from the module.

I’m really confused as to why this works for some people but not for me. Any suggestions for debugging?

Avatar

sriforum

November 19th, 2008 at 11:52 pm

Thanks a lot for all your help to understand on how to write a custom modules to begin with. I’ve bookmarked you for future reference. Thanks again

Avatar

kiran

November 30th, 2008 at 12:22 pm

First of all thanks for the tut. I created exactly like you said, but i am not able to get the reqd output. Is there any method to debug. Thankyou!!

Avatar

Ahsan Shahzad

December 1st, 2008 at 7:46 am

Great Article!,

your article helped me a lot to clear my mind about module creation.
This article is best to learn the basics of module creation in Magento but it will be more helping if you write another article with more advance things like database handling etc

i found this article quite good too:http://www.magentocommerce.com/wiki/custom_module_with_custom_database_table

Thanks once again :)

Avatar

Helpful Magento Tutorials from the Web | Jake Rutter - Designer, CSS/XHTML, jQuery, AS3, Magento Developer

December 7th, 2008 at 8:34 am

[...] How to write a custom Module Share and Enjoy: [...]

Avatar

Leslie

December 10th, 2008 at 6:09 pm

Hi Branko,

I am working on creating a USAePay payment module using the Magento create payment gateway instructions. I see that your instructions above call for additional files though and I am a newbie with Magento and php.

I am having a parser error issue with the
app/code/local/Mage/Usaepay/Model/PaymentMethod.php file and I wonder if you could help me fix it. If yes, could I send you the php code for this file? Here is the error:

Warning: simplexml_load_string() [function.simplexml-load-string]: Entity:
line 133: parser error : Opening and ending tag mismatch: usaepayach line 107 and payeach in
/home/the/domains/silverborn.com/public_html/lib/Varien/Simplexml/Config.php
on line 500

Otherwise, could you tell me if/what you charge to create a payment module?

Thank you,
Leslie

Avatar

Magento Website Development

December 11th, 2008 at 7:44 am

thanks

perfect step by step guide for beginers

Avatar

zmove

January 12th, 2009 at 3:37 am

Hi,

It is possible to have a package with files of that module to copy on a magento install to quickly test how it works ?

Thanks

Avatar

Shaun

January 18th, 2009 at 11:33 am

I am sorry but when i follow these instructions to the letter i am getting no admin panel or anything as best as i can see. I really could use some help here is there a version issue or something. The tutorial and the comments about what was missing were very clear and simple, its just that they dont seem to be working for me

Avatar

Anton Olsen.com » Blog Archive » Bookmarks for February 10th

February 10th, 2009 at 7:02 pm

[...] Writing a custom module in Magento, detailed walktrough | ActiveCodelineGood overview of writing a custom module for Magento. [...]

About this site

Branko Ajzele Welcome to ActiveCodeline. My name is Branko Ajzele. I'm 26-year-old, currently working as full time PHP web application developer at Inchoo (in partnership with Surgeworks). My special interest and expertise evolve mainly around Zend Framework, Doctrine ORM, Magento eCommerce platform and few other related technologies.

More about me?
View Branko Ajzele's profile on LinkedIn
  • Uwe Stoll: Thanks for your valuable advice. Furthermore, I found it be important to use the backend generated [...]
  • Danny: Ah. I think I figured it out.. But 1 thing.. How can I have it appear at just the home page and on t [...]
  • Danny: I've set everything up as instructed on this page, but it still doesn't show up on the front page... [...]
  • Chris: [code] true local [/code] [...]
  • Chris: Looks like the author forgot to include a pool to which the code comes from. local or community. [...]

Categories