开发者

crossing over to php oop

so far the syntax is not the problem but my question is more about better understanding OOP

I am creating a class called "user" which should describe a user. typically such class would set user variables and retrieve them

would that class have a method for signingup a new user as well? how about login?

if not ..how would I structure it?

should "signing up" be another class? in which case wouldn't the resulting object be a "user"

same goes for the a l开发者_StackOverflowogin class...

sorry for the novis question....just trying to wrap my head around OOP.

thanks for the help :)


Classes do not necessarily represent an entity from your experience. Sometimes they represent a concept:

  • Registering a user is actually the job of the user management. Consider a class that represents the user management.
  • Logging in is the job of the authentication component. Consider a class that represents the authentication component.

Theses are just some examples and they probably do not tell you the reasons why it is often done that way. For that I suggest literature about object oriented programming. That literature should tell you about separation of concerns, lose coupling, open/close principle, programming against interfaces, how to transform requirements into classes.


Most PHP OOP applications would use a model-view-controller (MVC) approach to solve this, with your user class being the 'model' and a 'controller' class providing business logic that interacts with your user class, like 'signup' or 'login'. The 'view' part refers to the presentation code (a mix of PHP / HTML) that gets output to the browser.

A controller approach would look something like this:

class UserController {

    public function signup($userDetails) {
        // create a new user
        $user = new User();
        $user->name = $userDetails['name'];
        $user->username = $userDetails['username'];
        $user->password = $userDetails['password'];
        $user->save(); // Save to database, for example
    }

    public function login($username, $password) {
        // check the user exists and log them in
        $user = new User();

        // query database for a user with these credentials, for example
        if($id = $user->find($username, $password)) {
            $_SESSION['user'] = $id; // Save the ID to the session for future use
            return true;
        }

        return false;
    }

}

This is just a really basic example, but generally you don't want to mix your application logic (actions such as login or signup) with your domain logic (which should just concern managing your data).

A good article on MVC in PHP can be found here: http://oreilly.com/php/archive/mvc-intro.html

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