创建项目

  1. 创建一个项目test,目录结构为:

image.png

引入 Composer

使用 composer init 命令创建 composer.json 文件

**

  1. $ composer init
  2. Welcome to the Composer config generator
  3. This command will guide you through creating your composer.json config.
  4. Package name (<vendor>/<name>) [asus/test]: king/testproject
  5. Description []: This is a test project
  6. Author [yangyi <2497471389@qq.com>, n to skip]:
  7. Minimum Stability []:
  8. Package Type (e.g. library, project, metapackage, composer-plugin) []: project
  9. License []: MIT
  10. Define your dependencies.
  11. Would you like to define your dependencies (require) interactively [yes]? n
  12. Would you like to define your dev dependencies (require-dev) interactively [yes]? n
  13. {
  14. "name": "king/testproject",
  15. "description": "This is a test project",
  16. "type": "project",
  17. "license": "MIT",
  18. "authors": [
  19. {
  20. "name": "yangyi",
  21. "email": "2497471389@qq.com"
  22. }
  23. ],
  24. "require": {}
  25. }
  26. Do you confirm generation [yes]? yes

在 composer.json 文件中加入 psr-4

**

  1. {
  2. "name": "yangyi/laravel-teach",
  3. "description": "This is a yangyi project",
  4. "type": "library",
  5. "license": "MIT",
  6. "authors": [
  7. {
  8. "name": "yangyi",
  9. "email": "2497471389@qq.com"
  10. }
  11. ],
  12. "autoload":{
  13. "psr-4":{
  14. "yangyi\\app\\":"./src/"
  15. }
  16. },
  17. "require": {}
  18. }

注意:yangyi\app 代表命名空间,./src/ 代表对应的目录

运行composer更新命令,它会把我们需要的文件都自动下载到 vendor 目录下

  1. composer update

现在的目录结构
image.png

在 src 下建立一个文件 ./src/database/Mysql.php

<?php

namespace yangyi\app\database;

class Mysql{
    public function index(){
        return 'This is a mysql';
    }
}

在index.php 中 引入 ./vendor/autoload.php 就可以了

**

<?php
require './vendor/autoload.php';

use yangyi\app\database\Mysql;

$mysql = new Mysql();

echo $mysql->index();

测试输出

This is a mysql