在PHP中具有多继承的类的存储库+工厂模式实现?

问题描述 投票:0回答:1

这里是情况:假设我有一个User抽象类。该类扩展为EmployeeCustomer子类。

User类具有nameaddress之类的基本属性。 Employee具有附加属性sallaryCustomer具有附加属性membership_code

这些实体存储在多个表中:usersemployeescustomersusers表包含有关任何用户的基本信息。 employeescustomers表引用users表,并且每个表中都包含其他属性。

users表:

id | name       | address           | type
---+------------+-------------------+---------
1  | Employee 1 | First Address St. | Employee
2  | Customer 1 | First Address St. | Customer

employees表:

user_id | salary
--------+---------
1       | 5000

customers表:

user_id | membership_code
--------+---------
2       | 1325_5523_2351

这里是我应该如何在PHP中实现这些的想法:

abstract class User
{
    protected $id;
    protected $name;

    public static function load(int $id): User
    {
        /** @var array $data */
        $data = get_a_row_from_users_table_by($id); // this part does a query to DB

        return new $data['type']($data['id'], $data['name']);
    }

    final public function __construct($id, $name)
    {
        $this->id = $id;
        $this->name = $name;
        $this->init();
    }

    abstract protected function init();
}

class Employee extends User
{
    protected $salary;

    protected function init()
    {
        /** @var array $data */
        $data = get_a_row_from_employees_table_by($this->id); // this part does a query to DB
        $this->salary = $data['salary'];
    }
}

class Customer extends User
{
    protected $membership_code;

    protected function init()
    {
        /** @var array $data */
        $data = get_a_row_from_customers_table_by($this->id); // this part does a query to DB
        $this->salary = $data['membership_code'];
    }
}

这是控制器中的外观:

$employee = User::load(1); // return Employee type
$customer= User::load(2); // return Customer type

但是,我觉得上面的代码似乎仍然很难维护。最近,我读了一本书,讨论关于域驱动设计以及如何将持久性机制分离为存储库的书。另一方面,我还发现类型切换机制(例如,在EmployeeCustomer之间)应该在Factory中完成。

我对Repository

Factory的概念有所了解,但是我仍然无法理解如何将这些概念组合并实现为工作代码。

在这种情况下,应如何实现上述内容以在PHP中使用Repository

Factory模式?

这里是情况:假设我有一个User抽象类。该类扩展为Employee和Customer子类。 User类具有基本属性,例如名称和地址。员工有一个...

php design-patterns architecture repository-pattern factory-pattern
1个回答
0
投票

您创建User抽象基类的方法很好。您的表结构也看起来不错。

© www.soinside.com 2019 - 2024. All rights reserved.