如何在Laravel 5.1中自动加载自定义类? [英] How can I autoload a custom class in Laravel 5.1?

查看:165
本文介绍了如何在Laravel 5.1中自动加载自定义类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在app文件夹中创建了一个library文件夹,以添加自己的类.

I've created a library folder within the app folder to add my own classes.

这是文件app/library/helper.php的内容:

<?php

namespace Library;

class MyHelper
{
    public function v($arr)
    {
        var_dump($arr);
    }
}

我将名称空间添加到composer.json:

然后我跑了

$ composer dump-autoload

,但似乎没有任何效果.

but it does not seem to have any effects.

文件

  • vendor/composer/autoload_psr4.php
  • vendor/composer/autoload_classmap.php
  • vendor/composer/autoload_psr4.php
  • vendor/composer/autoload_classmap.php

没有改变.

如果我尝试创建MyHelper的实例,Laravel报告以下错误:

If I try to create an instance of MyHelper, Laravel reports the following error:

我不确定自己做错了什么.

I'm not sure what I am doing wrong.

推荐答案

您的自动加载配置几乎不错,但是您拥有

Your autoloading configuration is almost good, but you have

  • 弄错了命名空间
  • 走错了路

要解决此问题,请调整您的自动加载配置:

To fix the problem, adjust your autoloading configuration:

{
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "App\\": "app/"
        }
    }
}

然后将目录/library重命名为/Library(注意情况).

Then rename the directory /library to /Library (note the case).

然后将文件/app/Library/helper.php重命名为/app/Library/MyHelper.php(请注意类名应如何与文件名匹配).

Then rename the file /app/Library/helper.php to /app/Library/MyHelper.php (note how class name should match the file name).

然后调整/app/Library/MyHelper提供的类的名称空间,以匹配PSR-4前缀(以及项目的结构)以及该类的用法:

Then adjust the namespace of the class provided by /app/Library/MyHelper to match the PSR-4 prefix (and thus the structure of your project), as well as usages of the class:

namespace App\Library;

class MyHelper 
{
    public function v($arr)
    {
        var_dump($arr);
    }
}

有关参考,请参见:

这篇关于如何在Laravel 5.1中自动加载自定义类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