PHP ORM Object Relational Mapping

Source: Internet
Author: User

The full name of the ORM is the object Relational Mapping, which is a relational mapping of objects. The essence of it is to represent the business data in the relational data (library) in the form of objects, and to organize these objects by object-oriented (object-oriented) way, and realize the process of the system business logic. The most important concept in the ORM process is mapping (Mapping), which allows the business object to be detached from the database. From an object-oriented perspective, the database should not be bound together with business logic, ORM is such a separation, so that the database layer transparent, developers really object-oriented. Figure 1 illustrates this role of ORM in the architecture of multi-layered systems.

Figure 1:orm function in multi-layer system architecture

Most projects or products now use relational databases to store business data so that in the development process, there are often business logic that needs to be implemented directly with write SQL statements, but the result is that the SQL statements are everywhere. These high-coupling SQL statements bring many unpredictable obstacles to the transformation and upgrading of the system. ORM is a good choice for improving project flexibility, especially for rapid development. As a simple example: in a system using ORM, when the database model changes, it is no longer necessary to ignore all the changes in the logic code and SQL statements that involve the model, just change the object that the model is mapped to, or even make changes to meet the requirements.

Contents of this page
One, the ORM tool realization: Grove
Ii. the practical application of grove in development
Iii. Summary

One, the ORM tool realization: Grove

Good ORM Tools not only help us understand the relationship between objects and objects, but the tools themselves help us to maintain these relationships. Based on this concept, I designed a. NET ORM Tool--grove ORM Development Toolkit.

Grove ORM Development Toolkit contains two parts of Grove and Toolkit. Grove provides the ORM with object persistence, relational object query, simple transaction processing, simple exception management and other functions. Data persistence includes the INSERT, Delete, Update, retrieve and other functions of some objects, and the relational object query provides some complex object-based relational queries, including subqueries that correspond to database functions, association queries (joins), function support (count, AVG, Max, Min), aggregations, and so on. Toolkit is an add-in developed by VSIP, Vs.net 2002/2003, to help developers quickly map the business model in a relational database to the mapped entity classes that meet grove requirements, as well as mapping the relational mapping entities that complex relational queries in the database have to the grove requirements. Only C # support is available for the time being. Figure 2 is the Grove inner class implementation diagram.

Figure 2:grove Inner class implementation diagram

In the early work of ORM implementation, in order to achieve the shielding of the operational differences between the various databases, we need to define the data operation public interface, encapsulating the basic database Insert,update,delete,query and other operations.

public interface Idboperator{int Execnonquery (string cmdtext); int Execdataset (String cmdtext,dataset entity); object Execscalar (string cmdtext); ...}

Define a database operations factory class to adapt different types of data.

Public abstract class Dboperatorfactory:idboperator

Then implement the various database operation classes, take SQL Server as an example.

Internal class Sqldboperator:dboperatorfactory

When done, it is the implementation of the ORM protagonist-entity. The definition of an entity in an ORM can be implemented by means of the entity class itself containing the metadata of the data model, or by defining the meta-description of the XML. The following describes the implementation of mapping through the entity class itself.

Entity is the carrier of the actual business data, contains the meta-description of the business data model, can be generated directly from a table or view in the database, or can be created manually as needed. NET provides System.Attribute, which contains an easy way to access and test custom properties. The. NET Framework pre-defines some property types and uses them to control run-time behavior. We can customize the data model metadata that is needed to describe the entity object mappings by inheriting the System.Attribute base class, including some commonly used data such as table name, field name, field length, field type, and so on.

[AttributeUsage (AttributeTargets.Class | ATTRIBUTETARGETS.STRUCT)]public class Datatableattribute:attribute

AttributeUsage is used to indicate what kind of object the custom attribute can be bound to, which means that it is applied to a class or struct.

Abstract some properties that have the same characteristics, making them the base class for custom attributes.

[AttributeUsage (Attributetargets.property)]public class Basefieldattribute:attribute

