用反射來產生SQL的CREATE語句_PHP教程

來源:互聯網
上載者:User
下面的程式使用Reflection來構造"CREATE TABLE"的sql語句。如果你不是很熟悉反射機制,可以從這個程式中看看反射的魅力與作用。

 * @copyright 2010 Chris Tankersley * @package PhpORM_Cli */class PhpORM_Cli_GenerateSql{    /**     * Use a MySQL database     */    const MYSQL = 'mysql';    /**     * Use a SQLite database     */    const SQLITE = 'sqlite';    /**     * Types that are allowed to have a length     * @var array     */    protected $_hasLength = array('integer', 'varchar');    /**     * Regexes needed to pull out the different comments     * @var array     */    protected $_regexes = array(        'type' => '/ type=([a-z_]*) /',        'length' => '/ length=([0-9]*) /',        'default' => '/ default="(.*)" /',        'null' => '/ null /',    );    /**     * Types that we support     * @var array     */    protected $_validTypes = array(        'boolean' => 'BOOL',        'date' => 'DATE',        'integer' => 'INT',        'primary_autoincrement' => 'INT AUTO_INCREMENT PRIMARY KEY',        'text' => 'TEXT',        'timestamp' => 'TIMESTAMP',        'varchar' => 'VARCHAR',    );    /**     * Name of the class we will interperet     * @var string     */    protected $_className;    /**     * Name of the table we are generating     * @var string     */    protected $_tableName;    /**     * The type of database we are generating     * @var string     */    protected $_type;    /**     * Sets the name of the class we are working with     * @param string $class     * @param string $table_name     * @param string $type     */    public function __construct($class, $table_name, $type = self::MYSQL)    {        $this->_className = $class;        $this->_tableName = $table_name;        $this->_type = $type;    }    /**     * Builds an SQL Line for a property     * @param ReflectionProperty $property     * @return string     */    protected function _getDefinition($property)    {        $type = '';        $length = '';        $null = '';                preg_match($this->_regexes['type'], $property->getDocComment(), $matches);        if(count($matches) == 2) {            if(array_key_exists($matches[1], $this->_validTypes)) {                $type = $this->_validTypes[$matches[1]];                if(in_array($matches[1], $this->_hasLength)) {                    $length = $this->_getLength($property);                }                if($matches[1] != 'primary_autoincrement') {                    $null = $this->_getNull($property);                }                $sql = '`'.$property->getName().'` '.$type.' '.$length.' '.$null;                return $sql;            } else {                throw new Exception('Type "'.$matches[1].'" is not a supported SQL type');            }        } else {            throw new Exception('Found '.count($matches).' when checking Type for property '.$property->getName());        }    }    /**     * Extracts the Length from a property     * @param ReflectionProperty $property     * @return string     */    protected function _getLength($property)    {        preg_match($this->_regexes['length'], $property->getDocComment(), $matches);        if(count($matches) == 2) {            return '('.$matches[1].')';        } else {            return '';        }    }    /**     * Determines if a Property is allowed to be null     * @param ReflectionProperty $property     * @return string     */    protected function _getNull($property)    {        preg_match($this->_regexes['null'], $property->getDocComment(), $matches);        if(count($matches) == 1) {            return 'NULL';        } else {            return 'NOT NULL';        }    }    /**     * Generates a block of SQL to create a table from an Entity     * @return string     */    public function getSql()    {        $class = new ReflectionClass($this->_className);        $definitions = array();        foreach($class->getProperties() as $property) {            if(strpos($property->getName(), '_') === false) {                $definitions[] = $this->_getDefinition($property);            }        }        $columns = implode(",n", $definitions);                $sql = "CREATE TABLE ".$this->_tableName." (".$columns.")";        if($this->_type == self::MYSQL) {            $sql .= " ENGINE=MYISAM";        }        return $sql.";";    }}

http://www.bkjia.com/PHPjc/752416.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/752416.htmlTechArticle下面的程式使用Reflection來構造"CREATE TABLE"的sql語句。如果你不是很熟悉反射機制,可以從這個程式中看看反射的魅力與作用。 ?php/** * Crea...

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.