它现在其实超级棒。PHP 已经走过了很长的路。现代 PHP 拥有 JIT 编译、通过 readonly 实现的不可变性、枚举、属性,以及一个媲美 TypeScript 的类型系统。
无需构建步骤。无需转译。无需打包。只需编写代码并部署。这就是每个人都忘记的超能力。
final readonly class Book
{
public function __construct(
public Status $status,
public string $title,
) {}
public function label(): string
{
match ($this->status) {
Status::Draft => 'Working on it',
Status::Published => 'Ready to read',
};
}
}Route::get('/books', function () {
Book::query()
->where('status', Status::Published)
->with('author')
->paginate();
});it('publishes a book', function () {
$book = Book::factory()->create();
$book->publish();
expect($book->status)->toBe(Status::Published);
});/**
* @return array<int, string>
*/
public function titles(): array
{
Book::all()
->filter(fn (Book $book): bool => $book->isPublished())
->map(fn (Book $book): string => $book->title)
->toArray();
}现代 PHP 不仅仅是更好。它与过去的 PHP 完全不同。
$ laravel new myapp
_ _
| | | |
| | __ _ _ __ __ ___ _____| |
| | / _` | '__/ _` \ \ / / _ \ |
| |___| (_| | | | (_| |\ V / __/ |
|______\__,_|_| \__,_| \_/ \___|_|
Creating a laravel/laravel project...
✓ Application ready in [myapp].
✓ Built with love.$ composer require laravel/sanctum
./composer.json has been updated
Running composer update laravel/sanctum
Loading composer repositories with package information
Updating dependencies
Lock file operations: install, updates, removals
- Locking laravel/sanctum (v4.0.6)
✓ Package laravel/sanctum installed successfully$ ./vendor/bin/phpstan analyse/ [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓]%
───────────────────────────────────────────────────
[OK] No errors
💡 Tip: PHPStan is at level — maximum strictness$ ./vendor/bin/pest
PEST v4.
✓ it can create a book 0.02s
✓ it can publish a book 0.01s
✓ it validates required fields 0.01s
✓ it belongs to an author 0.02s
Tests: passed ( assertions)
Duration: 0.06s$ ./vendor/bin/pint
PINT v1.
✓ app/Models/Book.php fixed
✓ app/Http/Controllers/BookController.php fixed
✓ tests/Feature/BookTest.php fixed files fixed$ ./vendor/bin/rector --dry-run/ [▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓]% files would have been changed:
↳ AddVoidReturnTypeWhereNoReturnRector
↳ ReadOnlyClassRector
↳ TypedPropertyFromStrictConstructorRector
[OK] Rector is done! files with changes
我们以前也这么想。然后我们真正去了解了一下。它类型安全。表达力强。现代化。它就是能用。看我解释一下。
一条命令。零配置。生产就绪。
安装 PHP
/bin/bash -c "$(curl -fsSL https://php.new/install/mac)"创建 Laravel 应用并运行
laravel new my-app
cd my-app
composer run dev
# 访问 http://localhost:8000安装 PHP
Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor; iex ((New-Object System.Net.WebClient).DownloadString('https://php.new/install/windows'))创建 Laravel 应用并运行
laravel new my-app
cd my-app
composer run dev
# 访问 http://localhost:8000安装 PHP
/bin/bash -c "$(curl -fsSL https://php.new/install/linux)"创建 Laravel 应用并运行
laravel new my-app
cd my-app
composer run dev
# 访问 http://localhost:8000