sark9012
sark9012

Reputation: 5747

Confusion over OO approach to class

I place the following at the top of every page on my site.

require_once "classes/Session.php";

This class:

require_once 'Form.php';
require_once 'Database.php';

class Session{

public $referrer;
public $logged_in;
public $url;

public function __construct(){

    $this->startSession();

}

public function startSession(){

    session_start();

    $this->logged_in = $this->checkLogin();

    //set last page visited
    if(isset($_SESSION['url'])){
        $this->referrer = $_SESSION['url'];
    }
    else{
        $this->referrer = "/";
    }

    //sets the current URL
    $this->url = $_SESSION['url'] = $_SERVER['REQUEST_URI'];
}

}

I've changed my approach to how I handle this.

I used to put new Session at the bottom of Session.php but that isn't pure OOP?

What I don't understand is where to create the Session object so I can use it on my page?

I'm a bit confused about this but feel I'm missing something basic to just get me thinking on the right lines.

Any help would be great!

Upvotes: 0

Views: 91

Answers (1)

Tony Arra
Tony Arra

Reputation: 11109

It sounds like you're trying to make a Singleton class (a class that is only instantiated once). It's true that this is often considered non-OOP or bad-form, but common when dealing with things like database handlers. This might be helpful: Creating the Singleton design pattern in PHP5

Edit: If you don't want to use a Singleton, then you don't really need to use an object at all. Just make all the member functions and variables of Session static so that they can be called like Session::startSession(). You don't even need a constructor if you do this.

It's important to recognize when you actually NEED to use an object, and when you don't. An object is typically used when you want to have multiple instances - each with their own values. Objects can also be passed to other functions. If you don't need multiple instances or the ability to pass it as a function parameter, you just use a Static Class to encapsulate the logic. The Singleton design pattern is for cases where you still want to pass the object to methods and use it like an object, but you only want there to be one instance. You technically don't need a Singleton to do this.

Edit again again: Dependency injection is technically the best way to handle this stuff. You could pass around the Server object (or a container holding the Server object) to all your other constructors. That's the "pure" OOP method.

Upvotes: 1

Related Questions