当前位置:首页 > PHP教程 > php高级应用 > 列表

使用PHP反射机制来构造"CREATE TABLE"的sql语句

发布:smiling 来源: PHP粉丝网  添加日期:2021-11-13 22:44:44 浏览: 评论:0 

反射是指在PHP运行状态中,扩展分析PHP程序,导出或提取出关于类、方法、属性、参数等的详细信息,包括注释。这种动态获取的信息以及动态调用对象的方法的功能称为反射API。

反射是操纵面向对象范型中元模型的API,其功能十分强大,可帮助我们构建复杂,可扩展的应用。

其用途如:自动加载插件,自动生成文档,甚至可用来扩充PHP语言。

php反射api由若干类组成,可帮助我们用来访问程序的元数据或者同相关的注释交互。借助反射我们可以获取诸如类实现了那些方法,创建一个类的实例(不同于用new创建),调用一个方法(也不同于常规调用),传递参数,动态调用类的静态方法。

反射api是php内建的oop技术扩展,包括一些类,异常和接口,综合使用他们可用来帮助我们分析其它类,接口,方法,属性,方法和扩展,这些oop扩展被称为反射。

下面的程序使用Reflection来构造"CREATE TABLE"的sql语句。如果你不是很熟悉反射机制,可以从这个程序中看看反射的魅力与作用。

  1. <?php 
  2. /** 
  3.  * Creates an SQL 'Create Table' based upon an entity 
  4.  * @author Chris Tankersley <chris@ctankersley.com> 
  5.  * @copyright 2010 Chris Tankersley 
  6.  * @package PhpORM_Cli 
  7.  */ 
  8. class PhpORM_Cli_GenerateSql 
  9. { 
  10.   /** 
  11.    * Use a MySQL database 
  12.    */ 
  13.   const MYSQL = 'mysql'; 
  14.   /** 
  15.    * Use a SQLite database 
  16.    */ 
  17.   const SQLITE = 'sqlite'; 
  18.   /** 
  19.    * Types that are allowed to have a length 
  20.    * @var array 
  21.    */ 
  22.   protected $_hasLength = array('integer', 'varchar'); 
  23.   /** 
  24.    * Regexes needed to pull out the different comments 
  25.    * @var array 
  26.    */ 
  27.   protected $_regexes = array( 
  28.     'type' => '/ type=([a-z_]*) /', 
  29.     'length' => '/ length=([0-9]*) /', 
  30.     'default' => '/ default="(.*)" /', 
  31.     'null' => '/ null /', 
  32.   ); 
  33.   /** 
  34.    * Types that we support 
  35.    * @var array 
  36.    */ 
  37.   protected $_validTypes = array( 
  38.     'boolean' => 'BOOL', 
  39.     'date' => 'DATE', 
  40.     'integer' => 'INT', 
  41.     'primary_autoincrement' => 'INT AUTO_INCREMENT PRIMARY KEY', 
  42.     'text' => 'TEXT', 
  43.     'timestamp' => 'TIMESTAMP', 
  44.     'varchar' => 'VARCHAR', 
  45.   ); 
  46.   /** 
  47.    * Name of the class we will interperet 
  48.    * @var string 
  49.    */ 
  50.   protected $_className; 
  51.   /** 
  52.    * Name of the table we are generating 
  53.    * @var string 
  54.    */ 
  55.   protected $_tableName; 
  56.   /** 
  57.    * The type of database we are generating 
  58.    * @var string 
  59.    */ 
  60.   protected $_type; 
  61.   /** 
  62.    * Sets the name of the class we are working with 
  63.    * @param string $class 
  64.    * @param string $table_name 
  65.    * @param string $type 
  66.    */ 
  67.   public function __construct($class, $table_name, $type = self::MYSQL) 
  68.   { 
  69.     $this->_className = $class; 
  70.     $this->_tableName = $table_name; 
  71.     $this->_type = $type; 
  72.   } 
  73.   /** 
  74.    * Builds an SQL Line for a property 
  75.    * @param ReflectionProperty $property 
  76.    * @return string 
  77.    */ 
  78.   protected function _getDefinition($property) 
  79.   { 
  80.     $type = ''; 
  81.     $length = ''; 
  82.     $null = ''; 
  83.     preg_match($this->_regexes['type'], $property->getDocComment(), $matches); 
  84.     if(count($matches) == 2) { 
  85.       if(array_key_exists($matches[1], $this->_validTypes)) { 
  86.         $type = $this->_validTypes[$matches[1]]; 
  87.         if(in_array($matches[1], $this->_hasLength)) { 
  88.           $length = $this->_getLength($property); 
  89.         } 
  90.         if($matches[1] != 'primary_autoincrement') { 
  91.           $null = $this->_getNull($property); 
  92.         } 
  93.         $sql = '`'.$property->getName().'` '.$type.' '.$length.' '.$null; 
  94.         return $sql; 
  95.       } else { 
  96.         throw new Exception('Type "'.$matches[1].'" is not a supported SQL type'); 
  97.       } 
  98.     } else { 
  99.       throw new Exception('Found '.count($matches).' when checking Type for property '.$property->getName()); 
  100.     } 
  101.   } 
  102.   /** 
  103.    * Extracts the Length from a property 
  104.    * @param ReflectionProperty $property 
  105.    * @return string 
  106.    */ 
  107.   protected function _getLength($property) 
  108.   { 
  109.     preg_match($this->_regexes['length'], $property->getDocComment(), $matches); 
  110.     if(count($matches) == 2) { 
  111.       return '('.$matches[1].')'; 
  112.     } else { 
  113.       return ''; 
  114.     } 
  115.   } 
  116.   /** 
  117.    * Determines if a Property is allowed to be null 
  118.    * @param ReflectionProperty $property 
  119.    * @return string 
  120.    */ 
  121.   protected function _getNull($property) 
  122.   { 
  123.     preg_match($this->_regexes['null'], $property->getDocComment(), $matches); 
  124.     if(count($matches) == 1) { 
  125.       return 'NULL'; 
  126.     } else { 
  127.       return 'NOT NULL'; 
  128.     } 
  129.   } 
  130.   /** 
  131.    * Generates a block of SQL to create a table from an Entity 
  132.    * @return string 
  133.    */ 
  134.   public function getSql() 
  135.   { 
  136.     $class = new ReflectionClass($this->_className); 
  137.     $definitions = array(); 
  138.     foreach($class->getProperties() as $property) { 
  139.       if(strpos($property->getName(), '_') === false) { 
  140.         $definitions[] = $this->_getDefinition($property); 
  141.       } 
  142.     } 
  143.     $columns = implode(",n", $definitions); 
  144.     $sql = "CREATE TABLE ".$this->_tableName." (".$columns.")"; 
  145.     if($this->_type == self::MYSQL) { 
  146.       $sql .= " ENGINE=MYISAM"; 
  147.     } 
  148.     return $sql.";"; 
  149.   } 
  150. }

Tags: PHP反射机制 CREATE TABLE

分享到: