composer实现自动加载

1.创建项目目录[project]

2.在目录下新建composer.json文件

1
2
3
{

}

3.打开控制台,进入项目目录,执行composer命令:

1
composer install

4.运行后生成composer文件目录,目录结构如下:

[project]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
- Vendor

- composer

- autoload_classmap.php

- autoload_namespaces.php

- autoload_psr4.php

- autoload_real.php

- autoload_static.php

ClassLoader.php

installed.json

LICENSE

- autoload.php

- composer.json

5.在composer.json文件中新增代码

1
2
3
4
5
6
7
8
{
"autoload": {
"psr-4": {
"DesignPatterns\\" : "DesignPatterns"
}
}
}
# DesignPatterns\\代表命名空间,DesignPatterns代表目录名称,两个名称可不一样

6.新建目录DesignPatterns,创建php文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<?php
namespace DesignPatterns\Structural\Decorator;

class ExtraBed extends BookingDecorator
{
private const PRICE = 30;

public function calculatePrice(): int
{
return $this->booking->calculatePrice() + self::PRICE;
}

public function getDescription(): string
{
return $this->booking->getDescription() . ' with extra bed';
}
}

7.在项目下创建目录web,新建入口文件index.php

1
2
3
4
5
6
7
8
9
10
11
<?php
use DesignPatterns\Structural\Decorator\DoubleRoomBooking;
use DesignPatterns\Structural\Decorator\WiFi;
use DesignPatterns\Structural\Decorator\ExtraBed;

require '../vendor/autoload.php'; //引入自动加载文件

$booking = new DoubleRoomBooking();
echo $booking->calculatePrice();
echo '<br>';
echo $booking->getDescription();

8.执行composer命令,使修改后的comoser文件生效

1
composer dump-autoload