dougou8639 2019-08-09 12:27
浏览 58
已采纳

类不在命名空间中

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?

  • 写回答

1条回答 默认 最新

  • doumigu9594 2019-08-09 14:01
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料