Introduction of ORM Doctrine under CodeIgniter

Source: Internet
Author: User
Tags autoload codeigniter

Two years of CI development, has been using ActiveRecord to operate the database. Simple, lightweight and convenient. A recent project was handed over to the team, and the development process started with the database design, which is now running on-line. Through the process of clearing requirements, designing databases, establishing model in CI, controller, change of requirements, changing database, changing code, increasing demand, changing database and so on. Looking back, when you need to understand the global code and business logic requirements, still have to start from the database, suddenly have a bored feet: The object's properties are in the database, and the related operations in the code, feel very split. Recall that many years ago developed C # and Java have some good ORM framework, for me, the biggest advantage of ORM is to hide the database, project design, according to the requirements of the design of objects, light, do not have to fall into the increase in the deletion; direct use of tools to map objects to a database The database is also object-oriented in its modification and deletion.

Possible two-point concerns:

    1. Since objects are automatically mapped to databases, it is natural to follow a set of metadata rules.
    2. Performance issues, automatically generated by ORM SQL statements, performance may not be as good as before. However, comparing the readability/maintainability of a frame with a little hardware performance cost, or choosing a framework is preferred. In addition, it is believed that ORM's 90% performance impact is not small, a little real ORM can not solve the problem will provide the original SQL to solve, in general, is the advantages outweigh the disadvantages.

(Official Reference Document:http://doctrine-orm.readthedocs.org/en/latest/tutorials/getting-started.html)

Let's get started, what we're aiming for, no cavities! Well, this is just one of our purposes, and for other purposes:

    • Generate databases based on established objects;
    • New objects are persisted to the database;
    • You can use entity to easily query information in your data and achieve changes.
1. Install the doctrine under CI

A. The latest CI 3.0 has supported composer. Create the Composer.son file under the application folder as follows. (Not in the CI root directory). Note the AutoLoad parameter (not the/src/folder in the official example)

{    "require": {        "doctrine/orm": "2.4.*",        "Symfony/yaml": "2.*"    },     "AutoLoad": {        "psr-0": {"": "Models/entities"}}    }

NOTES: The above AutoLoad parameter is important, because doctrine need to specify the entity directory, the original example is given/SRC, here we put in the model/entities directory of CI, in addition, create model/ Generated and models/proxies directories, generated directories are used by the database to generate the Entity,proxies directory used to store the code that the lazy load needs to generate.

B. Install the Doctrine:composer installation. The post-installation directory structure is as follows:

2. Configuring Bootstrap and Cli-config

In doctrine, Bootstrap is responsible for creating Entitymanager,entitymanager is the entire doctrine external interface: The hidden Database interface, provides the entity query, update and persist.

In bootstrap, the entire doctrine implementation is first loaded using composer's own functionality. (The composer feature is retained here to minimize the introduction of doctrine to CI modifications)

It only takes two steps to create a basic entitymanager:

    1. Use Setup to create a config.
    2. Initializes the database configuration object.

After creating Entitymanager with a database connection object, we may and cannot resist the need to reverse engineer the database from the object. Don't worry, slow down.

<?PHP//bootstrap.phpUse doctrine\orm\tools\setup;use doctrine\orm\entitymanager;use doctrine\common\classloader, Doctrine\DBAL\ Logging\echosqllogger, Doctrine\common\cache\arraycache;date_default_timezone_set ("Asia/shanghai"); Require_once"Vendor/autoload.php";//Database Configuration Parametersif(defined (APPPATH)) {require_once APPPATH.' Config/database.php '; $conn=Array (' Driver ' = ' pdo_mysql ',            ' User ' = $db [' Default '] [' username '],            ' Password ' = $db [' Default '] [' Password '],            ' Host ' = $db [' Default '] [' hostname '],            ' dbname ' = $db [' Default '] ' database ']        );}Else{$conn=Array (' Driver ' = ' pdo_mysql ',    ' User ' = ' root ',    ' Password ' and ' = ',    ' Host ' = ' 127.0.0.1 ',    ' dbname ' = ' doctrine ');}//Below can exected in CLI/*require_once APPPATH. '  Vendor/doctrine/common/lib/doctrine/common/classloader.php '; $doctrineClassLoader = new ClassLoader (' Doctrine ', APPPATH. ' Libraries '); $doctrineClassLoader->register (); $entitiesClassLoader = new ClassLoader (' Models ', RTrim (APPPATH, "/" ); $entitiesClassLoader->register (); $proxiesClassLoader = new ClassLoader (' Proxies ', APPPATH. ' Models/proxies '); $proxiesClassLoader->register ();*///Create a simple ' default ' Doctrine ORM configuration for Annotations$isDevMode =true; $config= Setup::createannotationmetadataconfiguration (Array (__dir__). /models/entities "), $isDevMode);//or if you prefer Yaml or XML//$config = setup::createxmlmetadataconfiguration (Array (__dir__). /config/xml "), $isDevMode);//$config = setup::createyamlmetadataconfiguration (Array (__dir__). /config/yaml "), $isDevMode);$cache=NewArraycache; $config-Setmetadatacacheimpl ($cache); $driverImpl= $config->newdefaultannotationdriver (Array (__dir__. ') /models/entities ') ); $config-Setmetadatadriverimpl ($driverImpl); $config-Setquerycacheimpl ($cache); $config-Setquerycacheimpl ($cache);//Proxy Configuration$config->setproxydir (__dir__. ' /models/proxies '); $config->setproxynamespace (' Proxies ');//Set up Logger//$logger = new Echosqllogger;//$config->setsqllogger ($logger);$configsetautogenerateproxyclasses (TRUE);//obtaining the Entity managerglobal $entityManager; $entityManager= Entitymanager::create ($conn, $config);
View Code

To let Entitymanager know where to use the object for reverse engineering, the following sentence is particularly important:

$config = setupcreateannotationmetadataconfiguration (Array (DIR. " /models/entities "), $isDevMode);

(also mentioned here, when generating the entity from the database, it is also necessary to indicate which folder the entity is placed in, the Entitygenerator object is used, and the folder can be specified when using the Generate method of the object.) )

