Introduction of ORMDoctrine and codeigniterorm_PHP in CodeIgniter

Source: Internet
Author: User
Tags autoload composer install
Introduce ORMDoctrine and codeigniterorm under CodeIgniter. ORMDoctrine is introduced in CodeIgniter. codeigniterorm has been developing CI for two years and has been using activeRecord to operate databases. Simple, lightweight, and convenient. The latest project is handed over to CodeIgniter to introduce ORM Doctrine and codeigniterorm.

After two years of CI development, activeRecord has been used to operate databases. Simple, lightweight, and convenient. A recent project was handed over to Alibaba Cloud. it is also a development process starting with database design and is now running online. It has gone through the process of clarifying requirements, designing databases, establishing models and controllers in CI, changing requirements, changing databases, changing code, adding requirements, and changing databases. Looking back, when you need to understand the global code and business logic requirements, you still have to start with the database. suddenly there is an annoying feeling: the attributes of objects are in the database, related operations are very split in the code. Recall that C # and JAVA developed many years ago have some good ORM frameworks. for me, the biggest benefit of ORM is to hide the database and design the object as needed during the preliminary design of the project, with ease, you do not have to go into adding, modifying, deleting, and querying early. you can directly use tools to map objects to the database. database addition, modification, and query are also object-oriented.

Two possible concerns:

  1. Since objects must be automatically mapped to the database, a set of metaData rules must be followed.
  2. Performance problems: the ORM automatically generates SQL statements, and the performance may not be as good as before. However, to compare the readability/maintainability of the framework with a little hardware performance cost, the framework is preferred. In addition, I believe that the performance of ORM 90% has little impact, and a few problems that can not be solved by ORM can also be solved by native SQL. In general, it is more advantageous than a disadvantage.

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

Let's get started. what is our purpose? there is no tooth decay! Well, this is just one of our purposes, but it is still another purpose:

  • Generate a database based on the created object;
  • Added objects to the database for persistence;
  • You can use entity to conveniently query and change the information in the data.
1. install doctrine under CI

A. The latest CI 3.0 supports composer. Create the composer. son file in 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 autoload parameter above is very important, because the entity directory needs to be specified for doctrine startup. The/src directory is given in the original example. Here we put it under the model/entities directory of CI. In addition, at the same time, create the model/generated and models/proxies directories. the generated directory is used to generate the entity from the database, and the proxies directory is used to store the code to be generated by lazy load.

B. install doctrine: composer install. the directory structure after installation is as follows:

  

2. configure bootstrap and cli-config

In doctrine, bootstrap is responsible for creating entityManager. entityManager is an external operation interface provided by the entire doctrine: hides the database interface and provides query, update, and persistence of the entity.

In bootstrap, the built-in functions of composer are used to load the entire doctrine. (The composer function is retained here to minimize the introduction of doctrine to CI)

To create a basic entityManager, only two steps are required:

  1. Use setup to create a config.
  2. Initialize the database configuration object.

After using a database to connect to an object to create an entityManager, we may be able to reverse engineer the database from the object. Come on.

'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' => '', 'host' => '2017. 0.0.1 ', 'dbname' => 'doctrine');} // Below can be 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 = new ArrayCache; $ config-> setmetadatacheimpl ($ cache ); $ driverImpl = $ config-> newDefaultAnnotationDriver (array (_ DIR __. '/models/entities'); $ config-> setMetadataDriverImpl ($ driverImpl); $ config-> setQueryCacheImpl ($ cache ); // Proxy configuration $ config-> setProxyDir (_ DIR __. '/models/proxies'); $ config-> setProxyNamespace ('proxies '); // Set up logger // $ logger = new EchoSQLLogger; // $ config-> setSQLLogger ($ logger); $ config-> setAutoGenerateProxyClasses (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 );

(Here, we also mention that when generating entity from the database, we also need to specify the folder where the entity is to be placed. the EntityGenerator object is used, use the generate method of this object to specify the folder to store .)

The official document uses the command line method for reverse engineering. here we also draw a gourd based on the sample, and then create the necessary cli-config file. This file is not as long as bootstrap, and the total public only has the following two lines:

requireonce "bootstrap.php";return DoctrineORMToolsConsoleConsoleRunnercreateHelperSet($entityManager);

Reverse engineering uses the doctrine command in vendor/bin:

vendor/bin/doctrine

Common examples are as follows:

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

Notes: using the update command to add fields does not affect the original data.

Okay, isn't it urgent to give it a try? enter the first create command, retry. it's hard to see an error "No Metadata Classes to process. ", the heartbeat speed up, calm down, this is normal, because we have not set up the entity we want.

Create entity for reverse engineering

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

Note that each attribute here has the protected attribute, and each corresponding has a pair of mutator (getter and setter). What is the use of this? The official document states that it is used to facilitate doctrine to generate entity, rather than using entity. field = foo. Further exploration is needed on how to operate doctrine. There is no setter method for the primary key Id, you know.

2. now we only define the object, but the database structure requires some database attributes. the metadata before the class name and attribute is used to do this. (Defined table name, database field name and field attribute corresponding to the object attribute)

 id;    }    public function getName()    {        return $this->name;    }    public function setName($name)    {        $this->name = $name;    }}

3. now we can use the following command for reverse engineering. are you very excited!

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

4. next we will build a script to generate a product and insert it into the data (persistence). then you will find out how to object-oriented and hide database operations.

  1.    setName($newProductName);$entityManager->persist($product);$entityManager->flush();echo "Created Product with ID " . $product->getId() . "\n";

5.Next we will use cli to run this php script to call the ORM framework to insert the product.

  1. $ php createproduct.php ORM $ php createproduct.php DBAL

Check the database to see if new data has been inserted. OK.

The introduction of ORM Doctrine under the http://www.bkjia.com/PHPjc/1063520.htmlwww.bkjia.comtruehttp://www.bkjia.com/PHPjc/1063520.htmlTechArticleCodeIgniter, codeigniterorm for two years of CI development, has been using activeRecord to operate the database. Simple, lightweight, and convenient. Hand over the last project...

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.