Jump to content

Recommended Posts

Hey everyone,

 

So I'm in the process of making the jump to OOP and I decided that the best way would be to make an app, a 'to-do' that would involve various modules that I would be able to include in future projects(login system, db connection, etc). I figured that the first thing(module) I should do is the login system. After putting my thinking cap and some research I came to the conclusion that this is what I need

 

  • Check to see if the user has any sessions

-yes- then re-direct the user to a control panel page

-no-continue on to the next question

  • Did the user submit the form already?

-yes-then process the data and check it is a valid login

-no-continue

  • Then show the login form

 

To answer those questions I would need three methods(a function inside a class?), one for each question, which is the easy part. The part that is troubling me is who can I tie it all together into its final form. I also figured that it would be best if all the processing is done in a dedicated login page which call on the classes.

 

Any ways this is what I came up with.

class Membership {
    
        function  __construct() {
            session_start();
        }

        function  verifyStatus() {
            if(!empty($_SESSION['LoggedIn']) && !empty($_SESSION['Username'])){
               header("location:main.php");//admin  panel type page
            }
        }
        
         function loginCheckInDatabase($un, $pwd) {

	$query = "SELECT * FROM users WHERE username = ? AND password = ? LIMIT 1";

                $mysqli = new DbConnect();

                $mysqli->connect(); // from an .inc file "$DbInfo = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME) or die ('there was an erro....."


                //create statement object
                $stmt = $mysqli->stmt_init();

                //preapare stmt for execution
                $stmt->prepare($query);

                //bind the parameters
                $stmt->bind_param('ss',$un,md5($pwd));

                $stmt->execute();

                //reecuperate the stmt resources
                $stmt->close();

                if($stmt->num_rows==1){
                    session_start();
                    $_SESSION['status']= "verified";
                    header ("location:main.php");
                } else {
                    echo "There was an error authenticating you; loginCheckInDatabase method";// I should include a way to connect to call the next function(displayLoginForm)
                }

}

         function displayLoginForm(){
            echo "<form action='' method='post'>
                  <fieldset>
                        <label for='username'>Username:</label><input type='text' name='username' id='username' /><br />
                        <label for='password'>Password:</label><input type='password' name='password' id='password' /><br />
                        <input type='submit' name='login' id='login' value='Login' />
           </fieldset>";
        }

 

 

Now I just need to build the sequence that will bring them all together. Any help

 

 

Note: Is there some kind of book, web site that has free OOP applications that someone can study/analyze?

 

Link to comment
https://forums.phpfreaks.com/topic/208637-oop-login-system/
Share on other sites

THere are plenty of good books on the subject, and good articles on OOP for that matter, but there's also some excellent OOP Frameworks out there, which are FOSS and you can download them and study them.

 

For a start, try Zend Framework.  It has various classes and you can read the code and look at what they're doing.

 

There are also "design patterns" which are frequently used in software development.  Often frameworks implement design patterns because they are known to solve certain common design problems.  For example, the Model-View-Controller pattern is implemented in many frameworks.  The specific code is built around the basic idea of the pattern, and has been implemented in many different ways, but it's fair to say that most of the popular php Frameworks have implemented some variation of that design pattern using a number of different classes.  So in the aforementioned Zend Framework, there's a view class and a controller class you can look at right off the bat. 

 

In just taking a really cursory look at your code, you haven't really done something that's particularly oop yet.  This is self evident, because you have created a class where the objects have no properties.  At this point you might just as well have an include of the functions, because there's nothing really binding them together.  You have the right syntax, but OOP allows you to step back and think about the objects inherent in a problem.  For example, since your problem involves "users" wouldn't it make sense to have a user class?

 

Once you start thinking about what a "user" is, then you can start thinking about the properties of a user... things like username, password, permissions, etc.  When you look at other class libraries, you may find that they change your approach to the problem.

Link to comment
https://forums.phpfreaks.com/topic/208637-oop-login-system/#findComment-1090001
Share on other sites

wow, thanks for telling it like it is, appreciate it.

 

Now you have told me that I've googled some of the stuff you told me and there are a lot of articles. I've also found the zend classes you were talking about, but I think the question remains, how should I bind them together? How would you?

Link to comment
https://forums.phpfreaks.com/topic/208637-oop-login-system/#findComment-1090288
Share on other sites

One of the best ways to reduce the complexity is to break it down into discrete pieces.  In your case I would suggest a session class that handles sessions.  You can create that and unit test it.  Again you can look at the Zend framework and see what they did as well.

 

Two classes that I find very useful are a config class and a registry class.  They tend to go together.

 

A config class simply provides you a way of reading configuration items that the application will need, like databases, username/password combinations, directory paths, and anything else that you might otherwise put into a configuration file.  The purpose of this class is usually to read in all those variables and make them easily available via an object. 

 

Along with a config class, and especially in PHP, a registry class is very useful.  The idea of the registry is that it can provide handles you require, like files that you need to open for logging or output, database connections, memcache connections, and other things that are typically resources.  The registry can be used as a static class, which gets you around having to have lots of object parameters for things you commonly need.  So for example, you can use it to setup a database connection and then get access to that connection inside classes that need a database handle.

 

 


$db = registry::get('dbConnection');

 

You probably want a simple database class uses a database connection you've created and set in the registry, and lets you pass SQL and get back a result set data structure, and does error handling in a sane manner.

 

I'd create a user class, which in the MVC paradigm would be a model.  The idea of a model is that all the details of the internal data structures and how the data gets read and written to your database should be hidden inside the class.  The user class should bring everything together, so that you can __construct a user, getStatus, register, confirm, login, logout, get userName etc.

 

Link to comment
https://forums.phpfreaks.com/topic/208637-oop-login-system/#findComment-1090311
Share on other sites

My humble suggestion would be to start thinking about entities in your domain, as gizmola suggests. For example, you might have User, ToDoItem, and ToDoItemCollection as entity classes.

 

The key is to make objects very loosely coupled, and not really aware of eachother. For example, your entity objects shouldn't really know anything about the database. But you should have some kind of mapper object to persist each entity object.

 

Quick example to give an idea:

<?php
class User
{
    private $username;
    private $password;
    
