现代 PHP 工程
命名空间、类型声明、DI、PSR 标准。
30 分钟
现代 PHP 工程
PHP 8+ 带来 命名空间、严格类型、构造器属性提升与只读属性。本课还介绍依赖注入与 PSR 标准。前置 php-essentials;路径 /roadmaps/php。
学习目标
- 用命名空间组织代码并配合 Composer 自动加载
- 编写带类型声明的可维护函数与类
- 理解 DI 容器与 PSR-4 / PSR-12 的意义
命名空间与类型
<?php
declare(strict_types=1);
namespace App\Service;
final readonly class LessonDto {
public function __construct(
public string $slug,
public string $title,
public int $order,
) {}
}
function formatLesson(LessonDto $lesson): string {
return sprintf('#%d %s (%s)', $lesson->order, $lesson->title, $lesson->slug);
}
declare(strict_types=1) 让类型检查更严格;readonly 属性创建后不可变。
Composer 自动加载
composer.json:
{
"autoload": {
"psr-4": {
"App\\": "src/"
}
}
}
运行 composer dump-autoload 后,App\Service\LessonDto 自动映射到 src/Service/LessonDto.php。
依赖注入
namespace App\Service;
class LessonService {
public function __construct(
private LessonRepository $repo,
) {}
public function get(string $slug): ?LessonDto {
$row = $this->repo->findBySlug($slug);
return $row ? new LessonDto($row['slug'], $row['title'], (int) $row['order']) : null;
}
}
构造函数注入便于测试;Laravel、Symfony 内置 DI 容器。团队遵循 PSR-4(自动加载)与 PSR-12(代码风格)。
练习
- 创建
App\Repository\LessonRepository接口与实现 - 配置 PSR-4 自动加载并
composer dump-autoload
小结
命名空间 + 类型 + DI + PSR = 可协作的现代 PHP 项目。 下一课数据库与 ORM。
加载本节练习…