Writing a model for the user (php)

I have a user model that has many properties such as first_name, last_name, email, address, address2 ... etc.

I am writing a php class to manage these properties, but it looks like I am writing a lot of the same code. (Getters and seters). Should I use magic methods to control this? This is similar to the idea of ​​OK, but I do not want the wrong properties to be set. Any ideas?

<?php
class User
{
    private $username;
    private $email
    private $first_name;
    private $last_name;
    private $address;
    private $address2;

    function __construct()
    {

    }

        function getUsername()
        {
            return $this->username
        }


        function setUsername($username)
        {
            $this->username = $username;
        }

        ...
}
?>
+3
source share
2 answers

If you do not perform input validation, in my opinion there is no point in using getters / setters.

Make properties publicand override getters / setters for invalid properties using magic methods:

class User
{
    public $username;
    public $email;
    public $first_name;
    public $last_name;
    public $address;
    public $address2;

    public function __get($var) {
        throw new Exception("Invalid property $var");
    }

    public function __set($var, $value) {
        $this->__get($var);
    }

}

$user = new User;
$user->username = 'foo';  // works
$user->foo = 'bar';       // errors
0
source

-, ?

/, __get __set.

"" (?), , :

function __set($key, $value) {
    $whitelist = array("firstname", "lastname", ..);
    if(!in_array($key, $whitelist))
        throw new Exception("Invalid property");
}
0

All Articles