问题描述
我想让 Composer 自动加载 这个包.
I want to make this package to be autoloaded by Composer.
此软件包可在 Packagist
我意识到我需要在 composer.json
中添加一些东西,并且我需要在某处有一个 autoload.php
.
I realized I need to add something to composer.json
and I need to have a autoload.php
somewhere.
应该自动加载的唯一类是 Webbot.php
.
The only class that should be autoloaded is the Webbot.php
.
谁能给我一步一步的分解来完成这个?
Can someone give me the step by step breakdown to accomplish this?
返回的 Google 搜索结果是自动加载库的说明.
Google search results returned are instructions to autoload libraries.
我需要有关如何编写可自动加载库的说明.
I need instructions on how to write autoloadable libraries.
推荐答案
首先,您需要在 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.
这篇关于如何创建一个供作曲家自动加载使用的库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!