AMP 项目使用教程
1. 项目的目录结构及介绍
AMP 项目的目录结构如下:
/amphp/amp
├── bin
├── examples
├── src
│ ├── byte-stream
│ ├── cache
│ ├── concurrent
│ ├── dns
│ ├── http
│ ├── log
│ ├── process
│ ├── redis
│ ├── socket
│ ├── sync
│ └── timer
├── tests
└── composer.json
bin
:包含项目的可执行文件。examples
:包含项目的示例代码。src
:包含项目的源代码,按模块划分。tests
:包含项目的测试代码。composer.json
:项目的依赖管理文件。
2. 项目的启动文件介绍
AMP 项目的启动文件通常位于 examples
目录下。例如,examples/http-server.php
是一个简单的 HTTP 服务器示例。
<?php
require __DIR__ . '/../vendor/autoload.php';
use Amp\Http\Server\RequestHandler\CallableRequestHandler;
use Amp\Http\Server\Response;
use Amp\Http\Server\Server;
use Amp\Http\Status;
use Amp\Socket;
Amp\Loop::run(function () {
$sockets = [
Socket\listen("0.0.0.0:1337"),
Socket\listen("[::]:1337"),
];
$server = new Server($sockets, new CallableRequestHandler(function () {
return new Response(Status::OK, [
"content-type" => "text/plain; charset=utf-8"
], "Hello, World!");
}), new Amp\Log\ConsoleFormatter(new Amp\Log\StreamHandler(new Amp\ByteStream\ResourceOutputStream(STDOUT))));
yield $server->start();
// Stop the server when SIGINT is received (this is technically optional, but it is best to call Server::stop()).
Amp\Loop::onSignal(SIGINT, function (string $watcherId) use ($server) {
Amp\Loop::cancel($watcherId);
yield $server->stop();
});
});
3. 项目的配置文件介绍
AMP 项目的配置文件主要是 composer.json
,它定义了项目的依赖和其他配置信息。
{
"name": "amphp/amp",
"description": "A non-blocking concurrency framework for PHP applications.",
"keywords": ["concurrency", "asynchronous", "non-blocking", "event-driven"],
"homepage": "https://amphp.org",
"license": "MIT",
"authors": [
{
"name": "Daniel Lowrey",
"email": "rdlowrey@php.net"
},
{
"name": "Aaron Piotrowski",
"email": "aaron@trowski.com"
}
],
"require": {
"php": ">=7.0"
},
"require-dev": {
"phpunit/phpunit": "^6.0"
},
"autoload": {
"psr-4": {
"Amp\\": "src/"
}
},
"autoload-dev": {
"psr-4": {
"Amp\\Test\\": "tests/"
}
}
}
name
:项目的名称。description
:项目的描述。keywords
:项目的关键词。homepage
:项目的主页。license
:项目的许可证。authors
:项目的作者。require
:项目的依赖。require-dev
:开发环境的依赖。autoload
:自动加载的配置。autoload-dev
:开发环境的自动加载配置。