我认为我做错了(PHP类创建和标志等)

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

目前我有一个名为user的类,我想用不同的变量创建,但我认为我做错了。

目前我有一个具有这两个功能的“单元”类

public function __construct($table, $id) {
    require_once('database.php');
    require_once('app.php');
    require_once("postmark.php");
    $this->table = $table;
    $this->valid = true;

    if(!$id) {
        $this->valid = false;
    }

    $this->populate($id);
}

public function populate($id) {
    $db = new DB();
    $q = $db->where('id', $id)->get($this->table);
    $resp = $q->fetchAll();
    foreach ($resp as $row) {
        foreach ($row as $key=>$value) {
            if(!is_int($key))
                $this->$key = html_entity_decode($value, ENT_QUOTES);
            if(is_null($value)) {
                $this->$key = null;
            }
        }
    }
    if(count($resp) <= 0) $this->valid = false;
    $verdict = !$db->error;

    $db = null;
    unset($db);

    return $verdict;    
}

然后我的“用户”类就像这样扩展它

public function __construct($id, $hash = null, $verify = null, $api = null) {
    if($api)
    $value = $this->apiToId($api);
    else if($verify)
    $value = $this->verifyToId($verify);
    else if($hash)
    $value = $this->hashToId($hash);
    else 
    $value = $id;

    parent::__construct("users", $value);
}

但我不禁想到这在设计上很差。我过去看到的一些事情是使用&符号,可能是我能做到的

$user = new User()->fromId($id);

要么

$user = new User()->withHash($hash);

而不是传递一长串的空参数。那或我可以改善继承的工作方式。虽然我想我知道我在用PHP做什么,但我真的很想找到一些正确方向的帮助。 PHP的文档非常繁琐,我从来没有在哪里看,但总能找到很酷的有用工具。我想知道如何改善这一点以获得更大的灵活性和结构。

php class oop inheritance
1个回答
4
投票
  • 移动包含到您的php文件的最顶层。任何需要条件包含的东西可能设计得很差。
  • 您的单元类应声明为抽象。这可以防止任何人实例化单位。您只能声明它的子类。
  • 与您的班级相关的任何功能都应声明为方法。因此,现在删除的答案中给出的例子是一个可怕的选择。函数alloc实际上应该是User中定义的静态函数。底部的代码片段。
  • 您的init函数应声明为static并返回该类的新实例。定义类的实例以重新实例化类只是一个坏主意。
  • 您的数据库连接应使用Singleton模式。如果需要,请查阅。

如果您想要一些帮助实现所有这些,请发布您的完整代码并对此答案发表评论。


$user  = User::initWithHash($hash);


//your create method:
/**
 * Creates and returns a new instance of the class. Useful
 * @return an instance of User.
 */
public static function create() {
    return new User();
}
© www.soinside.com 2019 - 2024. All rights reserved.