Defines a custom attribute class that is required for a generic field.

[AttributeUsage (Attributetargets.property)]public class Datafieldattribute:basefieldattribute

Defines the custom attribute class that is required for the keyword field.

[AttributeUsage (Attributetargets.property)]public class Keyfieldattribute:basefieldattribute

Defines the custom attribute class that is required for the foreign key field.

[AttributeUsage (Attributetargets.property)]public class Foreignkeyfieldattribute:basefieldattribute

After the custom attribute class is complete, we need a help class that accesses the custom properties and property data that the entity binds to at run time.

Internal class Typehelper

After the entity definition is complete, we need to construct the SQL statements required for the runtime based on the custom attributes bound in the entity class, in order to collect the data structure descriptions in the entity class definition, we need to define a class that describes all the data persistence information that the entity refers to at runtime, including the key field, the Foreign key field, General fields, and so on.

Internal class TypeInfo

You also need a field metadata description class that describes the name, size, nullable, column type, and so on for the field in the database.

Internal class Columninfo

With these conditions in place, we need to define a parsing class that is responsible for converting the data's program type to the database field type, and constructs the SQL statements needed for operations such as Insert,update,delete,query.

Internal class Sqlentityparser

Combining the above actions is the entity class object operator.

public class Objectoperator

Implementation adds a new record to the database, which is to create a fresh entity object and leave it to the object operator for persistence.

public void Insert (object o) {typeinfo info1=new typeinfo (O.gettype ());//based on instance or entity description Information SqlCommand sc=info1. Buildinsertcommand (o);//constructs the SQL command object DBOPERATOR.PARAMETERS=SC. parameters;//the parameter dboperator.execnonquery (Sc.commandtext) required to assign the SQL command;//Execute SQL command}

The SqlCommand object here encapsulates some of the values required for SQL command processing, including SQL statements, command parameters (Parameter), and so on.

Ii. the practical application of grove in development

Installing Grove Kit requires Visual Studio 2003 and. NET Framework 1.1 support. After downloading the installation package from the Grove website, unzip the Grovekit.zip and perform the installation.

After the Grovekit installation is complete, open vs.net, on the vs.net splash screen, you will see the Grove DEVELOP Kit flag indicating that Grovekit has been properly installed.

2.1 Generating Mapping entity classes

This article will take the C # project as an example to explain the specific application of grove in development. Project name WEBAPP1, operating system Windows 2000, database SQL Server 2000, DB instance Name: WEBAPP1, table structure is defined as follows:

Table name Field

Customers

CustomerID Int (4) PK

CustomerName varchar (50)

Customerdesc varchar (200)

Status tinyint

Addresses

Addressid Int (4) PK

CustomerID Int (4) FK

Address varchar (200)

1.

In Vs.net, open the new project, "file," in the Visual C # project, select the ASP. NET Web application, determine the build WebApp1 project, Add a reference to Grove.dll in your project, Grove.dll is located under the installation path of Grovekit, and you can add the Grove to the assembly cache through. NET configuration.

2.

In Vs.net, open tools->grove tool Kit, set the database connection properties in Grovetoolkit, and save.

Figure 3 Setting up a database connection string

3.

Configure the Web. config for the current project (add the following configuration before </configuration>)

<appsettings><add key= "dbconnstring" value= "server=localhost; Uid=sa; Pwd=sa;database=webapp1 "/></appsettings>

4.

4) Select entities in the Vs.net Solution Explorer and select the table name in the Grovetoolkit and click the Preview entity class button in Grovetoolkit toolbar to see the Entity Mapping Class Preview window for that table.

Figure 4 Previewing the Entity mapping class

5.

Check the entity class for the current preview, click the Generate File button, and the entity class will be generated under the path currently selected by Solution Explorer.

6.

Repeating the 4,5 step allows you to generate mapping entity classes for other tables.

