Databse connection: Setting the database connection

Database connection is usually defined on Porte construction. The Porte constructor may loaded with an array of connection settings or a database connection resource (or an object depending on the database driver).

Configuration properties relevant to the connection

Singleton pattern: storing porte as a static variable

This is an easy way to create a connection once and for all with having to directly associate your record objects with a connection. Note, the singleton strategy prevent your from working with multiple instance of porte at the same time.

Defining connection attributes

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

Porte::$porte = new Porte(array(
	'host' => '127.0.0.1',
	'port' => 3306,
	'username' => 'root',
	'password' => '',
	'encoding' => 'utf8',
	'database' => 'porte',
));

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

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

// Test idenfier of our new user
assert( 1 === $user->getIdentifier() );

Defining an existing database resource

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

$res = mysql_pconnect('127.0.0.1', '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();

// Test idenfier of our new user
assert( 1 === $user->getIdentifier() );

Instance connection

The recommanded way of using porte is by keeping a reference of porte and working with it. It is a cleaner approach, since you can instanciate multiple instance of Porte all independant of each other. Pop and Padrino will easily provide you access to Porte if you use them.

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

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

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

// Test idenfier of our new user
assert( 1 === $user->getIdentifier() );