Php orm framework and simple code implementation

Source: Internet
Author: User

Object Relational ing (ORM) is a technology designed to solve the mismatch between objects and Relational databases. To put it simply, ORM automatically persists the objects in the program to the relational database by using metadata that describes the ing between objects and databases. In essence, data is converted from one form to another.

ORM provides the generation of all SQL statements, and the code staff are far away from the Database concept. Ing from a conceptual requirement (such as an HQL) into an SQL statement does not require any cost, and even 1% of the performance loss occurs. In the ing process, the real performance loss is more specifically in the Process of Object Instantiation.

Currently, the most famous open-source php orm includes the following:

1. Propel

Propel is an Object Relational Mapping framework applicable to PHP5. It supports the Object Persistence Layer Based on Apache Torque. It uses schema definition files in XML format and corresponding configuration files to generate SQL statements and classes. It allows you to use objects instead of SQL statements to read and write records in database tables. Propel provides a generator to create an SQL definition file and a PHP class for your data model. Developers can also easily customize the generated classes. We can also integrate Propel into the existing application development framework through XML, PHP, and Phing build tools. for example, in versions earlier than 1.2 of PHP framework symfony, the lite version of Propel is used as the default ORM framework by default.

Http://www.propelorm.org/

2. Doctrine

Doctrine is a php orm framework that must run on version> = php5.2.3. It is a powerful data abstraction layer.

One of its main features is the use of object-oriented methods to achieve database query transfer. It uses a DQL query statement similar to Hibernate HQL at the underlying layer for database query, this makes development more flexible and greatly reduces repeated code. Compared with Propel, Doctrine supports full-text retrieval. Doctrine documents are always richer and more active than Propel, it is more natural to use, easier to read, and closer to native SQL. Performance is slightly better than Propel. You can also easily integrate Doctrine into existing application frameworks. For example, Doctrine is used as the default ORM framework in Versions later than 1.3 of PHP symfony, doctrine and Codeigniter can also be integrated.

Http://www.doctrine-project.org/

3. EZPDO

EZPDO is a very lightweight php orm framework. The author of EZPDO aims to reduce the complex ORM learning curve and try to strike a balance between the operational efficiency and functions of the ORM. It is the simplest ORM framework I have ever used, at present, I want to integrate it into my CoolPHP SDK, and the running efficiency is quite good, and the functions can basically meet the needs, but the ESPDO update is relatively slow.

Http://www.ezpdo.net/blog? P = 2

4. RedBean

RedBean is an easy-to-use, lightweight php orm framework that provides support for MySQL, SQLite & PostgreSQL. The RedBean architecture is very flexible and the core is very simple. developers can easily extend functions through plug-ins.

Http://www.redbeanphp.com/

5. Others

The fleaphp development Framework in China implements ORM Based on TableDataGateway. In addition to providing SQL statement encapsulation, Zend Framework also implements TableGateway, TableRowSet, and TableRow; there are also some solutions similar to the implementation of Rails ActiveRecord.

In general, the orm framework can meet basic requirements to deal with simple application systems, greatly reducing development difficulty and improving development efficiency. However, in terms of SQL optimization, it must be a little worse than pure SQL, and it may not be ideal for processing complex associations and SQL nested expressions. Perhaps this is mainly because of the persistence of PHP objects, resulting in low ORM efficiency, which is generally slower than pure SQL. However, there are solutions to these problems. The most basic solution to performance is that we can use cache to improve efficiency. For Hibernate, although the configuration is complicated, however, the flexible use of the second-level cache and query cache greatly relieves the database query pressure, greatly improving the system performance.

If you want to implement a php orm by yourself, refer to the following:

<?phpabstract class Model{   protected $pk = 'id';   protected $_ID = null;    protected $_tableName;   protected $_arRelationMap;   protected $_modifyMap;   protected $is_load = false;   protected $_blForDeletion;   protected $_DB;   public function __consturct($id = null){       $this->_DB = mysql_connect('127.0.0.1','root','') ;       $this->_tableName = $this->getTableName();       $this->_arRelationMap = $this->getRelationMap();       if(isset($id))$this->_ID = $id;   }   abstract protected function getTableName();   abstract protected function getRelationMap();   public function Load(){       if(isset($this->_ID)){           $sql = "SELECT ";           foreach($this->_arRelationMap as $k => $v){               $sql .= '`'.$k.'`,';           }           $sql .= substr($sql,0,strlen($sql)-1);           $sql .= "FROM ".$this->_tableName." WHERE ".$this->pk." = ".$this->_ID;           $result =$this->_DB->mysql_query($sql);           foreach($result[0] as $k1 => $v1){              $member = $this->_arRelationMap[$key];              if(property_exists($this,$member)){                 if(is_numeric($member)){                     eval('$this->'.$member.' = '.$value.';');                 }else{                     eval('$this->'.$member.' = "'.$value.'";');                 }              }           }       }       $this->is_load = true;   }   public function __call($method,$param){      $type   = substr($method,0,3);      $member = substr($method,3);      switch($type){         case 'get':             return $this->getMember($member);             break;         case 'set':             return $this->setMember($member,$param[0]);      }      return false;   }   public function setMember($key){       if(property_exists($this,$key)){          if(is_numeric($val)){             eval('$this->'.$key.' = '.$val.';');          }else{             eval('$this->'.$key.' = "'.$val.'";');          }          $this->_modifyMap[$key] = 1;       }else{          return false;       }   }      public function getMember($key,$val){       if(!$this->is_load){          $this->Load();       }       if(property_exists($this,$key)){          eval('$res = $this->'.$key.';' );          return $this->$key;       }       return false;   }   public function save(){      if(isset($this->_ID)){          $sql = "UPDATE ".$this->_tableName." SET ";          foreach($this->arRelationMap as $k2 => $v2){              if(array_key_exists( $k2, $this->_modifyMap)){                  eval( '$val = $this->'.$v2.';');                  $sql_update .=  $v2." = ".$val;              }          }          $sql .= substr($sql_update,0,strlen($sql_update));          $sql .= 'WHERE '.$this->pk.' = '.$this->_ID;      }else{          $sql = "INSERT INTO ".$this->_tableName." (";          foreach($this->arRelationMap as $k3 => $v3){              if(array_key_exists( $k3,$this->_modifyMap)){                  eval('$val = $this->'.$v3.';');                  $field  .= "`".$v3."`,";                   $values .= $val;              }          }          $fields = substr($field,0,strlen($field)-1);          $vals   = substr($values,0,strlen($values)-1);          $sql .= $fields." ) VALUES (".$vals.")";      }      echo $sql;      //$this->_DB->query($sql);   }   public function __destory(){      if(isset($this->ID)){         $sql = "DELETE FROM ".$this->_tableName." WHERE ".$this->pk." = ".$this->_ID;        // $this->_DB_query($sql);      }   }}class User extends Model{    protected  function getTableName(){       return "test_user";    }    protected function getRelationMap(){        return array(                       'id'       => USER_ID,                      'user_name'=> USER_NAME,                      'user_age' => USER_AGE                    );    }    public function getDB(){       return $this->_DB;    }}$UserIns = new User();print_r($UserIns);?>

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.