View.php 2.31 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
<?php
/**
 * Doctrine_View
 *
 * this class represents a database view
 */
class Doctrine_View {
    /**
     * SQL DROP constant
     */
    const DROP   = 'DROP VIEW %s';
    /**
     * SQL CREATE constant
     */
    const CREATE = 'CREATE VIEW %s AS %s';
    /**
     * SQL SELECT constant
     */
    const SELECT = 'SELECT * FROM %s';


    /**
     * @var string $name
     */
    protected $name;
    /**
     * @var Doctrine_Query $query
     */
    protected $query;
    /**
     * @var PDO $dbh
     */
    protected $dbh;

    /**
     * constructor
     *
     * @param Doctrine_Query $query
     */
zYne's avatar
zYne committed
40 41
    public function __construct(Doctrine_Query $query, $viewName) {
        $this->name  = $viewName;
42 43
        $this->query = $query;
        $this->query->setView($this);
zYne's avatar
zYne committed
44
        $this->dbh   = $query->getConnection()->getDBH();
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
    }
    /**
     * simple get method for getting 
     * the associated query object
     *
     * @return Doctrine_Query
     */
    public function getQuery() {
        return $this->query;
    }
    /**
     * returns the name of this view
     *
     * @return string
     */
    public function getName() {
        return $this->name;
    }
    /**
     * returns the database handler
     *
     * @return PDO
     */
    public function getDBH() {
        return $this->dbh;
    }
    /**
     * creates this view
     *
     * @return void
     */
    public function create() {
        $sql = sprintf(self::CREATE, $this->name, $this->query->getQuery());
78 79 80 81 82
        try {
            $this->dbh->query($sql);
        } catch(Exception $e) {
            throw new Doctrine_View_Exception($e->__toString());
        }
83 84 85 86 87 88 89
    }
    /**
     * drops this view
     *
     * @return void
     */
    public function drop() {
90 91 92 93 94
        try {
            $this->dbh->query(sprintf(self::DROP, $this->name));
        } catch(Exception $e) {
            throw new Doctrine_View_Exception($e->__toString());
        }
95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
    }
    /**
     * executes the view
     * 
     * @return Doctrine_Collection
     */
    public function execute() {
        return $this->query->execute();
    }
    /**
     * @return string
     */
    public function getSelectSql() {
        return sprintf(self::SELECT, $this->name);
    }
}
111