Kategorie-Archiv: OSS

Rewrite Classes in Contao

The Contao Web CMS System provides the possibility to rewrite classes of the core or of 3rd party modules.

In case you want to publish your extension, this is not a suggested way because this can create conflicts if two installed modules try to rewrite the same class. But for local modules this is a valid method.

First of all you must ensure, that your module is loaded after the module you want to rewrite. You can assure this by giving your module a name which comes alphabetically after the name of the module to be rewritten. Or you can add a line

requires[] = "dlh_googlemaps"

to your autoload.ini. Digging into the code you find out that this require statement is evaluated in \Contao\ModuleLoader::scanAndResolve.

Now you simply have to add your class to the autoload.php with the same class name (without namespace prefix) as the class to be rewritten:

	'Mymodule\Googlemap' => 'system/modules/mymodule/classes/Googlemap.php',

The class loader uses the class_alias() PHP function to define an alias for the class name without the namespace. So now the class can be instantiated using \Googlemap.

Your Googlemap.php would look like this

namespace Mymodule;

class Googlemap extends \delahaye\googlemaps\Googlemap {
    public static function getMapData($intMap, $strFormat= '', $arrParams=false) {
        parent::getMapData($intMap, $strFormat, $arrParams);
        // your code

If you set

$GLOBALS['TL_CONFIG']['debugMode'] = true;

in your localconfig.php, a debug area is displayed on the page’s bottom indicating which classes are aliased:


The method \Contao\ClassLoader::findClass() is responsible for searching the registered namespaces for the class. The static field ClassLoader::$namespaces contains the registered namespaces in reverse order of the loading order of the modules so the first match is picked.

There is one catch: if two or more of your modules use the same namespace, all of them have to be loaded before the module you want to overwrite (using the required-configuration mentioned above) . Otherwise the namespace will be listed in the wrong order as each namespace can be only registered once and the overwrite will not have an effect.