php-strict/struct

PHP 复合类型的实现。

v1.0.0 2019-03-26 06:05 UTC

This package is auto-updated.

Last update: 2024-09-16 16:40:53 UTC


README

Software License Build Status codecov Codacy Badge

PHP 复合类型的实现。

包含从关联数组、JSON字符串或另一个Struct创建结构体的方法,有/无类型转换。

要求

  • PHP >= 7.1

安装

使用 Composer 安装

composer require php-strict/struct

用法

通过扩展 Struct 类定义自己的复合类型

use PhpStrict\Struct\Struct

class Book extends Struct
{
    /**
     * @var string
     */
    public $author = '';
    
    /**
     * @var string
     */
    public $title = '';
    
    /**
     * @var string
     */
    public $isbn = '';
    
    /**
     * @var int
     */
    public $pages = 0;
    
    /**
     * @var bool
     */
    public $publicated = false;
    
    /**
     * @var array
     */
    public $tags = [];
}

现在您可以填充结构体中的数据

//book with classic assign data to class fields
$book1 = new Book();
$book1->author = 'Author Name';
$book1->title = 'Book title 1';
$book1->isbn = '000-0-000-00000-0';
$book1->pages = 240;
$book1->publicated = true;
$book1->tags = ['fantastic', 'space', 'detective'];

//another book with data through array
$book2 = new Book([
    'author' => 'Author Name',
    'title' => 'Book title 2',
    'isbn' => '000-0-000-00000-0',
    'pages' => 156,
    'publicated' => true,
    'tags' => ['drama', 'nature'],
]);

//another book with data through JSON
$json = '{"author":"Author Name","title":"Book title 3","isbn":"000-0-000-00000-0","pages":156,"publicated":true,"tags":["comedy","city"]}';
$book3 = new Book($json);

//book, based on existing book
$book4 = new Book($book1);
$book4->title = 'Book title 4';

查看示例目录。

测试

要执行测试套件,您需要 Codeception

vendor\bin\codecept run