Home
Doctrine - Open Source PHP ORM
Contents
1. Sqlite Download To get started first download the latest Doctrine sandbox package http www phpdoctrine org download Second extract the downloaded file and you should have a directory named Doctrine x x x Sandbox Inside of that directory is a simple example implementation of a Doctrine based web application Package Contents The files directory structure should look like the following cd Doctrine 0 10 1 Sandbox Listing ls config php doctrine index php migrations schema data doctrine php lib models The sandbox does not require any configuration it comes ready to use with a sqlite database Below is a description of each of the files directories and what its purpose is e doctrine Shell script for executing the command line interface Run with doctrine to see a list of command or Idoctrine help to see a detailed list of the commands e doctrine php Php script which implements the Doctrine command line interface which is included in the above doctrine 1 http ww phpdoctrine org download SENSIOLABS gt Chapter 1 My First Project 4 shell script index php Front web controller for your web application e migrations Folder for your migration classes e schema Folder for your schema files e models Folder for your model files e lib Folder for the Doctrine core library files Running the CLI If you execute the doctrine shell script from the command line it will output the followin
2. gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt symfony doctrine dql frontend FROM BlogPost p p Tags t doctrine executing FROM BlogPost p p Tags t doctrine body symfony and Doctrine are great doctrine doctrine id 1 doctrine title symfony Doctrine doctrine author Jonathan H Wage doctrine slug symfony doctrine doctrine Tags doctrine doctrine id 1 doctrine name symfony doctrine doctrine id 2 doctrine name doctrine doctrine doctrine id 3 doctrine name php Setup Migration Now what if a few months later you want to change the schema to split out the BlogPost author column to an Author model that is related to BlogPost author id First lets add the new model to your config doctrine schema yml Replace your schema yaml with the schema information from below Bl ogPost actAs Sluggable fields title columns title string 255 body clob author string 255 author_id integer relations Author foreignAlias BlogPosts Tags class Tag refClass BlogPostTag foreignAlias BlogPosts SENSIOLABS X Chapter 3 symfony 1 1 and Doctrine Migrations 19 BlogPostTag columns blog post id type integer primary true tag_id type integer primary true Tag columns name string 255 Author columns name string 255 Rebuild your models now with the following command symfony doctrine build model Listin
3. Listing mkdir symfony1 1Doctrine cd symfonyl 1Doctrine path to symfony generate project symfonyl 1Doctrine svn co http svn symfony project com plugins sfDoctrinePlugin trunk plugins sfDoctrinePlugin php symfony cc Now type the following command to list all the new commands that sfDoctrinePlugin provides You will notice that it gives you all the same commands as sfPropelPlugin and lots more Listin php symfony list doctrine lt Available tasks for the doctrine namespace build all Generates Doctrine model SQL and initializes the database doctrine build all build all load Generates Doctrine model SQL initializes database and load data doctrine build all load build all reload Generates Doctrine model SQL initializes database and load data doctrine build all reload build all reload test all Generates Doctrine model SQL initializes database load data and run all test suites doctrine build all reload test all build db Creates database for current model doctrine build db build forms Creates form classes for the current model doctrine build forms build model Creates classes for the current model doctrine build model build schema Creates a schema xml from an existing database doctrine build schema build sql Creates SQL for the current model doctrine build sql data dump Dumps data to the fixtures directory doctrine dump data data load Loads data from fixtures
4. dql dql id 2 dql username jwage dql password changeme dql Groups dql dql id 2 SENSIOLABS gt Listing 1 9 Chapter 1 My First Project 8 dql name Lead dql dql id 3 dql name Documentation User CRUD Now we can demonstrate how to implement Doctrine in to a super simple module for managing users and passwords Place the following code in your index php and pull it up in your browser You will see the simple application require once config php Doctrine loadModels models module isset REQUEST module REQUEST module users action isset REQUEST action REQUEST action list if module users 4 userld isset REQUEST id amp amp REQUEST id gt O REQUEST id null userTable Doctrine getTable User if userId null user new User else user userTable gt find userld switch action case edit case add echo lt form action index php module users amp action save method POST gt lt fieldset gt lt legend gt User lt legend gt lt input type hidden name id value user gt id u J gt lt label for username gt Username lt label gt lt input type text name user username value user gt username gt lt label for password gt Password lt label gt lt input type text name user password value user gt password
5. this gt hasColumn username string 255 this gt hasColumn password string 255 public function setUp SENSIOLABS YY Chapter 5 Plug and Play Schema Information With Templates 30 this gt actAs Address Now we also have a Company model which also must contain an address Listing class Company extends Doctrine Record public function setTableDefinition this gt hasColumn name string 255 this gt hasColumn description clob public function setUp this gt actAs Address Now lets generate the SQL to create the tables for the User and Company model You will see that the attributes from the template are automatically added to each table Listing CREATE TABLE user id BIGINT AUTO INCREMENT 2 username VARCHAR 255 password VARCHAR 255 address1l VARCHAR 255 address2 VARCHAR 255 address3 VARCHAR 255 city VARCHAR 255 state VARCHAR 2 zipcode VARCHAR 15 PRIMARY KEY id ENGINE INNODB CREATE TABLE company id BIGINT AUTO INCREMENT name VARCHAR 255 description LONGTEXT address1l VARCHAR 255 address2 VARCHAR 255 address3 VARCHAR 255 city VARCHAR 255 state VARCHAR 2 zipcode VARCHAR 15 PRIMARY KEY id ENGINE INNODB That s it Now you can maintain your Address schema information from one place and use the address functionality in as many places as you like SENSIOLABS gt Chapter 6 Taking Advantage of Column
6. Aggregation Inheritance 31 Chapter 6 Taking Advantage of Column Aggregation Inheritance First let me give a brief explanation of what column aggregation inheritance is and how it works With column aggregation inheritance all classes share the same table and all columns must exist in the parent Doctrine is able to know which class each row in the database belongs to by automatically setting a type column so that Doctrine can cast the correct class when hydrating data from the database Even if you query the top level column aggregation class the collection will return instances of the class that each row belongs to Now that you have a basic understand of column aggregation inheritance lets put it to use In this example we will setup some models which will allow us to use one address table for storing all of our addresses across the entire application Any record will be able to have multiple addresses and all the information will be stored in one table First lets define our Address class Address extends Doctrine Record Listing public function setTableDefinition this gt hasColumn address1 string 255 this gt hasColumn address2 string 255 this gt hasColumn address3 string 255 this gt hasColumn city string 255 this gt hasColumn state string 2 this gt hasColumn zipcode string 15 this gt hasColumn type string 255 this gt hasColumn record_id integer t
7. directory SENSIOLABS YY Chapter 2 symfony 1 1 and Doctrine 11 doctrine load data dql Execute a DQL query and view the results doctrine dql drop db Drops database for current model doctrine drop db generate crud Generates a Doctrine CRUD module doctrine generate crud generate migration Generate migration class doctrine generate migration generate migrations db Generate migration classes from existing database connections doctrine generate migrations db doctrine gen migrations from db generate migrations models Generate migration classes from an existing set of models doctrine generate migrations models doctrine gen migrations from models init admin Initializes a Doctrine admin module doctrine init admin insert sql Inserts SQL for current model doctrine insert sql migrate Migrates database to current specified version doctrine migrate rebuild db Creates database for current model doctrine rebuild db First sfDoctrinePlugin currently requires that at least one application be setup so lets just instantiate a frontend application now php symfony generate app frontend Listing Setup Database Now lets setup our database configuration in config databases yml Open the file in your favorite editor and place the YAML below inside For this test we are simply using a SQLite database Doctrine is able to create the SQLite database at the config doctrine db path for you which w
8. gt lt input type submit name save value Save gt lt fieldset lt form gt break case save user gt merge REQUEST user user gt save header location index php module users amp action edit amp id user gt id break case delete user gt delete SENSIOLABS X Chapter 1 My First Project 9 header location index php module users amp action List break default query new Doctrine Query query gt from User u gt orderby u username users query gt execute echo lt ul gt foreach users as user echo lt li gt lt a href index php module users amp action edit amp id user gt id gt user gt username lt a gt amp nbsp lt a href index php module users amp action delete amp id user gt id gt X lt a gt lt li gt echo lt ul gt echo lt ul gt lt li gt lt a href index php module usersgaction add gt Add lt a gt lt li gt lt li gt lt a href index php module users amp action List gt List lt a gt lt li gt lt ul gt else throw new Exception Invalid module SENSIOLABS X Chapter 2 symfony 1 1 and Doctrine 10 Chapter 2 symfony 1 1 and Doctrine So you want to give Doctrine a try with symfony 1 1 eh First we will need to setup a new symfony 1 1 project and install the sfDoctrinePlugin for 1 1 Execute the following commands below and continue reading Setup
9. local gt record id foreign gt id Now lets define our Company and link it to the CompanyAddress model so it can have multiple addresses class Company extends Doctrine Record public function setTableDefinition i this gt hasColumn name string 255 public function setUp this gt hasMany CompanyAddress as Addresses array local gt oe foreign gt record id SENSIOLABS X Chapter 6 Taking Advantage of Column Aggregation Inheritance 33 Now both Users and Companies can have multiple addresses and the data is all stored in one address table Now lets create the tables and insert some records Doctrine createTablesFromArray array User Company Address Listing user new User user gt username jwage user gt password changeme user gt Addresses 0 gt address1 123 Road Dr user gt Addresses 0 gt city Nashville user gt Addresses 0 gt state TN user gt save company new Company company gt name centre source company gt Addresses 0 gt address1 123 Road Dr company gt Addresses 0 gt city Nashville company gt Addresses 0 gt state TN company gt save Query for the user and its addresses users Doctrine Query create Listing gt from User u is gt leftJoin u Addresses a gt execute echo users 0 gt username jwage echo users 0 gt Addr
10. multiple Doctrine classes without having to duplicate any code Below we will show some examples of what a template could be used for and how it can make your schema easier to maintain Let s get started Imagine a project where you have multiple records which must have address attributes Their are two basic approaches to solving this problem One is to have a single table to store all addresses and each record will store a foreign key to the address record it owns This is the normalized way of solving the problem The de normalized way would be to store the address attributes with each record In this example a template will extract the attributes of an address and allow you to plug them in to as many Doctrine classes as you like First we must define the template so that we can use it in our Doctrine classes class Doctrine Template Address extends Doctrine Template Listing public function setTableDefinition this gt hasColumn address1 string 255 this gt hasColumn address2 string 255 this gt hasColumn address3 string 255 this gt hasColumn city string 255 this gt hasColumn state string 2 this gt hasColumn zipcode string 15 Now that we have our template defined lets define some basic models that need to have address attributes added to them Lets start first with a User class User extends Doctrine Record Listing 5 2 public function setTableDefinition
11. schema and data changes without having to manually write or keep up with SQL statements Database migrations essentially allow you to have multiple versions of your schema A single Doctrine migration class represents one version of the schema Each migration class must have an up and a down method defined and the down must negate everything done in the up method Below I will show you an example of how to use Doctrine to control your database This tutorial is written for symfony 1 1 but the same functionality exists for the 1 0 version of sfDoctrinePlugin but in the 1 0 style task system Setting up your database First thing we need to do is define your database and create it Edit config databases yml and setup your mysql database Copy and paste the yaml below in to the file all doctrine class sfDoctrineDatabase param dsn mysql Define your schema In this example we are going to use a traditional Blog model Open config doctrine schema yml and copy and paste the yaml contents from below in to the file BlogPost actAs SENSIOLABS X Chapter 3 symfony 1 1 and Doctrine Migrations 17 Sluggable fields title columns title string 255 body clob author string 255 relations Tags class Tag refClass BlogPostTag foreignAlias BlogPosts BlogPostTag columns blog post id type integer primary true tag_id type integer primary true Tag columns name string 255 Place th
12. will automatically perform the migration process and update the database Run Migration symfony doctrine migrate frontend Listing gt gt doctrine migrated successfully to version 2 T Now the database is updated with the new schema information and data migrated Give it a check and you will see that we have a new author table the blog post author column is gone and we have a new blog post author id column that is set to the appropriate author id value The 2 migration removed the author column from the blog post table but we left it in the model definition so that while it still existed before the 2 migration began we copied the contents of the author column to the author table and related the blog post to the author id You can now remove the author string 255 column definition from the config doctrine schema yml and rebuild the models Here is the new BlogPost model definition e Listing BlogPost actAs Sluggable fields title columns title string 255 body clob author_id integer relations Author foreignAlias BlogPosts Tags class Tag refClass BlogPostTag foreignAlias BlogPosts Re build the models now since we removed the author column from the model definition and the table in the database symfony doctrine build model Listing gt gt doctrine Generated models successfully bd Now lets run a DQL query from the command line to see the final product symfony doctrine dql fronten
13. S doctrine Doctrine 1 1 License Creative Commons Attribution Share Alike 3 0 Unported License Version cookbook 1 1 pt_BR 2010 04 19 SENSIOLABS X Table of Contents ii Table of Contents MY First POCA a A AAA AA ARA RARA AP A eso ealascnenaadinanes DOWN AN AAN A A Package Contents Running the CLI Defining Schema T st Data FIXtUTES cid baaa pi B ildin Everything ideas RUNNING TESS a User CRUDA E E das 0 dd UU HH uuu uy f 1 1 and D i 10 symfony 1 1 and Doctrine nin a Sra trdotendon n o a a a aerae L Setup Database ainia tada Ll S tup SCA rra LA Build Dotar LA Admin Generators iaa LO AP AAA LA symfony 1 1 and Doctrine Migrations ssssesssossesssossesssossesssossesseossesseossessse LO Setting up your datar LO Dele your sch ma daras LO Build Dita dd A A LO R n Migrati n A e A A s Code Igniter and Doce lt a 08 Download Doctrine dia SCUD DOCM dnd dd diia Setup Command Line Interaccion Start Using DOS Aia Plug and Play Schema Information With Templates ccssssscssssseeeeees 29 Taking Advantage of Column Aggregation Inheritance csssscsssseessees OL SENSIOLABS X Chapter 1 My First Project 3 Chapter 1 My First Project Introduction This is a tutorial amp how to on creating your first project using the fully featured PHP Doctrine ORM This tutorial uses the the ready to go Doctrine sandbox package It requires a web server PHP and PDO
14. act class BaseUser extends Doctrine Record public function setTableDefinition this gt setTableName user this gt hasColumn id integer 4 array primary gt true autoincrement gt true this gt hasColumn username string 255 this gt hasColumn password string 255 public function setUp this gt hasMany Group as Groups array refClass gt UserGroup local gt user id foreign gt group id this gt hasMany UserGroup array local gt id foreign gt user id Add custom methods to system application models User php This class has been auto generated by the Doctrine ORM Framework class User extends BaseUser public function setPassword password 1 this gt password md5 password This class has been auto generated by the Doctrine ORM Framework my class UserTable extends Doctrine Table public function retrieveALl query new Doctrine Query query gt from User u query gt orderby u username ASC return query gt execute SENSIOLABS X Listing 4 16 Listing 4 17 Listing 4 18 Listing 4 19 Chapter 4 Code Igniter and Doctrine 28 Now we can create some sample data to load in to our application this step requires you have a valid database configured and ready to go The build all reload task will drop and recreate the database create tables and load data fi
15. bout Doctrine Full User Manual http www phpdoctrine org documentation manual 0 11 one page API Documentation http www phpdoctrine org documentation api 0 11 E Cheatsheet http www phpdoctrine org Doctrine Cheat Sheet pdf Blog http www phpdoctrine org blog Community http www phpdoctrine org community Frequently Asked Questions http www phpdoctrine org faq Download http www phpdoctrine org download 4 http ww phpdoctrine org documentation manual 0 11 chapter dql doctrine query Language 5 http www phpdoctrine org documentation manual 0 11 chapter basic schema mapping constraints and validators 6 http www phpdoctrine org documentation manual O 11 chapter hierarchical data 7 http www phpdoctrine org documentation manual 0 11 chapter caching 8 http www phpdoctrine org documentation manual 0 11 0ne page 9 http www phpdoctrine org documentation api O 11 10 11 12 13 14 http www phpdoctrine org Doctrine Cheat Sheet pdf http www phpdoctrine org blog http www phpdoctrine org community http www phpdoctrine org faq http www phpdoctrine org download SENSIOLABS X Listing 3 1 Listing 3 2 Listing Chapter 3 symfony 1 1 and Doctrine Migrations 16 Chapter 3 symfony 1 1 and Doctrine Migrations The PHP Doctrine ORM offers a fully featured database migration utility that makes it easy to upgrade your databases for both
16. d FROM BlogPost p p Tags p Author a Listing gt gt doctrine executing FROM BlogPost p p Tags p Author a a gt gt doctrine gt gt doctrine id 1 gt gt doctrine title symfony Doctrine gt gt doctrine body symfony and Doctrine are great gt gt doctrine author_id 1 gt gt doctrine slug symfony doctrine gt gt doctrine Tags SENSIOLABS X Chapter 3 symfony 1 1 and Doctrine Migrations gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt doctrine doctrine doctrine doctrine doctrine doctrine doctrine doctrine doctrine doctrine doctrine doctrine id 1 name symfony id 2 name doctrine id 3 name php Author id 1 name Jonathan H Wage 22 If you compare the data returned here to the data that was returned in the beginning of this tutorial you will see that the author column was removed and migrated to an Author model SENSIOLABS gt Chapter 4 Code Igniter and Doctrine 23 Chapter 4 Code Igniter and Doctrine This tutorial will get you started using Doctrine with Code Igniter Download Doctrine First we must get the source of Doctrine from svn and place it in the system database folder cd system database Listing svn co http svn phpdoctrine org branches 0 11 lib doctrine f cd If you use svn in your project you can set Doctrine as an external so you receive bug fixes aut
17. e below data fixtures in to data fixtures data yml eee Listing BlogPost BlogPost_1 slug symfony doctrine author Jonathan H Wage title symfony Doctrine body symfony and Doctrine are great Tags symfony doctrine php Tag symfony name symfony doctrine name doctrine php name php Build Database Now with one simple command Doctrine is able to create the database the tables and load the data fixtures for you Doctrine works with any PDO http www php net pdo driver and is able to drop and create databases for any of them symfony doctrine build all reload frontend Listing 3 5 gt gt doctrine Are you sure you wish to drop your databases y n y 15 http www php net pdo SENSIOLABS YY Listing 3 6 Listing 3 7 Chapter 3 symfony 1 1 and Doctrine Migrations gt gt do gt gt do gt gt gt gt gt gt 18 doctrine Successfully dropped database f 1 1Doctrine config ctrine db doctrine Successfully created database f 1 1Doctrine config ctrine db doctrine Generated models successfully doctrine Created tables successfully doctrine Data was successfully loaded Now your database models and tables are created for you so easily Lets run a simple DQL query to see the current data that is in the database so we can compare it to the data after the migration has been performed gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt gt
18. e located at a url like the following SENSIOLABS gt Chapter 2 symfony 1 1 and Doctrine 14 Listing http localhost symfony1 1Doctrine web frontend_dev php blog_posts http localhost symfony1 1Doctrine web frontend_dev php tags Now with a little configuration of the blog post admin generator we can control the associated blog post tags by checking checkboxes when editing a blog post Open apps frontend modules blog posts config generator yml and replace the contents with the YAML from below Listing 2 11 generator class sfDoctrineAdminGenerator param model class BlogPost theme default list display title author object actions _edit _delete edit display author title body Tags fields author type input tag title type input tag body type textarea_tag params size 50x10 Tags type doctrine admin check list params through class BlogPostTag Now refresh the blog post list and you will see it is cleaned up a little bit Edit a blog post by clicking the edit icon or the title and you can see below you can check the tags associated to the blog post All of the features you get in Propel work 99 the same way with Doctrine so it should be fairly easy to get the hang of if you are coming from propel sfDoctrinePlugin implements all the same functionality as sfPropelPlugin as well as several additional features which sfPropelPlugin is not capable of Below you can find some more informa
19. e will do once we setup our schema and some data fixtures ria Listing all doctrine class sfDoctrineDatabase param dsn sqlite Setup Schema Now that we have our database configured lets define our YAML schema files in config doctrine schema yml In this example we are setting up a simple BlogPost model which hasMany Tags De Listing BlogPost ai actAs Sluggable fields title SENSIOLABS X Listing 2 6 Listing 2 7 Chapter 2 symfony 1 1 and Doctrine 12 Timestampable columns title string 255 body clob author string 255 relations Tags class Tag refClass BlogPostTag foreignAlias BlogPosts BlogPostTag columns blog post id type integer primary true tag_id type integer primary true Tag actAs Timestampable columns name string 255 Now that we have our Doctrine schema defined lets create some test data fixtures in data fixtures data yml Open the file in your favorite editor and paste the below YAML in to the file BlogPost BlogPost_1 title symfony Doctrine body symfony and Doctrine are great author Jonathan H Wage Tags symfony doctrine php Tag symfony name symfony doctrine name doctrine php name php Build Database Ok now for the fun stuff We have our schema and we have some data fixtures so lets run one single Doctrine command and create your database generate your models create tables and load the data fixtu
20. esses 0 gt addressl1 123 Road Dr echo get_class users 0 gt Addresses 0 UserAddress Query for the company and its addresses companies Doctrine Query create Listing gt from Company c es gt leftJoin c Addresses a gt execute echo companies 0 gt name centre source echo companies 0 gt Addresses 0 gt addressl 123 Road Dr echo get_class companies 0 gt Addresses 0 CompanyAddress Now lets query the Addresses directly and you will notice each child record returned is hydrated as the appropriate child class that created the record initially addresses Doctrine Query create Listing gt from Address a e9 gt execute echo get_class addresses 0 UserAddress echo get _class addresses 1 CompanyAddress SENSIOLABS gt
21. fixtures folder aes Listing User dl zyne username zYne password changeme Groups founder lead documentation jwage username jwage password changeme Groups lead documentation Group founder name Founder lead name Lead documentation name Documentation Building Everything Now that you have written your schema files and data fixtures you can now build everything and begin working with your models Run the command below and your models will be generated in the models folder doctrine build all reload Listing build all reload Are you sure you wish to drop your databases y n i y SENSIOLABS X Chapter 1 My First Project 6 build all reload Successfully dropped database for connection sandbox at path Users jwage Sites doctrine branches 0 10 tools sandbox sandbox db build all reload Generated models successfully from YAML schema build all reload Successfully created database for connection sandbox at path Users jwage Sites doctrine branches 0 10 tools sandbox sandbox db build all reload Created tables successfully build all reload Data was successfully loaded Take a peak in the models folder and you will see that the model classes were generated for you Now you can begin coding in your index php to play with Doctrine itself Inside index php place some code like the following for a simple test Running Tests Listing query new Doctrine Query 1 6 query
22. g et doctrine Doctrine Command Line Interface doctrine build all doctrine build all load doctrine build all reload doctrine compile doctrine create db doctrine create tables doctrine dql doctrine drop db doctrine dump data doctrine generate migration doctrine generate migrations db doctrine generate migrations models doctrine generate models db doctrine generate models yaml doctrine generate sql doctrine generate yaml db doctrine generate yaml models doctrine load data doctrine migrate doctrine rebuild db Defining Schema Below is a sample yaml schema file to get started You can place the yaml file in schemas schema yml The command line interface looks for all yml files in the schemas folder Listing 2 User columns id primary true autoincrement true type integer 4 username string 255 password string 255 relations Groups class Group refClass UserGroup SENSIOLABS gt Chapter 1 My First Project 5 foreignAlias Users Group tableName groups columns id primary true autoincrement true type integer 4 name string 255 UserGroup columns user id integer 4 group id integer 4 relations User onDelete CASCADE Group onDelete CASCADE Test Data Fixtures Below is a sample yaml data fixtures file You can place this file in data fixtures data yml The command line interface looks for all yml files in the data
23. g gt gt doctrine Generated models successfully i As you see we have added a new Author model and changed the author column to author id and integer for a foreign key to the Author model Now lets write a new migration class to upgrade the existing database without losing any data Run the following commands to create skeleton migration classes in lib migration doctrine You will see a file generated named 001 add author class php and 002 migrate author class php Inside them are blank up and down method for you to code your migrations for the schema changes above symfony doctrine generate migration frontend AddAuthor Listing gt gt doctrine Generated migration class AddA Doctrine lib migration 53 doctrine symfony doctrine generate migration frontend MigrateAuthor gt gt doctrine Generated migration class Migr Doctrine lib migration doctrine Now we have 2 blank migration skeletons to write our migration code in Below I have provided the code to migrate the author column to an Author model and automatically relate blog posts to the newly created author id 001 add author class php Listing 3 10 This class has been auto generated by the Doctrine ORM Framework class AddAuthor extends Doctrine_Migration public function up Create new author table columns array id gt array type gt integer length gt 4 autoincrement gt true name gt array type gt stri
24. gt from User u u Groups g users query gt execute echo lt pre gt print_r users gt toArray true The print r should output the following data You will notice that this is the data that we populated by placing the yaml file in the data fixtures files You can add more data to the fixtures and rerun the build all reload command to reinitialize the database Listing a Array 0 gt Array id gt 1 username gt zYne password gt changeme Groups gt Array 0 gt Array id gt 1 name gt Founder 1 gt Array id gt 2 name gt Lead 2 gt Array id gt 3 name gt Documentation SENSIOLABS gt Chapter 1 My First Project 7 1 gt Array id gt 2 username gt jwage password gt changeme Groups gt Array 0 gt Array id gt 2 name gt Lead 1 gt Array id gt 3 name gt Documentation You can also issue DQL queries directly to your database by using the dql command line function It is used like the following jwage sandbox jwage doctrine dql FROM User u u Groups g Listing dql executing FROM User u u Groups g ad dql dql id 1 dql username zYne dql password changeme dql Groups dql dql id 1 dql name Founder dql dql id 2 dql name Lead dql dql id 3 dql name Documentation
25. hema cli new Doctrine Cli config cli gt run SERVER argv Now we must create all the directories for Doctrine to use Create directory for your yaml data fixtures files Listing mkdir system application fixtures i Create directory for your migration classes mkdir system application migrations Create directory for your yaml schema files mkdir system application schema Create directory to generate your sql to create the database in mkdir system application sql Now you have a command line interface ready to go If you execute the doctrine shell script with no argument you will get a list of available commands cd system application Listing doctrine i Doctrine Command Line Interface doctrine build all doctrine build all load doctrine build all reload doctrine compile doctrine create db doctrine create tables doctrine dql doctrine drop db doctrine dump data doctrine generate migration doctrine generate migrations db doctrine generate migrations models doctrine generate models db doctrine generate models yaml doctrine generate sql doctrine generate yaml db doctrine generate yaml models doctrine load data doctrine migrate doctrine rebuild db On Microsoft Windows call the script via the PHP binary because the script won t invoke it automatically php exe doctrine Listing SENSIOLABS X Listing 4 13 Listing 4 14 Chap
26. his gt option export tables this gt setSubClasses array UserAddress gt array type gt UserAddress CompanyAddress gt array type gt CompanyAddress Note the option set above to only export tables because we do not want to export any foreign key constraints since record id is going to relate to many different records We are going to setup a User so it can have multiple addresses so we will need to setup a UserAddress child class that User can relate to SENSIOLABS gt Listing 6 2 Listing 6 3 Listing 6 4 Listing 6 5 Chapter 6 Taking Advantage of Column Aggregation Inheritance 32 class UserAddress extends Address 1 public function setUp 1 this gt hasOne User array local gt record_id foreign gt id Now lets define our User and link it to the UserAddress model so it can have multiple addresses class User extends Doctrine Record public function setTableDefinition this gt hasColumn username string 255 this gt hasColumn password string 255 public function setUp this gt hasMany UserAddress as Addresses array local gt id foreign gt record id Now say we have a Company record which also needs ot have many addresses First we need to setup the CompanyAddress child class class CompanyAddress extends Address public function setUp this gt hasOne Company array
27. ng length gt 255 SENSIOLABS X Chapter 3 symfony 1 1 and Doctrine Migrations 20 this gt createTable author columns array primary gt array id Add author_id to the blog post table this gt addColumn blog post author id integer array length gt 4 public function down Remove author table this gt dropTable author Remove author_id column from blog post table this gt removeColumn blog post author id 002 migrate author class php This class has been auto generated by the Doctrine ORM Framework class MigrateAuthor extends Doctrine Migration public function preUp 1 q Doctrine Query create gt select p id p author gt from BlogPost p blogPosts q gt execute foreach blogPosts as blogPost author Doctrine getTable Author gt findOneByName bLogPost gt author if author instanceof Author amp amp author gt exists author new Author author gt name blogPost gt author author gt save blogPost gt author id author gt id blogPost gt save public function up this gt removeColumn blog post author public function down this gt addColumn blog post author string array length gt 255 SENSIOLABS X Chapter 3 symfony 1 1 and Doctrine Migrations 21 Now run the following command and Doctrine
28. omatically from svn svn propedit svn externals database In your favorite editor add the following line doctrine http svn phpdoctrine org branches 0 11 lib Setup Doctrine Now we must setup the configuration for Doctrine and load it in system application config database php vi application config database php Listing The code below needs to be added under this line of code db default cachedir Listing Add this code Create dsn from the info above Listing 4 4 db default dsn db default dbdriver db default username db default password a db default hostname db default database Require Doctrine php require once realpath dirname _ FILE DIRECTORY SEPARATOR database doctrine Doctrine php SENSIOLABS gt Listing 4 5 Listing 4 6 Listing 4 7 Listing 4 8 Listing 4 9 Chapter 4 Code Igniter and Doctrine 24 Set the autoloader spl_autoload register array Doctrine autoload Load the Doctrine connection Doctrine Manager connection db default dsn db default database Set the model loading to conservative lazy loading Doctrine Manager getInstance gt setAttribute model loading conservative Load the models for the autoloader Doctrine loadModels realpath dirname FILE DIRECTORY SEPARATOR models Now we must make sure system a
29. pplication config database php is included in your front controller Open your front controller in your favorite text editor cd vi index php Change the last 2 lines of code of index php with the following require once APPPATH config database php require once BASEPATH codeigniter CodeIgniter EXT Setup Command Line Interface Create the following file system application doctrine and chmod the file so it can be executed Place the code below in to the doctrine file vi system application doctrine Place this code in system application doctrine usr bin env php define BASEPATH mockup that this app was executed from ci chdir dirname _ FILE include doctrine php Now create the following file system application doctrine php Place the code below in to the doctrine php file require once config database php Configure Doctrine Cli Normally these are arguments to the cli tasks but if they are set here the arguments will be auto filled config array data fixtures path gt dirname _ FILE DIRECTORY SEPARATOR fixtures models path gt dirname _ FILE_ DIRECTORY SEPARATOR models migrations path gt dirname _ FILE_ DIRECTORY SEPARATOR migrations sql_path gt dirname __FILE_ SENSIOLABS gt Chapter 4 Code Igniter and Doctrine 25 DIRECTORY SEPARATOR sql yaml_schema_path gt dirname __FILE_ DIRECTORY SEPARATOR sc
30. res php symfony doctrine build all reload frontend gt gt doctrine Are you sure you wish to drop your databases y n y gt gt doctrine Successfully dropped database f 1 1Doctrine config doctrine db SENSIOLABS X Chapter 2 symfony 1 1 and Doctrine 13 gt gt doctrine Successfully created database f 1 1Doctrine config doctrine db gt gt doctrine Generated models successfully gt gt doctrine Created tables successfully gt gt doctrine Data was successfully loaded Now your doctrine db SQLite database is created all the tables for your schema were created and the data fixtures were populated in to the tables Now lets do a little playing around with the data to see how we can use the Doctrine Query Language to retrieve data php symfony doctrine dql frontend FROM BlogPost p p Tags t Listing gt gt doctrine executing FROM BlogPost p p Tags t gt gt doctrine gt gt doctrine id 1 gt gt doctrine title symfony Doctrine gt gt doctrine body symfony and Doctrine are great gt gt doctrine author Jonathan H Wage gt gt doctrine slug symfony doctrine gt gt doctrine created at 2008 06 16 12 28 57 gt gt doctrine updated at 2008 06 16 12 28 57 gt gt doctrine Tags gt gt doctrine gt gt doctrine id 1 gt gt doctrine name symfony gt gt doctrine created at 2008 06 16 12 28 57 gt gt doctrine updated at 2008 06 16 12 28 57 gt gt doct
31. rine gt gt doctrine id 2 gt gt doctrine name doctrine gt gt doctrine created at 2008 06 16 12 28 57 gt gt doctrine updated at 2008 06 16 12 28 57 gt gt doctrine gt gt doctrine id 3 gt gt doctrine name php gt gt doctrine created at 2008 06 16 12 28 57 gt gt doctrine updated at 2008 06 16 12 28 57 Now lets do a little explaining of the data that was returned As you can see the models have a created at updated at and slug column which were not defined in the schema files These columns are added by the behaviors attached to the schema information under the actAs setting The created at and updated at column are automatically set onInsert and onUpdate and the slug column is a url friendly string that is created from the value of the name column Doctrine has a few behaviors that are included in core such as Sluggable and Timestampable but the behavior system is built to allow anyone to easily write behaviors for their models to re use over and over Admin Generators Now we have our data model all setup and populated with some test fixtures so lets generate an admin generator to manage the blog posts and tags php symfony doctrine init admin frontend blog posts BlogPost Listing php symfony doctrine init admin frontend tags Tag p Now go open up your web browser and check out the frontend application and the blog posts and tags modules It should b
32. ter 4 Code Igniter and Doctrine Start Using Doctrine 26 It is simple to start using Doctrine now First we must create a yaml schema file save it at schema with filename like user yml User columns id primary true autoincrement true type integer 4 username string 255 password string 255 relations Groups class Group class name local user id foreign group id refClass UserGroup foreignAlias Users hasMany Users Group tableName groups columns id primary true autoincrement true type integer 4 name string 255 UserGroup columns user id type integer 4 primary true group id type integer 4 primary true relations User local user id foreign id onDelete CASCADE Group local group id foreign id onDelete CASCADE Class name Optional if alias is the Local Foreign xRefClass for relating Users to Groups Opposite relationship alias Group Local key Foreign key Database constraint Now if you run the following command it will generate your models in system application models doctrine generate models yaml generate models yaml Generated models successfully from YAML schema SENSIOLABS X Chapter 4 Code Igniter and Doctrine 27 Now check the file system application models generated BaseUser php You will see a compclass definition like below Listing This class has been auto generated by the Doctrine ORM Framework a abstr
33. tion on the major features that Doctrine supports Helpful Links e Behaviors http www phpdoctrine org documentation manual 01 1 chapter plugins Easily create reusable behaviors for your Doctrine models e Migrations http www phpdoctrine org documentation manual 0 11 chapter migration Deploy database schema changes to your production environment through a programmatic interface 3 2 http www phpdoctrine org documentation manual 0 11 chapter plugins 3 http www phpdoctrine org documentation manual O 11 chapter migration SENSIOLABS gt Chapter 2 symfony 1 1 and Doctrine Doctrine Query Language http www phpdoctrine org documentation manual 01 1 chapter dql doctrine query language Build your database queries through a fluent OO interface Validators http www phpdoctrine org documentation manual 0 11 chapter basic schema mapping constraints and validators Turn on column validators for both database and code level validation Hierarchical Data http www phpdoctrine org documentation manual 01 1 chapter hierarchical data Turn your models in to nested sets easily with the flip of a switch Caching http www phpdoctrine org documentation manual 0 1 1 chapter caching Tune performance by caching your DQL query parsing and the result sets of queries 15 If this short tutorial sparked your interest in Doctrine you can check out some other Doctrine resources below to learn more a
34. xtures Create a file in system application fixtures users yml vi fixtures users yml Add the following yaml to the file User jwage username jwage password test Now run the build all reload task to drop db build models recreate doctrine build all reload build all reload Are you sure you wish to drop your databases y n y build all reload Successfully dropped database named jwage codeigniter build all reload Generated models successfully from YAML schema build all reload Successfully created database named jwage codeigniter build all reload Created tables successfully build all reload Data was successfully loaded Now we are ready to use Doctrine in our actual actions Lets open our system application views welcome message php and somewhere add the following code somewhere user new User user gt username zYne user gt setPassword password user gt save userTable Doctrine getTable User user userTable gt find0neByUsername zYne echo user gt username prints zYne users userTable gt retrieveAll echo users gt count echo 2 foreach users as user echo user gt username SENSIOLABS X Chapter 5 Plug and Play Schema Information With Templates 29 Chapter 5 Plug and Play Schema Information With Templates Doctrine templates essentially allow you to extract schema information so that it can be plugged in to
Download Pdf Manuals
Related Search
Related Contents
User Manual - Automatikprodukter FX2N-4AD USER'S GUIDE Reproductor de Blu TAFCO WINDOWS S2448DIA Installation Guide Relaciones interamericanas - Site langues de l`académie de Dijon Frigidaire 600 Series Dishwasher User Manual White Rodgers SST1000 Air Cleaner User Manual M2Mのベース技術となる Copyright © All rights reserved.
Failed to retrieve file