Jump to content

PHP OO Beginner:Whether to create a new class or just a new function?


codeboyuk

Recommended Posts

Hi

 

I am a newbie to PHP OO.

 

I have successfully built a class called login. Unsurprisingly this deals with the logic of logging in a user.

However, I am now on with the logout logic, but am unsure where the best place to include this code would be.

I was initially going to just add a new function to the login class (which I guess should also be referred to as the base class).But then I read about class inheritance, and wondered whether it would make better practice to extend the login class to cover a logout class i.e: 'class logout extends login'.

 

Also, my base class does not use the setter or getter methods. It just didn't need them as far as I could see (I basically just modified the original procedural script - transferring the logic to a seperate class away from the content HTML/CSS).

I suppose what I want to know is whether or not the setter and getter approach is a necessity for all objects, or do I just use it as and when I think I need them?

 

Finally. If I was to extend the login class e.g. 'class logout extends login', would I need to instantiate the logout class or the login class, or both? (if I wanted to use the functions/variables contained in them).

Currently I have adopted the approach of instantiating the class at the bottom of the class script (rather than instantiating it within a separate HTML file for example).

 

These are probably stupid questions! So I apologise!

 

I attach the class for you to look at at. I appreciate that it is quite simplistic!

 

 
error_reporting (E_ALL);
class login {

 function admin_login() {	
 $message = NULL;
    if (isset($_POST['submit'])) {
    require_once ('../includes/connections/mysql_connect.php'); 
 if (empty($_POST['username'])) {
	$u = FALSE;
	$message .= '<p> Please enter your username </p>';
} else {
	$u = escape_data($_POST['username']);
}
if (empty($_POST['password'])) {
	$p = FALSE;
	$message .= '<p>You forgot to enter your password </p>';
} else {
	$p = escape_data($_POST['password']);
        }

if ($u && $p) { // If everything's OK.
	$query = "SELECT * FROM admin WHERE username= ('$u') AND password=('$p')";		//changed the table name from 'customer' to 'customers' to fit in with new database structure.
	$result = @mysqli_query($GLOBALS["___mysqli_ston"], $query);
	//echo $result;
      //var_dump "$result";
       $row = mysqli_fetch_array($result,  MYSQLI_BOTH); 
	if ($row) { 
	session_start();		
       $_SESSION['admin_id'] = $row[0];
       header ("Location:  http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/admin_index.php");  

	} else {
		$message = '<p> The username and password combination are incorrect.</p>'; 
	}
	((is_null($___mysqli_res = mysqli_close($GLOBALS["___mysqli_ston"]))) ? false : $___mysqli_res);
       } else {
    $message .= '<p>Please try again.</p>';		
  }

}
if (isset($message)) {
echo '<font color="red">', $message, '</font>';
         }
     }//Closing function
  } //Closing class tag
$login = new login(); //***Instantiating the login class. If I extend the class would I still call this from here?

/*Extended login class starts here*/
class logout extends login {
//Code would go here	
}
$login = new login(); //***Or would I move it down here? Or do I need to instantiate the logout class instead??

 

 

Thanks

Will

Link to comment
Share on other sites

Just to let you know that I have opted for adding a new function to the existing class. I've also changed the class name to 'user'.

So basically the class now contains two functions: admin_login and logout....I think 'user' makes more sense as the parent object.

I've built it in such a way that when the user clicks the logout link, it directs him to logout.php, which immediately includes the site classes file and then calls the logout function as so: $user->logout();

 

Its working, although would still be interested to get some feedback on my previous post.

 

Also, what is the difference between the following:

user::admin_login($user);

and,

$user->admin_login();

 

They both appear to do the same thing or am I missing something?

 

One final question: When the user clicks the link, I am using the traditional '<a href> filename.php </a>' approach. Is there a way of cutting that stage out altogether i.e. by using a variable instead: such as '<a href> $user->logout(); </a>'

 

Thanks

Link to comment
Share on other sites

Here's the way I would approach it...

 

I would modify your class so it covers a wider scope of functionality. Rather than calling it "login" (one would assume that the class would only contain functionality related to logging in the user, which is probably very limited) I would call it "Auth" (for "authorization") and have it handle any tasks related to authorization: login/logout/permissions/checking if user is logged in. I try to avoid extending classes unless it is really necessary or makes sense. I don't think making a class for "logout" makes much sense because it would really only hold one function.

 

Using setters/getters is only necessary if you want to store variables within your object. If you don't have any data to store, there is little point in creating getters/setters. Also, keep in mind that getters/setters are only necessary if you want things "outside" of your class to have access to the data within the class. If you use a variable within the class and there is no need to access that variable outside the class, there is no need for a getter/setter.

Link to comment
Share on other sites

regarding "::"

I'm not really familiar with it, but this is what I found with a quick Google search:

 

"The double colon's allow you to reference a function of a class without actually creating an instance of the class. The syntax is:

 

classname::functioname();

 

Note, however, that if any references in the function are made to $this, the call will fail--you will need to create an instance of the class to use the function. Hope that helps.

from http://www.phpbuilder.com/board/showthread.php?t=10149409

 

One final question: When the user clicks the link, I am using the traditional '<a href> filename.php </a>' approach. Is there a way of cutting that stage out altogether i.e. by using a variable instead: such as '<a href> $user->logout(); </a>'

Not really... You could probably use AJAX so you didn't have an page you linked to, but that Javascript would still have to call a PHP file to log the user out.

 

I suppose you could always set the link to "?logout", which would call the page the user is currently on with the $logout variable set within the URL. You could then check if the logout variable is set (using $_GET) and log the user out if it appears...

 

For example:

 

<?php if(isset($_GET['logout'])) { $user->logout(); } ?>

 

That code snippet would have to be placed in all your files though -- wherever the user has the opportunity to log out. Obviously the $user variable would have to be created before the if statement.

Link to comment
Share on other sites

Thanks for your advice Ben.

I'm just feeling my way around with what is possible and what isn't possible with the OO approach.

You mentioned that getters and setters should only be used if data is needed to be stored within the object.

With a login process, user data entered into the form fields is stored within the relevant $_POST variables/attributes (for reconciling to the database). It is (technically speaking) taken from one file, and then stored within the class object for processing.

The session id will also need to be set within the class object and then used by files outside of the class object.

Does this mean that I should have used the getter/setter approach here? Clearly it worked without me using it - but I'd rather be using a conventional approach if I should be.

 

Thanks for the tip about the class name! 'Auth' seems very appropriate for the functions that it will carry out.

 

Thanks

Will

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  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.

Loading...
×
×
  • Create New...