且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何创建一个供作曲家自动加载使用的库?

更新时间:2023-09-28 07:53:09

首先,您需要在 PSR-0 或 PSR-4 中构建您的包.我还没有开始使用 PSR-4,因为它刚刚被接受为标准.Composer 仍将在很长一段时间内支持 PSR-0.

First, you need to have your package structured in either PSR-0 or PSR-4. I haven't started using PSR-4 yet as it has only just been accepted as a standard. Composer will still support PSR-0 for a long time to come.

这意味着您必须遵守以下规则:

This means that you MUST follow these rules:

  • 完全限定的命名空间和类必须具有以下内容结构 <Vendor Name>(<Namespace>)*<Class Name>
  • 每个命名空间都必须有一个***命名空间(供应商名称").
  • 每个命名空间都可以拥有任意数量的子命名空间.
  • 每个命名空间分隔符都转换为 DIRECTORY_SEPARATOR 时从文件系统加载.
  • CLASS NAME 中的每个 _ 字符都转换为DIRECTORY_SEPARATOR._ 字符在命名空间.
  • 完全限定的命名空间和类以 .php 为后缀时从文件系统加载.
  • 供应商名称、命名空间和类名中的字母字符可以是小写和大写的任意组合.

这里有完整的FIG指南

这意味着你的包应该按如下方式在你的 github 存储库中布局:

This would mean that your package should be laid out in your github repository as follows:

-src
    -Simkimsia
        -Webbot
            -Webbot.php
-composer.json
-license.md
-{any other base level files}

Webbot.php 将位于命名空间中:SimkimsiaWebbot 由目录结构指定.

Webbot.php would be in the namespace : SimkimsiaWebbot as dicated by the directory structure.

然后...由于这是一个 github 包,您可以使用 repositories 属性将它添加到您的项目 composer.json.

Then... As this is a github package, you can add it to your projects composer.json using the repositories property.

{
    "name" : 'test',
    "description" : 'Test',
    "keywords" : ['test'],
    "repositories" : [
    {
        "type": "vcs",
        "url": "https://github.com/simkimsia/webbot.git"
    }
    ],
    "require" : {
        "simkimsia/webbot" : "dev-master"
    }
}

该包将从 Composers 自动加载中获得,并且可以实例化为:

The package will be available from Composers autoload and can be instantiated as :

$webbot = new SimkimsiaWebbotWebbot();

注意:运行 composer install 后,Composers autoload.php 将可用:

Note: Composers autoload.php will be available in once you have run composer install:

/vendor/composer/autoload.php

只需在 PHP 脚本的开头包含此文件,您的类就可用了.

Just include this file at the start of your PHP script and your classes will be available.