10.04.2018 Views

Doctrine_manual-1-2-en

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 3: Introduction to Connections 27<br />

Examples<br />

Example 1. Connect to database through a socket<br />

mysql://user@unix(/path/to/socket)/pear<br />

Listing<br />

3-4<br />

Example 2. Connect to database on a non standard port<br />

pgsql://user:pass@tcp(localhost:5555)/pear<br />

Listing<br />

3-5<br />

If you use, the IP address 127.0.0.1, the port parameter is ignored (default: 3306).<br />

Example 3. Connect to SQLite on a Unix machine using options<br />

sqlite:////full/unix/path/to/file.db?mode=0666<br />

Listing<br />

3-6<br />

Example 4. Connect to SQLite on a Windows machine using options<br />

sqlite:///c:/full/windows/path/to/file.db?mode=0666<br />

Listing<br />

3-7<br />

Example 5. Connect to MySQLi using SSL<br />

mysqli://user:pass@localhost/pear?key=cli<strong>en</strong>t-key.pem&cert=cli<strong>en</strong>t-cert.pem<br />

Listing<br />

3-8<br />

Op<strong>en</strong>ing New Connections<br />

Op<strong>en</strong>ing a new database connection in <strong>Doctrine</strong> is very easy. If you wish to use PDO 19 you<br />

can just initialize a new PDO object.<br />

Remember our bootstrap.php file we created in the Getting Started (page 18) chapter?<br />

Under the code where we registered the <strong>Doctrine</strong> autoloader we are going to instantiate our<br />

new connection:<br />

// bootstrap.php<br />

Listing<br />

3-9<br />

// ...<br />

$dsn = 'mysql:dbname=testdb;host=127.0.0.1';<br />

$user = 'dbuser';<br />

$password = 'dbpass';<br />

$dbh = new PDO($dsn, $user, $password);<br />

$conn = <strong>Doctrine</strong>_Manager::connection($dbh);<br />

Directly passing a PDO instance to <strong>Doctrine</strong>_Manager::connection() will not allow<br />

<strong>Doctrine</strong> to be aware of the username and password for the connection, since their is no<br />

way to retrieve it from an existing PDO instance. The username and password is required<br />

in order for <strong>Doctrine</strong> to be able to create and drop databases. To get around this you can<br />

<strong>manual</strong>ly set the username and password option directly on the $conn object.<br />

// bootstrap.php<br />

Listing<br />

3-10<br />

19. http://www.php.net/PDO<br />

----------------- Brought to you by

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!