HowTo:Override a core class

From ZenMagick Wiki

Jump to: navigation, search

Introduction

One of the goals of ZenMagick is to make it as easy as possible to modify existing core code without the need to touch core files. Being object oriented, inheritance is the obvious answer.

The central piece to get this going in an easy way is the ZenMagick (class) loader.

As you might have noticed, all core classes have the common prefix ZM in both file and class name. This is done for two reasons:

  • It helps to avoid name conflicts with Zen Cart classes like country, etc.
  • It allows to create sub classes that extend from core classes. Those classes would typically have the same name without the ZM prefix

Using the loader

To allow the loader to perform its magic, there is one important restriction:

New objects are created using ZMLoader::make('MyClass'); rather than using new.

Equally important is the fact that the class name used as parameter for the make(..) method does not include the prefix ZM.

The loader does know about the prefix and will resolve the class name as follows:

  1. Does the class already exist? If yes, create new instance and return
  2. If not, check if a class with that name is available - if so, load, create instance and return
  3. If not, check if a class exists with the prefix ZM added - if so, load, create instance and return
  4. give up and return null

All that is left is to make the new class available to the loader:

  • Add the new code to the directory zenmagick/core/ext
    This will make this class available to all themes
  • Add the new class to the extra directory of your theme; for example: zenmagick/themes/[MY_THEME]/extra/Categories.php
    This will replace the ZenMagick service class ZMCategories with a custom implementation if MY_THEME is used.

Example

One of the main areas where it might be useful to replace existing code is the toolbox. So, let's assume we'd like to replace the current implementation of ZMToolboxMacro::formatAddress(..).

1. Create a new class ToolboxMacro that extends ZMToolboxMacro.

class ToolboxMacro extends ZMToolboxMacro {
}

2. Add your custom implementation of formatAddress(). Make sure to use the same parameters as the original method.

class ToolboxMacro extends ZMToolboxMacro {
   /**
    * My address format method.
    */
   public function formatAddress($address, $html=true, $echo=ZM_ECHO_DEFAULT) {
      ...
   }
}

3. Save into a file named ToolboxMacro.php and copy into your theme's extra folder.

4. Done!

Personal tools