Customer.csusing system;using Grove.orm; [DataTable ("Customers")]public class Customer{int _customerid;string _customername;string _customerdesc;int _status;[ Keyfield ("CustomerID")]public int customerid{get{return This._customerid;} Set{this._customerid=value;}} [DataField ("CustomerName")]public string Customername{get{return this._customername;} Set{this._customername=value;}} [DataField ("Customerdesc")]public string Customerdesc{get{return This._customerdesc;} Set{this._customerdesc=value;}} [DataField ("status")]public int status{get{return this._ Status;} Set{this._ Status=value;}}}
Address.csusing system;using Grove.orm; [DataTable ("Addresses")]public class Address{int _addressid;int _customerid;string _address;[ Keyfield ("Addressid")]public int addressid{get{return This._addressid;} Set{this._addressid=value;}} [Foreignkeyfield ("CustomerID")]public int customerid{get{return This._customerid;} Set{this._customerid=value;}} [DataField ("Address")]public string Customeraddress{get{return this._address;} Set{this._address=value;}}}

Code 1. Entity Mapping class

2.2 Object Persistence

Grove provides objectoperator implementation of database persistence for mapped entity objects and implements queries for complex database relational mapping entities through the Iobjectquery interface, with the following main interfaces:

Method Description

Insert

Add an Object

Update

Update an object based on conditions

Remove

Delete an object based on a condition

Removechilds

Delete all Relationship objects

Retrieve

Returns an object

Retrievechilds

Return all Relationship objects

Getdatareader

Back to IDataReader

Getobjectset

Returns a collection of objects

Getobjectsource

Returns a dataset based on the object definition

GetCount

Returns the number of record bars from the data source

Begintranscation

Start the transaction on the basis of the database support transaction

Commit

Complete the current transaction

Rollback

Fallback current transaction

2.3 data Query

Like the general relational database has the query function, Grove also has a very rich query function, such as Object query, function query, sub-query, sort query and so on. Here is a brief introduction to object queries, and other query readers can refer to the Grove's development documentation themselves. Grove provides ObjectQuery help Objectoperator query data from a data source, Objectoperator need to parse the attribute (System.arrtibute) definition in the Entity object by ObjectQuery and construct a query statement. ObjectQuery often need to define a filter statement at run time (refer to the syntax definition of the filter statement). For example, retrieve the Customer object when the state property equals WA:

ObjectQuery query=new ObjectQuery (typeof (Customer), "this." State= ' WA ');

You do not need to define a filter statement when retrieving all objects that need to be returned

ObjectQuery query=new ObjectQuery (typeof (Customer), "");

2.4 syntax definitions for filter statements

The filters used in ObjectQuery allow you to define filter statements based on the use of object-oriented syntax rules when you define them.

Operation Describe

!, not

Used to compare Boolean types, for example:

! Order.CustomerID.Contains (Customer.customerid)

<, <=, >=

Used for value comparisons, such as:

Order.quantity >= 12

=,! =, <>, = =

Used for value judgments, for example:

Customer.country = ' USA ' and customer.region! = ' WA '

And, &&

Used for logical judgments, such as:

Customer.country = ' USA ' and customer.region = ' WA '

Or, | |

Used for logical judgments, such as:

Customer.lastname = ' Smith ' or customer.lastname = ' Jones '

Iii. Summary

The above is the simple implementation of ORM, complex relational object mapping and query of the relational mapping entity is a particularly important piece of processing, in order to block the SQL differences between the databases, many good ORM framework provides a matching object-oriented language itself syntax rules Query Language support, For example, when implementing support for database functions, it can be implemented by defining a number of publicly accessible languages, such as defining object.size (), Object.sum (), and other class-based operation syntax, which provides logical operator support for some languages, such as C # && in and,| | A series of support for object-oriented programming styles, such as OR and so on, is a good way to support the development of system based on relational database support to "object oriented". Grove currently has good support for relational object queries and is interested in learning more about the Grove's website.

PHP ORM Object Relational Mapping

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.