PHP中如何处理不同的账户类型?

发布于 2024-12-05 22:49:11 字数 404 浏览 0 评论 0原文

我有 3 个表/模型,其关系如下所示:

    Account
       |
   ----------
   |        |
 User     Company

它们全部由帐户的主键连接,并且用户和公司各自具有非常不同的方法和字段集。

假设我只知道“帐户ID”,并且我需要加载一个帐户,我假设以下是一个好的程序?

  1. 帐户模型通过 id 加载,
  2. 然后确定“帐户类型”
  3. 将用户对象或公司对象加载到帐户对象本身中。它可以像这样使用:

    $account->company->company_name();

不知怎的,这似乎不是很有效......有人可以建议更好的东西吗?

I have a 3 tables/models with the relationship illustrated below:

    Account
       |
   ----------
   |        |
 User     Company

They are all joined by the the Account's PRIMARY KEY, and the User and Company each have very different sets of methods and fields.

Assuming that I only know the "account id", and I need to load an account, I am assuming that the following is a good procedure?

  1. the Account model is loaded by id
  2. the "account type" is then determined
  3. either a User or a Company object is loaded into the Account object itself. It could be used like so:

    $account->company->company_name();

Somehow this doesn't seem very efficient...can somebody suggest something better?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云雾 2024-12-12 22:49:11

可能最好让用户和公司都扩展帐户,并且父类帐户不知道子类(只有子类应该知道父类),因此当您需要添加更多帐户子类时,不需要更改帐户中的任何内容:

    class Account {
        var $email;
        var $password;

        function load() {
            // load from db
        }
    }

    class User extends Account {
        var $first_name;
        var $last_name;

        function load() {
            parent::load();
            // load for this class
        }
    }

    class Company extends Account {
        var $company_name;

        function load() {
            parent::load();
            // load for this class
        }
    }

Probably best to have both User and Company extend Account, and with the parent class Account not knowing about the children classes (only the child classes should know about the parent class) so when you need to add more Account subclasses, you don't need to change anything in Account:

    class Account {
        var $email;
        var $password;

        function load() {
            // load from db
        }
    }

    class User extends Account {
        var $first_name;
        var $last_name;

        function load() {
            parent::load();
            // load for this class
        }
    }

    class Company extends Account {
        var $company_name;

        function load() {
            parent::load();
            // load for this class
        }
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文