angrybytes/domainobject

一个简单的DomainObject实现,提供模拟属性

3.0.0 2023-12-01 07:41 UTC

This package is auto-updated.

Last update: 2024-08-30 01:17:29 UTC


README

这是一个简单的类,表示扩展它的类是DomainObject。在更实际的意义上,它提供了一种PHP中缺乏的属性实现。

为什么

我们相信使用简单的PHP对象(POPO)来建模您的领域。这些对象应该只持有它们的核心值以外的逻辑。DomainObject应该与您的论域中的实体有直接的联系。

这个类以通用方式帮助您实现这一点。它有一些优点,例如支持通过函数和对象属性表示法访问属性。但主要的是,它是一个强烈的信号,表明扩展它的类实际上是一个DomainObject。

为什么不简单地依赖公共变量呢?

使用简单的变量如

class Person
{
    public $name;
}

对于大多数简单的属性来说效果相当好。

想象一下以下情况

class Person
{
    public $firstName;

    public $lastName;

    public function getFullName()
    {
        return $this->firstName . ' ' . $this->lastName;
    }
}

为了获取一个人的全名(姓氏+名字),你需要编写一个方法。现在你必须在你的API中混合属性和方法。这并不非常一致,也不太灵活。

示例

<?php

use Angrybytes\DomainObject;

use \InvalidArgumentException;

class BlogPost extends DomainObject
{
    private $title;

    private $contents;

    public function getTitle()
    {
        return $this->title;
    }

    public function setTitle($title)
    {
        // You can do simple sanity checks in your setters
        if (strlen($title) < 3) {
            throw new InvalidArgumentException('Title should be 3 or more characters long');
        }

        $this->title = $title;

        return $this;
    }

    public function getContents()
    {
        return $this->contents;
    }

    public function setContents($contents)
    {
        $this->contents = $contents;

        return $this;
    }
}

使用这个,你可以

<?php

$post = new BlogPost;

// Set properties
$post
    ->setTitle('This is the title for my blog post')
    ->setContents('foo');

// Retrieve properties using property notation
echo $post->title;
echo $post->contents;

// Retrieve data in array form for easy serialization
$json = json_encode(
    $post->toArray()
);