Laravel:引入自定义类/库

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24568008/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:45:58  来源:igfitidea点击:

Laravel : Introducing custom Classes/Libraries

phplaravellibraries

提问by Kamran Ahmed

I have just started learning Laravel and during the process, I found out that we can introduce our custom classes into Laravel using the following:

我刚刚开始学习 Laravel,在这个过程中,我发现我们可以使用以下方法将我们的自定义类引入 Laravel:

  1. Create a folder say app/MyLib
  2. Create my class inside app/MyLib, say I created MyDates
  3. Now modify the ClassLoader::addDirectoriesinside the app/start/global.phpas follows:

    ClassLoader::addDirectories(array(
        ...
        app_path().'/MyLib'
    ));
    
  4. Access MyDatesclass, however I want

  1. 创建一个文件夹说 app/MyLib
  2. 在里面创建我的类app/MyLib,比如说我创建的MyDates
  3. 现在修改ClassLoader::addDirectories里面的app/start/global.php内容如下:

    ClassLoader::addDirectories(array(
        ...
        app_path().'/MyLib'
    ));
    
  4. 访问MyDates类,但是我想要

I then came across this article Laravel 4 Application Setup: App library, Autoloading, Bindingthat uses composerto autoload the custom libraries. Now the question is, what's the best way to introduce my custom libraries in Laravel i.e. what's the recommended approad and if there are any differences between these approaches, what are those?

然后我看到了这篇文章Laravel 4 Application Setup: App library, Autoloading, Bindingthat usedcomposerto autoload the custom libraries。现在的问题是,在 Laravel 中引入我的自定义库的最佳方法是什么,即推荐的方法是什么,如果这些方法之间有任何区别,那些是什么?

回答by Sebastian Kraft

its best practice and the only way you should do it, if you modify your composer.json as follows

如果您按如下方式修改 composer.json,它的最佳实践也是您应该这样做的唯一方法

"autoload": {
    "classmap": [
        "app/commands",
        "app/controllers",
        "app/models",
        "app/database/migrations",
        "app/database/seeds",
        "app/tests/TestCase.php"
        /* HERE YOUR LIBRARY FOLDER */
        "app/MyLib",
    ]
},

EDIT:You should run after the change composer dump-autoloadto autoload your changes

编辑:您应该在更改后运行composer dump-autoload以自动加载您的更改