PHP code example of krak / struct-gen
1. Go to this page and download the library: Download krak/struct-gen library . Choose the download type require .
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
krak / struct-gen example snippets
namespace App\Catalog;
final class Product
{
use ProductStruct;
/** @var int */
private $id;
/** @var ?string */
private $code;
/** @var Category[] */
private $categories;
}
final class Category
{
use CategoryStruct;
/** @var int */
private $id;
/** @var string */
private $name;
}
$product = new App\Catalog\Product(1, null, []);
$product->id();
$product->code();
$product = $product->withCategories([
App\Catalog\Category::fromValidatedArray(['id' => 1, 'name' => 'Nike'])
]);
$product->toArray();
// ['id' => 1, 'code' => null, [['id' => 1', 'name' => 'Nike']]]
namespace App\Catalog;
trait ProductStruct
{
/** @param Category[] $categories */
public function __construct(int $id, ?string $code, array $categories)
{
$this->id = $id;
$this->code = $code;
$this->categories = $categories;
}
public static function fromValidatedArray(array $data) : self
{
return new self($data['id'], $data['code'], \array_map(function (array $value) : Category {
return Category::fromValidatedArray($value);
}, $data['categories']));
}
public function toArray() : array
{
return ['id' => $this->id, 'code' => $this->code, 'categories' => \array_map(function (Category $value) : array {
return $value->toArray();
}, $this->categories)];
}
public function id() : int
{
return $this->id;
}
public function code() : ?string
{
return $this->code;
}
/** @return Category[] */
public function categories() : array
{
return $this->categories;
}
public function withId(int $id) : self
{
$self = clone $this;
$self->id = $id;
return $self;
}
public function withCode(?string $code) : self
{
$self = clone $this;
$self->code = $code;
return $self;
}
/** @param Category[] $categories */
public function withCategories(array $categories) : self
{
$self = clone $this;
$self->categories = $categories;
return $self;
}
}
trait CategoryStruct
{
public function __construct(int $id, string $name)
{
$this->id = $id;
$this->name = $name;
}
public static function fromValidatedArray(array $data) : self
{
return new self($data['id'], $data['name']);
}
public function toArray() : array
{
return ['id' => $this->id, 'name' => $this->name];
}
public function id() : int
{
return $this->id;
}
public function name() : string
{
return $this->name;
}
public function withId(int $id) : self
{
$self = clone $this;
$self->id = $id;
return $self;
}
public function withName(string $name) : self
{
$self = clone $this;
$self->name = $name;
return $self;
}
}
class Acme {
/** @struct-gen generate getters,withers */
use AcmeStruct;
// ...
}