1. 安装composer(windos system)
指南:https://learnku.com/docs/composer/2018
2. 使用PSR-4基于命名空间的自动加载
参考文章:https://www.php.cn/php-weizijiaocheng-362938.html(php中文网)
composer.json定义
{
"require": {
"monolog/monolog": "1.0.*" //格式:作者或商业机构名/库名
},
"autoload": { // 自动加载
"psr-4": {
"Admin\\": "admin/", //定义多个自动加载命名空间与目录的映射
"Extend\\": "extend/"
}
}
}
index.php
// 装载自动加载函数
require __DIR__.'/../vendor/autoload.php';
use Admin\test;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$test = new test();
$test->sayHi();
$log = new Logger('name');
$log->pushHandler(new StreamHandler('app.log', Monolog\Logger::WARNING));
$log->addWarning('aaaaaaa');
admin目录下的test.php
<?php
namespace Admin;
class test
{
public function sayHi()
{
echo 'hi';
}
}
3. 必须的composer.json配置以及优化
指南:https://learnku.com/docs/composer/2018
{
"name": "xxl/hello-world",
"description": "a study composer test",
"version": "1.0.0",
"type": "project",
"keywords": [
"study",
"composer_test"
],
"homepage": "http://xxx",
"readme": "./README.md",
"time": "2019-08-08",
"license": "MIT",
"authors": [
{
"name": "xxl",
"email": "xxx@qq.com",
"homepage": "http://xxx",
"role": "Developer"
}
],
"support": {},
"require": {
"php": "^5.5 || ^7.0",
"monolog/monolog": "1.0.*"
},
"repositories": [
{
"type": "vcs",
"url": "github地址"
}
],
"autoload": {
"psr-4": {
"Admin\\": "admin/",
"Extend\\": "extend/"
},
"classmap": ["src/", "lib/", "Something.php"], //您可以通过生成类映射来自动加载不遵循 PSR-0/4 的库。通过设定要搜索类的所有目录或文件来进行配置
"files": ["src/MyLibrary/functions.php"], //如果你想在每个请求中引入某个文件,那么你可以使用 files 自动加载机制。这有利于加载包中无法自动加载的 php 函数
"exclude-from-classmap": ["/Tests/", "/test/", "/tests/"], //我们可以使用 exclude-from-classmap 从类库映射中排查某些文件或文件夹。这很方便我们在生成环境中排查测试类,例如,在构建加载的时候自动加载器会排除这些类
},
"autoload-dev": { //个节点允许为开发阶段自定义加载规则,运行测试套件所需的类不应包含在主自动加载规则中,以避免在生产中污染自动加载器以及其他人将您的包用作依赖项。因此,最好使用专用路径进行单元测试,并将其添加到 autoload-dev 部分
"psr-4": { "MyLibrary\\Tests\\": "tests/" }
},
"config": [],
"extra": []
}