0

我已经开始学习 OOP 并且我已经建立了一个名为 accountactions 的类,我想知道我是否写得很好。

该类在文件中:accountactions.class.php。

<?php

class accountactions(){

    public function register($login, $password, $email){

        //Zapisujemy dane wysłane formularzem
        $this->username = mysql_real_escape_string($login);
        $this->password = mysql_real_escape_string($password);
        $this->email = mysql_real_escape_string($email);

        //Hash password
        $this->password = md5(sha1($this->password));

        $db->simplequery("INSERT INTO radio_users(id, username, password, email) VALUES('', '$this->username', '$this->password', '$this->email')");

    }


}

?>

register.php 文件:

<?php

    require_once("accountactions.class.php");

    $account = new accountactions();

    $account->register('samplelogin', 'samplepassword', 'sample@email');

?>

我对这个片段有一些问题:

$db->simplequery("INSERT INTO radio_users(id, username, password, email) VALUES('', '$this->username', '$this->password', '$this->email')");

如何将我的数据库类加入我的帐户类?

我想保留一个模型,我可以在其中执行以下操作:

$account->register('$_POST['login']', '$_POST['password']', '$_POST['email']');

除非有更好的方法来做到这一点。

我是 OOP 的新手,所以任何提示和指南都值得赞赏。

4

1 回答 1

1

这段代码主要是好的,但也有一些我认为不好的地方。首先,我认为您应该遵循一些命名约定,因为 accountactions 是一个错误的类名。对于 OOP,我认为您应该使用驼峰式的一些变体(因此 accountActions 或 AccountActions - 我建议您使用后者)。然后,类名后面不应该有括号。我还建议您将每个大括号放在单独的行中,但这取决于您的个人喜好。然后,你的第一条评论是波兰语——我建议你总是用英文写所有评论、变量名等,因为每个人都会理解它。然后在 register 方法中,您将变量分配给类的属性,但您之前没有声明它们(或者至少您没有在代码中向我们展示它)。同样在插入查询中你' 重新尝试将 emtpy 字符串 '' 插入 id 字段(我假设它是唯一的、非空的无符号整数,带有 auto_increment - 如果是,则不应将其包含在查询中)。我会这样写你的代码:

class AccountActions
{
    protected $Username;
    protected $Password;
    protected $Email;
    protected $DB;

    public function __construct()
    {
        $this->DB = //instantiate your database driver of choice here, e.g. mysqli
    }

    public function register($Username, $Password, $Email)
    {
        //We escape the provided values and populate the object's properties with them
        $this->Username = mysql_real_escape_string($Login);
        $this->Password = mysql_real_escape_string($Password);
        $this->Email = mysql_real_escape_string($Email);
        //Hash password
        $this->Password = md5(sha1($this->Password));
        $Query = "INSERT INTO radio_users(username, password, email) 
                  VALUES('$this->Username', '$this->Password', '$this->Email')";
        $this->DB->simplequery($Query);    
    }
}

如何将我的数据库类加入我的帐户类?

不确定你在这里的意思,但是如果你想访问你的类中的一些数据库驱动程序,你应该添加一个属性来存储数据库驱动程序并在构造函数中实例化它(或者你可能有一个静态属性来保存数据库驱动程序)。

也不确定你在标题问题中的意思 - 如果你想使用内部类(在另一个类中声明的类) - 它们在 PHP 中不可用。

我还鼓励你在学习了基本的 OOP 之后再学习一些 PHP 框架——Zend 框架是我的最爱。

于 2012-12-27T19:28:52.643 回答