5.6. Database access using PDO

5.6.1. Using a class which inherits PDO

Let's create the class which inherits PDO class and setup the data source information by the constructor method. As an example, the following SqlitePdo class is created to /path/to/classes/SqlitePdo.php.

<?php
class SqlitePdo extends \PDO {
    public function __construct() {
        parent::__construct('sqlite:' . DB_DIR . '/sqlite.db');
        $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    }
}

Please create CdDao class which uses the created PDO class.

<?php
class CdDao {
    public $sqlitePdo = null;
    public function findAll() {
        $stmt = $this->sqlitePdo->prepare('select * from CD');
        $stmt->setFetchMode(PDO::FETCH_OBJ);
        $stmt->execute();
        return $stmt->fetchAll();
    }
}

PDO class and CdDao class are imported by S2ApplicationContext.

<?php
require_once('S2Container/S2Container.php');
define('DB_DIR', dirname(__FILE__) . '/db');
use seasar\container\S2ApplicationContext as s2app;

s2app::import(dirname(__FILE__) . '/classes');
$cdDao = s2app::get('CdDao');
var_dump($cdDao->findAll());

5.6.2. PDO setup by DICON

PDO is set up by a DICON file. As an example, please create following DICON file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE components PUBLIC "-//SEASAR2.1//DTD S2Container//EN"
"http://www.seasar.org/dtd/components21.dtd">
<components>
   <component name="sqlitePdo" class="PDO">
       <arg>return 'sqlite:' . DB_DIR . '/sqlite.db'</arg>
   </component>
</components>

The DICON file and CdDao class are imported by S2ApplicationContext.

<?php
require_once('S2Container/S2Container.php');
use seasar\container\S2ApplicationContext as s2app;

s2app::import(dirname(__FILE__) . '/classes/CdDao.php');
s2app::import(dirname(__FILE__) . '/dicon');
$cdDao = s2app::get('CdDao');
var_dump($cdDao->findAll());

[Note]NOTE

This Example is located in examples/misc/datasource.



© Copyright The Seasar Foundation and the others 2005-2010, all rights reserved.