The official document uses the command line method to reverse engineer, we also leaf out here, then create the necessary Cli-config file. This file is relatively not bootstrap so long, the total public only the following two lines can be:

Requireonce "bootstrap.php"; return Doctrineormtoolsconsoleconsolerunnercreatehelperset ($entityManager);

Reverse engineering uses the Doctrine command in vendor/bin/:

Vendor/bin/doctrine

Among the commonly used are the following:

Vendor/bin/doctrine orm:schema-tool:createvendor/bin/doctrine orm:schema-tool:update--force

NOTES: Adding fields with the update command does not affect the original data.

Well, is it urgent to try, Enter the first create command, eh, bad there is an error "no Metadata Classes to process.", the heart beats faster, calm, it's normal, because we haven't built the entity we want.

establish entity for reverse engineering

1. Build our first entity:Product.php in/models/entities

Note that each of these properties has a protected attribute, which corresponds to a pair of mutator (getter and setter) what is the use of this? The official documentation is used to facilitate doctrine to produce entity, rather than using Entity.field=foo. The specific doctrine how to operate the need for further exploration. There is no setter method for the primary key ID, you know.

2. Now we just define the object, but the database construction is to need some database properties, the class name and the metadata in front of the property is to do this. (defined table name, object property corresponding to database field name and field property)

<?PHP//src/product.php/** * @Entity @Table (name= "Products") **/classproduct{/** @Id @Column (type= "integer") @GeneratedValue **/    protected $id; /** @Column (type= "string") **/    protected $name;  Public functiongetId () {return $this-ID; }     Public functionGetName () {return $this-name; }     Public functionSetName ($name)    {        $this->name =$name; }}

3. Below we can use the following command to reverse engineer, is not very excited!

Vendor/bin/doctrine orm:schema-tool:update--force--dump-sql

4. Let's build a script to build a product and insert it into the data (persist), and you'll find out how to object-oriented and hide the database operations.

  1. <?PHPrequire_once"Bootstrap.php";$newProductName=$argv[1];$product=NewProduct ();$product->setname ($newProductName);$entityManager->persist ($product);$entityManager-Flush();Echo"Created Product with ID".$product->getid (). "\ n";

5. Below we will use the CLI to run this PHP script to invoke the ORM framework to insert the product.

    1. $$ php createproduct.php Dbal

Check the database, is not found that the new data has been inserted, OK is done.

Introduction of ORM Doctrine under CodeIgniter

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.