conn-mgt.xml 10.9 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
<chapter id="connection-management">
  <title>Connection Management</title>
  <sect1 id="dsn">
    <title>DSN, the Data Source Name</title>
    <para>
      In order to connect to a database through Doctrine, you have to create a
      valid DSN - data source name.
    </para>
    <para>
      Doctrine supports both PEAR DB/MDB2 like data source names as well as PDO
      style data source names. The following section deals with PEAR like data
      source names. If you need more info about the PDO-style data source names
      see <ulink
      url="http://www.php.net/manual/en/function.PDO-construct.php">http://www.php.net/manual/en/function.PDO-construct.php.</ulink>
    </para>
    <para>
      The DSN consists in the following parts:
    </para>
    <variablelist>
      <title>DSN components</title>
      <varlistentry>
        <term>phptype</term>
        <listitem>
          Database backend used in PHP (i.e. mysql , pgsql etc.) 
        </listitem>
      </varlistentry>
      <varlistentry>
        <term>dbsyntax</term>
        <listitem>
          Database used with regards to SQL syntax etc.
        </listitem>
      </varlistentry>
      <varlistentry>
        <term>protocol</term>
        <listitem>
          Communication protocol to use ( i.e. tcp, unix etc.)
        </listitem>
      </varlistentry>
      <varlistentry>
        <term>hostspec</term>
        <listitem>
          Host specification (hostname[:port])
        </listitem>
      </varlistentry>
      <varlistentry>
        <term>database</term>
        <listitem>
          Database to use on the DBMS server
        </listitem>
      </varlistentry>
      <varlistentry>
        <term>username</term>
        <listitem>
          User name for login
        </listitem>
      </varlistentry>
      <varlistentry>
        <term>password</term>
        <listitem>
          Password for login
        </listitem>
      </varlistentry>
      <varlistentry>
        <term>proto_opts</term>
        <listitem>
          Maybe used with protocol
        </listitem>
      </varlistentry>
      <varlistentry>
        <term>option</term>
        <listitem>
          option: Additional connection options in URI query string format. options get separated by &amp;. The Following table shows a non complete list of options:
        </listitem>
      </varlistentry>
    </variablelist>

    <variablelist>
      <title>List of Options</title>
      <varlistentry>
        <term>name</term>
        <listitem>
          Some backends support setting the client charset.
        </listitem>
      </varlistentry>
      <varlistentry>
        <term>new_link</term>
        <listitem>
          Some RDBMS do not create new connections when connecting to the same
          host multiple times. This option will attempt to force a new
          connection
        </listitem>
      </varlistentry>
    </variablelist>

    <para>
      The DSN can either be provided as an associative array or as a string. The
      string format of the supplied DSN is in its fullest form:
    </para>
    <programlisting>
phptype(dbsyntax)://username:password@protocol+hostspec/database?option=value
    </programlisting>


    <para>
      Most variations are allowed:
    </para>
    <programlisting>
  phptype://username:password@protocol+hostspec:110//usr/db_file.db
  phptype://username:password@hostspec/database
  phptype://username:password@hostspec
  phptype://username@hostspec
  phptype://hostspec/database
  phptype://hostspec
  phptype:///database
  phptype:///database?option=value&amp;anotheroption=anothervalue
  phptype(dbsyntax)
  phptype
    </programlisting>

    <para>
      The currently supported database backends are:
    </para>
    fbsql   -> FrontBase?
    ibase   -> InterBase? / Firebird (requires PHP 5)
    mssql   -> Microsoft SQL Server (NOT for Sybase. Compile PHP --with-mssql)
    mysql   -> MySQL?
    mysqli  -> MySQL? (supports new authentication protocol) (requires PHP 5)
    oci8    -> Oracle 7/8/9/10
    pgsql   -> PostgreSQL?
    querysim    -> QuerySim?
    sqlite  -> SQLite 2

    <para>
      A second DSN format is supported phptype(syntax)://user:pass@protocol(proto_opts)/database
    </para>


    <para>
      If your database, option values, username or password contain characters used to delineate DSN parts, you can escape them via URI hex encodings:
    </para>
    : = %3a
    / = %2f
    @ = %40
    + = %2b
    ( = %28
    ) = %29
    ? = %3f
    = = %3d
    &amp; = %26


    <important>
    Please note, that some features may be not supported by all database backends.
    </important>

    <example>
      <title>Connect to database through a socket</title>
      <programlisting>
  mysql://user@unix(/path/to/socket)/pear
      </programlisting>
    </example>

    <example>
      <title>Connect to database on a non standard port</title>
      <programlisting>
  pgsql://user:pass@tcp(localhost:5555)/pear
      </programlisting>
    </example>

    <example>
      <title>Connect to SQLite on a Unix machine using options</title>
      <programlisting>
  sqlite:////full/unix/path/to/file.db?mode=0666
      </programlisting>
    </example>

    <example>
      <title>Connect to SQLite on a Windows machine using options</title>
      <programlisting>
  sqlite:///c:/full/windows/path/to/file.db?mode=0666
      </programlisting>
    </example>

    <example>
      <title>Connect to MySQLi using SSL</title>
      <programlisting>
  mysqli://user:pass@localhost/pear?key=client-key.pem&amp;cert=client-cert.pem
      </programlisting>
    </example>
  </sect1>
