Setting the database connection

Porte offers different methods to associate the connection and your objects.

Static level connection with default values

This is an easy way to create a connection once for all your objects. If you got a fresh non-secure MySQL installation, and if the database is not defined per record model in the "meta_table['database']" property, only the database name is required.

Command: "php samples/connection/static-with-default.php"


PorteConfig::$database = 'porte';
PorteConfig::$connection = new PorteConnection();

class User extends PorteRecord{
  public $meta_fields = array(
    'username' => array()
  );
}

$user = new User();
$user->table->update(array('drop'=>true));
$user->setUsername('my username');
$user->save();

echo 'New user with id: '.$user->getPrimaryKey()."\r\n";

// New user with id: 1
    

Static level connection with custom parameters

The "server", "port", "username", "password" and "encoding" values used in this exemple correspond to the default values.

Command: "php samples/connection/static-with-custom.php"


PorteConfig::$server='localhost';
PorteConfig::$port=3306;
PorteConfig::$username='root';
PorteConfig::$password='';
PorteConfig::$encoding='utf8';
PorteConfig::$database='porte';
PorteConfig::$connection = new PorteConnection();

class User extends PorteRecord{
  public $meta_fields = array(
    'username' => array()
  );
}

$user = new User();
$user->table->update(array('drop'=>true));
$user->setUsername('my username');
$user->save();

echo 'New user with id: '.$user->getPrimaryKey()."\r\n";

// New user with id: 1
    

Static level connection from an existing resource

If a resource already exists, you can assign it to the "connection" static property of "PorteConfig".

Command: "php samples/connection/static-from-resource.php"


$res = mysql_pconnect('localhost', 'root', '');
mysql_query('USE `porte`;',$res);
PorteConfig::$connection = new PorteConnection($res);;

class User extends PorteRecord{
  public $meta_fields = array(
    'username' => array()
  );
}

$user = new User();
$user->table->update(array('drop'=>true));
$user->setUsername('my username');
$user->save();

echo 'New user with id: '.$user->getPrimaryKey()."\r\n";

// New user with id: 1
    

Instance level connection

You may use this method in case you need to set independant connections for your objects.

Command: "php samples/connection/instance.php"


$connection = new PorteConnection(array(
  'database'=>'porte',
));;

class User extends PorteRecord{
  public $meta_fields = array(
    'username' => array()
  );
}

$user = new User();
$user->setConnection($connection);
$user->table->update(array('drop'=>true));
$user->setUsername('my username');
$user->save();

echo 'New user with id: '.$user->getPrimaryKey()."\r\n";

// New user with id: 1
    

Open Source Object Relational Mapping in PHP

Download Porte 0.2.1