11
建立项目过程
kuangweijian edited this page 3 years ago
1 创建项目目录
$ mkdir projectname
2 创建composer项目
$ cd projectname
$ composer init
# 输入项目命名空间,由“你的名字/项目名字”组成
Package name (<vendor>/<name>) [yourname/projectname]:(回车)
#项目描述
Description []: (回车)
#作者信息
Author [, n to skip]:(回车)
#使用composer install下载包时选择的最低稳定版本[stable, RC, beta, alpha, dev] 从左到右版本稳定性越差,回车默认选择stable
Minimum Stability []: dev
#项目类型
Package Type (e.g. library, project, metapackage, composer-plugin) []: library
#授权类型
License []:(回车)
Define your dependencies.
#是否需要依赖,如果需要按回车,如果不需要填no
Would you like to define your dependencies (require) interactively [yes]?(回车)
#如果需要依赖,输入依赖包名称
Search for a package: php
#输入依赖包版本范围
Enter the version constraint to require (or leave blank to use the latest version): >=7.4,<8.0
#如果还需要依赖,输入依赖包名称,如果不需要按回车
Search for a package:(回车)
#如果需要开发版的依赖,如果需要按回车,如不需要输入no
Would you like to define your dev dependencies (require-dev) interactively [yes]? no
#把命名空间映射到指定目录
Add PSR-4 autoload mapping? Maps namespace "Yourname\Projectname" to the entered relative path. [src/, n to skip]:(回车)
{
"name": "yourname/projectname",
"type": "library",
"require": {
"php": ">=7.4,<8.0"
},
"autoload": {
"psr-4": {
"Yourname\\Projectname\\": "src/"
}
},
"minimum-stability": "dev"
}
#是否生产composer.json
Do you confirm generation [yes]?(回车)
#是否执行composer install
Would you like to install dependencies now [yes]?(回车)
...
PSR-4 autoloading configured. Use "namespace Yourname\Projectname;" in src/
Include the Composer autoloader with: require 'vendor/autoload.php';
2 创建源文件
$ cd src
$ touch ClassName.php
ClassName.php:
namespace Yourname\Projectname; //以提示“PSR-4 autoloading configured. Use "namespace Yourname\Projectname;" in src/”为准
require '../vendor/autoload.php';
class ClassName{
public function func(){
echo "hello";
}
}
ClassName.php中的类名ClassName与文件名需一致
3 创建测试用例
$ mkdir example
$ cd example
$ touch test.php
test.php:
namespace Yourname\Projectname\Example;
require '../vendor/autoload.php';
use Yourname\Projectname\ClassName;
$obj = new ClassName;
echo $obj->func().PHP_EOL;
效果
$ php test.php
hello