Monday, 30 April 2012

MCD: Class Naming Conventions and Their Relationship with the Autoloader

Magento was developed based on the Zend Framework, so the rules of class naming in Magento were taken from the Zend Framework (read more here).

Magento standardizes class names depending on their location in the file system. Such standardization enables automatic class loading (autoloader) instead of using require_once and include_once functions. Rather than the directory separator (‘/’ – invalid character for class names), developers use the underscore character (‘_’).

For example, the Mage_Catalog_Model_Product class is located in the /app/code/core/Mage/Catalog/Model/Product.php category. Magento autoloader replaces all underscore characters (‘_’) with the category separator (‘/’) and looks for the file in one of the categories (/app/code/local can be disabled in the app/etc/local.xml in the disable_local_modules tag).

- /app/code/core

- /app/code/community

- /app/code/local

- /lib/

File search categories in Magento are defined in app/Mage.php.

/**
     * Set include path
     */
    $paths[] = BP . DS . 'app' . DS . 'code' . DS . 'local';
    $paths[] = BP . DS . 'app' . DS . 'code' . DS . 'community';
    $paths[] = BP . DS . 'app' . DS . 'code' . DS . 'core';
    $paths[] = BP . DS . 'lib';
 
    $appPath = implode(PS, $paths);
    set_include_path($appPath . PS . Mage::registry('original_include_path'));
    include_once "Mage/Core/functions.php";
    include_once "Varien/Autoload.php";

The Varien_Autoload class is used for automatic upload:
class Varien_Autoload
{
...
/**
     * Register SPL autoload function
     */
static public function register()
{
        spl_autoload_register(array(self::instance(), 'autoload'));
}
  /**
     * Load class source code
     *
     * @param string $class
     */
    public function autoload($class)
    {
...
   $classFile = str_replace(' ', DIRECTORY_SEPARATOR, ucwords(str_replace('_', ' ', $class)));
...
   $classFile.= '.php';
     return include $classFile;
    }

Creating objects in Magento

Magento provides a special method to create models, helpers and blocks, using the Mage global class with a shortened class name. For example, to get the Mage_Catalog_Model_Product model in Magento the Mage :: getModel (‘catalog / product’) method is commonly used.

catalog – shortening for Mage_Catalog_Model
product – determines which class will be used

Correlation of the class name with a shortened name takes place in the module configuration (/etc/config.xml).

<!--?xml version="1.0"?-->
 
                <!-- a shortened name -->
                Mage_Catalog_Model
 
                <!-- a shortened name -->
                Mage_Catalog_Block
 
                <!-- a shortened name -->
                Mage_Catalog_Helper
 

Courtesy: http://blog.belvg.com/

No comments :

Post a Comment