DrXCheng
DrXCheng

Reputation: 4132

Reuse object in PHP

I have a class which includes mysql link and others. I create an object of this class when I load the front page, but I don't want to create again when I reload the page.

mysql cannot be stored in session, so is there any other way to keep the object globally?

Upvotes: 0

Views: 283

Answers (3)

slashingweapon
slashingweapon

Reputation: 11307

Some options:

  • cache the object using the APC cache
  • serialize() the object and save it to a file. When you need it again, read the file and call unserialize()

Keep in mind that you won't be able to store resources this way. You will want to use persistent connections, as others have mentioned, for that part of your object.

Edit I thought I would expound on this a bit, since there's an obvious issue with not being able to save the mysql connection and it is getting comments.

If you want to save/restore on object that includes a database connection, you need to deal with the bits that can't be serialized. You do this by unsetting the attributes when the object is serialized, and then re-creating them when the object is unserialized. PHP provides two convenient hooks, __sleep() and __wakeup(), for exactly this purpose. You could use them like this:

class SaveableConnection {

    $connection = null;

    public function __construct() {
        $this->connect();
    }

    public function connect() {
        // read config and connect
        $this->connection = new PDO($dso);
    }

    public function __sleep() {
        // get rid of the bit that cant be saved
        unset($this->connection);
    }

    public function __wakeup() {
        // re-create the bit that wasn't save on disk
        $this->connect();
    }
}

If you are using persistent database connections, then the value of $this->connection will be optimized for you by copying the connection from the relevant cache.

You can pull this same trick for any object use that implies serialization: saving to files, caching in memcached or APC, and sessions.

Upvotes: 0

amosrivera
amosrivera

Reputation: 26514

If you are tryin got avoid several connectionsto MySQL you can use a persisten connection with mysql_pconnect.

"First, when connecting, the function would first try to find a (persistent) link that's already open with the same host, username and password. If one is found, an identifier for it will be returned instead of opening a new connection."

Upvotes: 0

Chris Trahey
Chris Trahey

Reputation: 18290

I think what you want is persistent database connections.

This requires slightly reworking your connection code, but then you don't manually manage the persistence (i.e. you don't manually put something in the session).

Make sure you read up plenty before moving forward, though. There are a lot of implications.

Upvotes: 4

Related Questions