phpcontao

Class not in namespace


I am trying to create a hook extension for Contao. But Contao doesn't seem to be able to load my class from the namespace, which handles the hook. This is my file structure:

I have tried changing names and added ".php" to the class, looked up tutorials, but I can't find what I am doing wrong. I am fairly inexperienced in this topic, so I might be missing something obvious.

autoload.php

ClassLoader::addNamespaces(array 
    ( 
        'Memberlevels', 
    )); 

gister PSR-0 namespace 
 */ 
if (class_exists('NamespaceClassLoader')) { 
    NamespaceClassLoader::add('Memberlevels', 'system/modules/memberlevels/classes'); 
} 


if (class_exists('NamespaceClassLoader')) { 
    NamespaceClassLoader::addClassMap(array 
        ( 

            'Memberlevels'                => 'system/modules/memberlevels/classes/myClass.php' 
        )); 
} 

/* 
 * Register the templates 
 */ 
TemplateLoader::addFiles([ 
    'cookiebar' => 'system/modules/memberlevels/templates', 
]);  

config.php

$GLOBALS['TL_HOOKS']['outputBackendTemplate'][] = array('Memberlevels\myClass', 'myOutputBackendTemplate');  

I get the error message:

Attempted to load class "myClass" from namespace "Memberlevels". Did you forget a "use" statement for another namespace?


Solution

  • You are still using the old Contao 3 way of loading classes. In Contao 4, you should use the autoloading feature of composer. The default composer.json of the most recent Contao versions already include autoloading directives for the src/ folder of your Contao installation:

    "autoload": {
        "psr-4": {
            "App\\": "src/"
        }
    },
    

    Using that, this is how you create & register a hook in a Contao 4.4 compatible way:

    // src/EventListener/OutputBackendTemplateListener.php
    
    namespace App\EventListener;
    
    class OutputBackendTemplateListener
    {
        public function onOutputBackendTemplate(string $buffer, string $template): string
        {
            // Do something 
            return $buffer;
        }
    }
    
    // app/Resources/contao/config/config.php
    
    $GLOBALS['TL_HOOKS']['outputBackendTemplate'][] = [\App\EventListener\OutputBackendTemplateListener::class, 'onOutputBackendTemplate'];
    

    Starting with Contao 4.8 you can also use annotations to register a hook, eliminating the need to register the hook in app/Resources/contao/config/config.php.