191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372
  <sect1 id="new-conn">
    <title>Opening a new connection</title>

    <para>
      Opening a new database connection in Doctrine is very easy. If you wish
      to use PDO (<ulink url="http://www.php.net/PDO">www.php.net/PDO</ulink>)
      you can just initalize a new PDO object:
    </para>
    
    <programlisting role="php"><![CDATA[
<?php
  $dsn = 'mysql:dbname=testdb;host=127.0.0.1';
  $user = 'dbuser';
  $password = 'dbpass';

  try {
    $dbh = new PDO($dsn, $user, $password);
  } catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
  }
?>]]></programlisting>

    <para>
     If your database extension isn't supported by PDO you can use special
     Doctrine_Adapter class (if availible). The following example uses DB2
     adapter:
    </para>

    <programlisting role="php"><![CDATA[
<?php 
  $dsn = 'db2:dbname=testdb;host=127.0.0.1';
  $user = 'dbuser';
  $password = 'dbpass';
 
  try {
    $dbh = Doctrine_Adapter::connect($dsn, $user, $password);
  } catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
  }
?>]]></programlisting>

    <para>
      The next step is opening a new Doctrine_Connection.
    </para>

    <programlisting role="php"><![CDATA[
<?php
  $conn = Doctrine_Manager::connection($dbh);
?>]]></programlisting>
  </sect1>
  <sect1 id="lazy-conn">
    <title>Lazy Connections</title>
    <para>
      Lazy-connecting to database is handled via Doctrine_Db wrapper. When
      using Doctrine_Db instead of PDO / Doctrine_Adapter, lazy-connecting to
      database is being performed (that means Doctrine will only connect to
      database when needed).
    </para>

    <para>
      This feature can be very useful when using for example page caching,
      hence not actually needing a database connection on every request.
      Remember connecting to database is an expensive operation.
    </para>
    <programlisting role="php"><![CDATA[
<?php
  // we may use PDO / PEAR like DSN
  // here we use PEAR like DSN
  $dbh = new Doctrine_Db('mysql://username:password@localhost/test');
  // !! no actual database connection yet !!

  // initalize a new Doctrine_Connection
  $conn = Doctrine_Manager::connection($dbh);
  // !! no actual database connection yet !!

  // connects database and performs a query
  $conn->query('FROM User u');
?>]]></programlisting>
  </sect1>
  <sect1 id="managing-conn">
    <title>Managing Connections</title>
    <para>
      From the start Doctrine has been designed to work with multiple
      connections. Unless separately specified Doctrine always uses the current
      connection for executing the queries. The following example uses
      openConnection() second argument as an optional connection alias.
    </para>

    <programlisting role="php"><![CDATA[
<?php
  // Doctrine_Manager controls all the connections
  $manager = Doctrine_Manager::getInstance();

  // open first connection
  $conn = $manager->openConnection(new PDO('dsn','username','password'), 'connection 1');
?>]]></programlisting>

    <para>
      For convenience Doctrine_Manager provides static method connection()
      which opens new connection when arguments are given to it and returns the
      current connection when no arguments have been speficied.
    </para>

    <programlisting role="php"><![CDATA[
<?php
  // open first connection
  $conn = Doctrine_Manager::connection(new PDO('dsn','username','password'), 'connection 1');

  $conn2 = Doctrine_Manager::connection();
  // $conn2 == $conn
?>]]></programlisting>

    <para>
      The current connection is the lastly opened connection. 
    </para>

    <programlisting role="php"><![CDATA[
<?php
  // open second connection
  $conn2 = $manager->openConnection(new PDO('dsn2','username2','password2'), 'connection 2');

  $manager->getCurrentConnection(); // $conn2
?>]]></programlisting>

    <para>
      You can change the current connection by calling setCurrentConnection(). 
    </para>


    <programlisting role="php"><![CDATA[
<?php

  $manager->setCurrentConnection('connection 1');

  $manager->getCurrentConnection(); // $conn

?>]]></programlisting>


    <para>
      You can iterate over the opened connection by simple passing the manager
      object to foreach clause. This is possible since Doctrine_Manager
      implements special IteratorAggregate interface.
    </para>

    <programlisting role="php"><![CDATA[
<?php
  // iterating through connections
  foreach($manager as $conn) {

  }
?>]]></programlisting>
  </sect1>
  <sect1 id="conn-component-binding">
    <title>Connection-component binding</title>

    <para>
      Doctrine allows you to bind connections to components (= your
      ActiveRecord? classes). This means everytime a component issues a query
      or data is being fetched from the table the component is pointing at
      Doctrine will use the bound connection.
    </para>

    <programlisting role="php"><![CDATA[
<?php
  $conn = $manager->openConnection(new PDO('dsn','username','password'), 'connection 1');

  $conn2 = $manager->openConnection(new PDO('dsn2','username2','password2'), 'connection 2');

  $manager->bindComponent('User', 'connection 1');

  $manager->bindComponent('Group', 'connection 2');

  $q = new Doctrine_Query();

  // Doctrine uses 'connection 1' for fetching here
  $users = $q->from('User u')->where('u.id IN (1,2,3)')->execute();

  // Doctrine uses 'connection 2' for fetching here
  $groups = $q->from('Group g')->where('g.id IN (1,2,3)')->execute();
?>]]></programlisting>
  </sect1>
373
</chapter>