alias.io

I'm Elbert, a Dutch expatriate programmer in Australia. I use and create open-source software.

Currently employed as Technical Director at Tundra Interactive, a digital agency in Melbourne.

Contact

honeypot@alias.io PGP Key

Creating a Magento module, part II

Published on November 10, 2012

Continued from Creating a Magento module, part I (getting started).

This article describes how to create a basic Magento Model.

Model

The Model is the M in MVC. Typically this is the part of the application that interacts with the database. Magento Models play a much bigger role and are responsible for most of the business logic.

1. Create a Model directory

Create a directory at app/code/local/[Namespace]/[ModuleName]/Model.

2. Create a Model

Create a file at app/code/local/[Namespace]/[ModuleName]/Model/[ModelName].php.

<?php

class [Namespace]_[ModuleName]_Model_[ModelName] extends Mage_Core_Model_Abstract
{
}

The Model's class name must match the file's path, replacing slashes with underscores.

3. Configure the Model

Open app/code/local/[Namespace]/[ModuleName]/etc/config.xml and add the article between Start and End. Substitute the values between square brackets with your own.

<?xml version="1.0"?>
<config>
  <modules>
    <[Namespace]_[ModuleName]>
      <version>1.0.0</version>
    </[Namespace]_[ModuleName]>
  </modules>
  <!-- Start -->
  <global>
    <models>
      <[model_group_name]>
        <class>[Namespace]_[ModuleName]_Model</class>
      </[model_group_name]>
    </models>
  </global>
  <!-- End -->
</config>

As always with configuration changes, clear the cache.

Configuration in the <global> section is available throughout all of Magento. You may use <adminhtml> or <frontend> instead to limit configuration to those areas.

The <[model_group_name]> is used as an identifier and is typically the same as the module name.

The <class> tag contains the class prefix of all models in the group.

4. Load the Model

To check if the Model is working, create a file test.php in the root directory of your Magento installation:

<?php

require_once 'app/Mage.php';

umask(0);

Mage::app();

// Create a Model instance. The first letter in modelName must be lower case.
$model = Mage::getModel('[model_group_name]/[modelName]');

echo get_class($model);

This should print out the class name of the Model. If you see a blank page the Model could not be loaded, carefully retrace your steps and check for typos.

At this point the Model doesn't do anything noteworthy. The next parts will demonstrate what different types of Models can do.

Continued at Creating a Magento module, part III (Observer).