更精简的构造函数和类型指定

<?php

class Person
{
    public function __construct(
        public int $age = 0,
        public string $name = ''
    ) {}
    
    public function introduceSelf(): void
    {
        echo sprintf("Hi, This is %s, I'm %d years old.", $this->name, $this->age) . PHP_EOL;
    }
}

$person = new Person(name: "church", age: 26);
$person->introduceSelf();

构造函数可以简写成这样了,用更少的代码初始化属性。
传参的时候,可以指定key,不用管顺序,随心所欲。

注解

<?php

#[Attribute]
class Route
{
    public function __construct(
        public string $path = '/',
        public array $methods = []
    ) {}
}

#[Attribute]
class RouteGroup
{
    public function __construct(
        public string $basePath = "/"
    ) {}
}

#[RouteGroup("/index")]
class IndexController
{
    #[Route("/index", methods: ["get"])]
    public function index(): void
    {
        echo "hello!world" . PHP_EOL;
    }

    #[Route("/test", methods: ["get"])]
    public function test(): void
    {   
        echo "test" . PHP_EOL;
    }
}

class Kernel
{
    protected array $routeGroup = [];

    public function handle($argv): void
    {
        $this->parseRoute();
        [,$controller, $method] = explode('/', $argv[1]);
        [$controller, $method] = $this->routeGroup['/' . $controller]['get']['/'. $method];
        call_user_func_array([new $controller, $method], []);
    }

    public function parseRoute(): void
    {
        $controller = new ReflectionClass(IndexController::class);
        $controllerAttributes = $controller->getAttributes(RouteGroup::class);

        foreach ($controllerAttributes as $controllerAttribute) {
            [$groupName] = $controllerAttribute->getArguments();
            $methods = $controller->getMethods(ReflectionMethod::IS_PUBLIC);

            foreach ($methods as $method) {
                $methodAttributes = $method->getAttributes(Route::class);

                foreach ($methodAttributes as $methodAttribute) {
                    [0 => $path, 'methods' => $routeMethods] = $methodAttribute->getArguments();

                    foreach ($routeMethods as $routeMethod) {
                        $this->routeGroup[$groupName][$routeMethod][$path] = [IndexController::class, $method->getName()];
                    }
                }
            }
        }
    }
}

$kernel = new Kernel;
$kernel->handle($argv);

//cli模式下运行 php test.php /index/index

执行

php test.php /index/test

image.png

官方文档给出的<<>>语法是错的,让我很郁闷,还是去源码中找的测试用例。

image.png

nullsafe语法糖

新增nullsafe,很方便的东西,代码又可以少写两行了。

ORM可以更愉快地玩耍了。

<?php

class User
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

class Post
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

User::find(1)?->posts()->where("id", 1)->first()?->comments();

JIT

目前为止性能最强的PHP版本诞生了,又可以省两台服务器的钱了。


church
3.6k 声望67 粉丝

引用和评论

0 条评论