    public function __construct($options = null) 
    {
        $this->populate($options);
    }
    
    //Populates the fields for this entity
    public function populate($data) 
    {
        if(is_array($data)) {
            foreach($data as $field => $val) {
                if(property_exists($field)) {
                    $this->$field = $val;
                }
            }
        }
    }
}

class UserMapper
{
    private $db_conn;
    
    public function save(User $user)
    {
        //Db access to save (insert/update) user
        return $user;
    }
    
    //Returns a user object
    public function fetchOne($username)
    {
        //Db access
        return new User($data_from_db);
    }
    
    //Returns a collection of users
    public function fetchAll()
    {
        //Db access
        return new UserCollection($data_from_db);
    }
}

 

 

Link to comment
https://forums.phpfreaks.com/topic/208637-oop-login-system/#findComment-1090327
Share on other sites

lol, I was only able to understand lie half of the code you just posted, thanx for the attempt tho.

 

If I were to make myself a login system from scratch( the learning curve too high for a starter), what pattern would you guys recommend?  the "Meditator" perhaps?

 

thanks to both of you for you time.

Link to comment
https://forums.phpfreaks.com/topic/208637-oop-login-system/#findComment-1090549
Share on other sites

what pattern would you guys recommend?  the "Meditator" perhaps?

 

I think you mean mediator, and I'm not sure I see where / how it relates to a login system.

 

Generally, applications are made of several different patterns. There is no one pattern that would be recommended for a login system.

Link to comment
https://forums.phpfreaks.com/topic/208637-oop-login-system/#findComment-1090551
Share on other sites

I think at this point, if what schlumph posted is too complicated, it might be a good idea to just sit down with his code, and the manual and go through it until you do understand it.  Write a short script that makes a new user object.  In his implementation you pass an associative array to it, and it will automatically add properties to the object that coincide with the key names of the associative array.

 

Then look at his usermapper class.  Figure out how to flesh that out so that it actually works.  UserMapper is heading towards implementation of a factory pattern in that it will manufacture a user object for you if you call the fetchOne() method.  So clearly, fetchOne() would need to be fleshed out to actually open the database, query it by username, fetch the row, create a new User and return it.

Link to comment
https://forums.phpfreaks.com/topic/208637-oop-login-system/#findComment-1091385
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.