<?php
/**
 * Dao - simple extension for the Zend_Db_Table.
 *
 * @package koubel homepage
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */

/**
 * This class adds some usefull functionality onto Zend_Db_Table.
 *
 * Inits default adapter by resource module, adds the row count getter.
 * 
 * @package koubel homepage
 * @author Miroslav Kubelik (koubel@volny.cz)
 * @copyright Copyright (c) 2007-2009 Miroslav Kubelik
 * @license http://opensource.org/licenses/gpl-license.php GNU GPL
 */
abstract class Dao extends Zend_Db_Table_Abstract
{
    /**
     * Sets default adapter for the
     * table. Use cache for the tables metadata.
     * @return Dao
     */ 
    public function __construct()
    {
        //set default adapter if isn't set
        if (!self::$_defaultDb) {
            self::_initDefaultAdapter();
        }

        //sets default metadata cache if isn't set
        if (!self::$_defaultMetadataCache) {
            self::setDefaultMetadataCache(
                self::_getBootstrap()->getResource('cache')
            );
        }
        
        parent::__construct();
    }

    /**
     * inits default adapter from bootstrap resource
     */
    private static function _initDefaultAdapter()
    {
        self::setDefaultAdapter(self::_getBootstrap()
            ->getResource('db')
            ->getDbAdapter()
        );
    }

    /**
     * Gets defautl adapter
     * @return Zend_Db_Adapter_Abstract
     */
    public static function getDefaultAdapter()
    {
        if (!self::$_defaultDb) self::_initDefaultAdapter();
        return parent::getDefaultAdapter();
    }

    /**
     * Gets row count in the table.
     * @return int
     */
    public function getCount()
    {
        $sql = "select count(*) from $this->_name";
        return $this->getAdapter()->fetchOne($sql);
    }

    /**
     * Helper for accessing application bootstrap
     * @staticvar Bootstrap $bootstrap
     * @return Bootstrap
     */
    private static function _getBootstrap()
    {
        static $bootstrap;
        if (!isset($bootstrap)) {
            $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        }
        return $bootstrap;
    }
}
