使用 Composer 自动加载器进行自定义代码管理?

2022-01-21 00:00:00 php composer-php

我开始了一个新项目,我使用 Composer 来处理一些依赖项,以及它们的自动加载.

I've started a new project, where I use Composer to handle some dependencies, as well as their auto-loading.

我只将 composer.json 文件保存在 VCS 中,而不是整个供应商目录,所以我不想开始在其中添加我的代码.

I only keep the composer.json file in the VCS, instead of the entire vendor directory, so I don't want to start adding my code in there.

我应该如何处理我自己的项目特定代码,以便它也自动加载?

How should I handle my own project specific code, so that it auto loads as well?

推荐答案

这个其实很简单.从存储库中排除供应商目录是正确的方法.您的代码应存储在单独的位置(如 src).

This is actually very simple. Excluding vendors directory from your repository is the right approach. Your code should be stored in a separate place (like src).

使用 autoload 属性使作曲家识别您的命名空间:

Use the autoload property to make that composer recognizes your namespace(s):

{
    "autoload": {
        "psr-4": {
            "Acme\": "src/"
        }
    }
}

假设你有遵循 psr-4 标准的类名,它应该可以工作.下面是一些类名及其在文件系统上的位置的示例:

Assuming you have class names following the psr-4 standard, it should work. Below some example of class names and their locations on the file system:

  • AcmeCommandHelloCommand -> src/Command/HelloCommand.php
  • AcmeFormTypeEmployeeType -> src/Form/Type/EmployeeType.php

记得为每个类定义一个命名空间.这是 AcmeCommandHelloCommand 的示例:

Remember to define a namespace for each class. Here's an example of AcmeCommandHelloCommand:

<?php

namespace AcmeCommand;

class HelloCommand
{
}

不要忘记在您的 PHP 控制器中包含自动加载器:

Don't forget to include the autoloader in your PHP controllers:

<?php

require 'vendor/autoload.php';

阅读更多关于 PSR-4PHP 框架互操作性组标准.

请注意,如果您编辑 composer.json,则需要运行 install、update 或 dump-autoload 刷新自动加载器类路径.

Note that if you edit composer.json, you need to either run install, update or dump-autoload to refresh the autoloader class paths.

相关文章