kohana php object relational mapping guide - Hedan

14 downloads 153 Views 199KB Size Report
After reading through many of the posts within the Kohana PHP forum, plus reading an introduction to ORM on the Kohana PHP Development blog, I decided to ...
Kohana PHP

Object Relational Mapping guide

Written by Sam Clark Version 1.4 (Draft)

http://sam.clark.name

Kohana PHP Object Relational Mapping guide

Contents Introduction

3

Credits and contributions

3

What is this ORM thing anyway?

4

Creating an ORM class

5

Using Customer_Model with Customer_Controller

8

Extending the behaviour of Customer_Model

14

Creating ORM relationships

16

One to many relationship

16

Many to many relationship

18

ORM relationships summary

20

Using ORM relationships in your code

21

find_related

21

add

21

remove

21

Appendix A - Full Files

22

customers.sql

22

customer_addresses.sql

22

addresses.sql

23

customers_addresses.sql

23

application/models/customer.php

24

application/models/customer_address.php

24

application/models/address.php

24

application/controllers/customer.php

25 2

Kohana PHP Object Relational Mapping guide

Introduction The impetus for writing this guide came from discovering there was no real documentation for my favourite feature within Kohana PHP - ORM. ORM delivers a robust data manipulation toolset that provides almost everything you could possibly need to write clean, fast code to do wonderful things. After reading through many of the posts within the Kohana PHP forum, plus reading an introduction to ORM on the Kohana PHP Development blog, I decided to try and finish the missing bits regarding creating relationships. This document originally started as a blog post but as it started to grow, I decided to create a structured document rather than a meandering post. Because of this, sometimes the language in this document is in the first person, sometimes in the third and sometimes the person is missing altogether. For this I can only apologise and say, “it will get better”. This is currently only the first draft and I will update in time - but this will be helped if you help me by telling me what works for you, especially what doesn’t and anything you think I missed out. If you have any comments, just post them on my blog under the “Kohana PHP - ORM guide” post (http://sam.clark.name/2008/03/31/orm-guide/). Hopefully this should help the guys working hard to develop Kohana PHP with some extra documentation in the future. I am a PHP developer based in South London. I have been using and waxing lyrical about Kohana PHP for the last four months on my blog (http://sam.clark.name), as well as on the geekUp mailing list. I was inspired to write this document after reading “Kohana’s ORM - a brief introduction” at http://learn.kohanaphp.com/2008/02/14/kohanas-orm-a-brief-introduction/. You can read more about ORM at http://doc.kohanaphp.com/libraries/orm .

Credits and contributions Proof reading and error correction by phelz Further proof reading and error corrections by atomless and Louis

Licence

Kohana PHP Object Relational Mapping Guide by Sam Clark is licensed under a Creative Commons Attribution-Non-Commercial-Share Alike 2.0 UK: England & Wales License. Based on a work at learn.kohanaphp.com.

3

Kohana PHP Object Relational Mapping guide

What is this ORM thing anyway? ORM (Object Relational Mapping) is an object that mirrors data within a database. The idea of an Object Relational Mapping is to allow manipulation and control of data within a DB as though it was a PHP object. You may be thinking that this is just a database abstraction layer and you wouldn’t be entirely wrong. But ORM goes further than just removing SQL code from your PHP code, it allows you to tailor how data moves to and from different tables within your Database. Using ORM within your code allows you to pull data from your database, manipulate the data in any way you like and then save the result back to the database without one line of SQL. It goes further by providing methods for maintaining relationships across tables (joins) and finding data by criteria. ORM will even automatically save your object back database if you wish it too. This document provides a very basic introduction to ORM for the uninitiated. Once ORM is explained, I move on to the more complex task of creating relationships between models. The assumption is that you are already familiar with PHP and MySQL, as well as the Kohana PHP framework.

4

Kohana PHP Object Relational Mapping guide

Creating an ORM class How does one create an ORM class to use in Kohana? First you will need to create your table within your database. If you’re planning to use ORM within Kohana you need to adhere to some important naming conventions when naming tables in your database. The main convention you need to remember is singular and pluralisation of data set names. If you have a table for customers within your database, then you will need to call it something like ‘customers’ (always lowercase). To map this table to a ORM class, you need to ensure your ORM class is named using a singular form, ‘Customer_Model’ for example. (The capitalisation and inclusion of ‘_Model’ is mandatory and should be noted as your model will throw and error if the names are not formatted properly - for more, see http://doc.kohanaphp.com/libraries/orm) Using plural and singular versions of data set names is good practice as your customers table will store many customer records, but each instance of your ORM model will only work on one of those records. This is not always the case when using ORM, as you can also find and return many records, but more on that later. The SQL code for creating your customers table within MySQL is as follows. 1. 2. 3. 4. 5. 6. 7. 8.

CREATE TABLE `customers` ( `id` INT( 12 ) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Unique id', `title` TEXT NOT NULL COMMENT 'Title', `firstname` TEXT NOT NULL COMMENT 'Firstname', `surname` TEXT NOT NULL COMMENT 'Surname', `email` TEXT NOT NULL COMMENT 'Email Address', PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = 'A very simple customer table'

This will create your very simple customer table. The SQL code creates a table with five fields, indexed by a unique id that auto-increments. Now you have your database table correctly set up, you can forget SQL and begin creating your ORM class to manipulate data within the this table. To create your ORM class to map to the table you have just created you will need to open your editor and navigate to the application/models folder, then create a new file called ‘customer.php’. Notice the use of the singular name following our naming convention. All of your ORM classes are going to be extensions of the core ORM class, giving you all the methods of ORM through inheritance. This means that the core contents of your ORM class are going to be very similar across differing data sets.

5

Kohana PHP Object Relational Mapping guide

Lets set up our Customer_Model for ORM use. 1. 2. 3. 4. 5. 6. 7.



That’s it. Using this code you could now begin manipulating your data within your customers table. However this does not really show the inner workings of ORM, so I’m going to add an additional couple of lines of code. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21.



Please note that the inclusion of these three methods is not required, but the inclusion demonstrates what the default ORM method calls are for constructing an instance, plus getting and setting data. When Customer_Model is initiated the __construct() method is called, which in turn calls the ORM __construct() method. This class constructor accepts an ‘id’ as the argument which is referring to the field `customers.id` within the database. If you do not supply the id of a record, ORM will assume this is a new record and insert it as such when you are finished. Hopefully the __get() and __set() methods should be self explanatory. A quick note on the __set() method. By default, when you set a value using this method you are only updating your model within PHP, not the database. To set the data in stone you need to invoke the save() method using $my_customer_object->save() for example. 6

Kohana PHP Object Relational Mapping guide

If you want to reduce your lines of code or do not want to have to remember to save each time, you can invoke the ‘auto_save’ feature of ORM that saves the instance state upon destruction. To do this manually, you set ‘auto_save’ on your instance after initialisation within a controller. 1. 2.

$my_customer_object = new Customer_Model(); $my_customer_object->auto_save = TRUE;

You could also achieve this by adding this __destruct() method to your Customer_Model. 1. 2. 3. 4. 5.

public function __destruct() { $this->save(); parent::__destruct(); }

Or you could set auto_save within your __construct() method in your Customer_Model. 1. 2. 3. 4. 5.

public function __construct() { parent::__construct(); $this->auto_save = TRUE; }

Which method you use will depend on your application logic. If you always want to automatically save your object state to the database I recommend one of the latter solutions. If you want to automatically save on an ad hoc basis, use the first example.

7

Kohana PHP Object Relational Mapping guide

Using Customer_Model with Customer_Controller With your Customer_Model saved, it is now available throughout Kohana for use. All models within application/models folder are automatically loaded for you so all you need to do is call it when ready. Within the controllers folder I have created a file called customer.php to control my customer data. This controller needs to show all customer data, display a single record and edit records. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31.



I am now going to demonstrate how you can extend your model to your needs. I am going to concentrate on the __set() method. When I set my values for firstname, surname and title, I want to ensure that the values are capitalised correctly. To do this I first need to inspect what $key is being set, and then decide what to do - if anything. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10.

public { correctly

}

function __set( $key, $value ) if( $key === ‘title’ || $key === ‘firstname’ || $key === ‘surname’ ) { // Ensure the title, firstname or surname are formatted }

$value = ucwords(strtolower($value));

parent::__set( $key, $value );

Now before Customer_Model sets any value, it first checks to see if any of the keys match title, firstname or surname. If they do then $value is lowercased and then the first letter of each word is uppercased using the standard PHP functions strtolower() and ucwords(). Finally the data is set using the ORM method as usual. You can perform as many tasks as you like before your set 14

Kohana PHP Object Relational Mapping guide

your values in your models. Just ensure you check the keys you are working with before transforming their values.

15

Kohana PHP Object Relational Mapping guide

Creating ORM relationships So far I have detailed how ORM deals with single data sets. But what happens if we need to link a customer record to an address or addresses in the database? Well the short answer is ORM can do this to, but you need to set up your parent child relationships in your ORM model as well as within your database. I will demonstrate a ‘One to many’ and ‘Many to many’ relationship. The other variations should become easier to interpret once you’ve read through this chapter.

One to many relationship First of all I am going to create an address table that is directly related to my Customer_Model, with Customer_Model being the parent of addresses. This is the simplest of relationships. The address table has to have some key information to ensure ORM works properly for this relationship. The table name has to start with a singular version of the parent followed by underscore and the a plural version of the child name. In addition to this, a field providing the related parent needs to be included. This also follows a strict naming convention. The field name should be named using a singular parent name followed by an underscore and the field name that this record is linked to in the parent table (the id of the customer in this instance). This means a table called customer_addresses is created with a required field name called customer_id to cement the relationship. Make sure your required field name data-type matches the parents. The MySQL code is below. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.

CREATE TABLE `customer_addresses` ( `id` INT( 12 ) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Unique id', `customer_id` INT( 12 ) NOT NULL COMMENT 'The id of the customer', `type` TEXT NOT NULL COMMENT 'Type of address, home, work etc', `property` TEXT NOT NULL COMMENT 'Property name or number', `line1` TEXT NOT NULL COMMENT 'First line', `line2` TEXT NOT NULL COMMENT 'Second line', `city` TEXT NOT NULL COMMENT 'City', `postalcode` TEXT NOT NULL COMMENT 'Post code', `country` TEXT NOT NULL COMMENT 'Country', PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = 'A very simple address table'

NOTE: Kohana PHP has an inflector helper to help determine the correct plural or singular version of a word, particularly useful for decoding the singular of addresses.

Now we need to create an address model and tell both models about the relationships between customers and addresses. Lets create the address model first, naming the file containing the model, customer_address.php. 16

Kohana PHP Object Relational Mapping guide

1. 2. 3. 4. 5. 6. 7. 8. 9.



Following the same rules as before, the address model is named Customer_Address_Model. This is because we are using a singular version of customers and a singular version of addresses, which matches the rules stated earlier. 6.



protected $belongs_to = array(‘customer’);

The $belongs_to array has one entry, ‘customer’. This tells ORM which model this model is a child of. As $belongs_to is an array, you have probably realised you can associate this model with more than one other model. With the address model set up, it is time to inform the customer model that it has some children. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29.



}

function __set( $key, $value ) if( $key === ‘title’ || $key === ‘firstname’ || $key === ‘surname’ ) { // Ensure the title, firstname or surname are formatted }

$value = ucwords(strtolower($value));

parent::__set( $key, $value );

17

Kohana PHP Object Relational Mapping guide

Once again the relationship is defined before anything else. With the customer model we use the plural version of the model name, as there are many addresses that could relate to this instance. Model will know to look for Customer_Address_Model because you have declared the relationship in $has_many. You have now completed your relationship declaration.

Many to many relationship When it comes to many to many relationships the set up slightly differs. This time I am going to assume addresses can be shared between customers; two or more customers can use the same address record for example. This time address data is not a direct child of customer data. So the table in MySQL will be more similar to the structure of the customer table. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

CREATE TABLE `addresses` ( `id` INT( 12 ) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Unique id', `type` TEXT NOT NULL COMMENT 'Type of address, home, work etc', `property` TEXT NOT NULL COMMENT 'Property name or number', `line1` TEXT NOT NULL COMMENT 'First line', `line2` TEXT NOT NULL COMMENT 'Second line', `city` TEXT NOT NULL COMMENT 'City', `postalcode` TEXT NOT NULL COMMENT 'Post code', `country` TEXT NOT NULL COMMENT 'Country', PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = 'A very simple address table'

Notice that the table name is plural (‘addresses’ ) this time and the field that ties each record to a customer_id is gone. Because all of the relationship data is gone from the addresses table, an additional table is created to map the addresses to their customers. This is the pivot table and has a specific naming convention like all other tables. I am choosing that Customers is still parent of Addresses for this example, but you could map them in reverse if your application logic dictated that. As there now are many of both data types in our relationship, the pivot table name is called `customers_addresses` - all plural. Notice there is no `id` field, just the `{related table name}_id` for each table in the join. 1. 2. 3. 4. 5.

CREATE TABLE `customers_addresses` ( `customer_id` INT( 12 ) UNSIGNED NOT NULL COMMENT 'Customer id', `address_id` INT( 12 ) UNSIGNED NOT NULL COMMENT 'Address id', PRIMARY KEY (`customer_id`,`address_id`) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = 'A very simple customers pivot table'

18

Kohana PHP Object Relational Mapping guide

This completes the database table set up required for many to many joins. To get the join to work within ORM we need to do some modification of the Customers_Model and create a new Addresses_Model. Below is the refined Customers_Model file with newly updated relationships. I should note that I have also removed the __construct() and __get() functions as they were unchanged from their parents default behaviour. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19.



}

function __set( $key, $value ) if( $key === ‘title’ || $key === ‘firstname’ || $key === ‘surname’ ) { // Ensure the title, firstname or surname are formatted }

$value = ucwords(strtolower($value));

parent::__set( $key, $value );

The relationship is now $has_and_belongs_to_many = array(‘addresses’). Notice the classes is now plural as the relationship is ‘to many’. A new file called address.php should be created within the application/models folder with the code below. 1. 2. 3. 4. 5. 6. 7. 8. 9.



Now the Address_Model is not a child of any other class, but belongs to many customers as defined in $belongs_to_many = array(‘customers’).

19

Kohana PHP Object Relational Mapping guide

Once your models are in place and correctly linked, ORM will be able to update all tables by using methods for finding, adding and removing relationships. These are outlined in the next chapter, “Using ORM relationships in your code”.

ORM relationships summary The biggest hurdle when dealing with ORM relationships is getting the naming conventions correct. Producing a database diagram before coding should make the relationships apparent, which will help writing ORM classes and their relationships. The table below outlines the parent and child declarations for the different data types. The { P } under ‘Many to many’ signifies it requires a pivot table to be created as this is a join. Relationship

Parent class header

Child class header

One to one

$has_one = array(‘child’)

$belongs_to = array(‘parent’)

One to many

$has_many = array(‘childs’)

$belongs_to = array(‘parent’)

Many to many

$belongs_to_many = array(‘parents’)

{P}

$has_and_belongs_to_many = array(‘childs’)

Many to one

$has_one = array(‘child’)

$belongs_to_many = array(‘parents’)

Pivot tables do not require a unique id, but do require the singular {related}_id for each table within the join. The incorrect use of ‘childs’ is deliberate as Kohana PHP’s Inflector class will not resolve child to children, it will add an ‘s’ to child instead. You can read more about the ORM conventions on the Kohana PHP web site.

20

Kohana PHP Object Relational Mapping guide

Using ORM relationships in your code With all relationships set up between models, additional methods within ORM become available. I am not going to go into great detail here, but the following methods become available using the example above.

find_related $parent->find_related_$child 1. 2.

$customer = new Customer_Model(1); $addresses = $customer->find_related_addresses();

$addresses will contain all addresses that belong to this customer.

add $parent->add_$child( $instance ) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14.

$address = new Customer_Address_Model(); $address->type = ‘home’; $address->property = ‘1’; $address->line1 = ‘Brockle Gate Drive’; $address->city = ‘London’; $address->postalcode = ‘SE1 1PP’; $address->country = ‘United Kingdom’; $customer = new Customer_Model(); // Add $address to $customer $customer->add_address( $address ); $customer->save();

This will add a new address to the $customer instance. When you perform; $customer->save(); all data across models and database tables will be updated.

remove $child->remove( ) 15. 16. 17. 18. 19.

$customer = new Customer_Model(1); $addresses = $customer->find_related_addresses(); // Remove the first related $address $addresses[0]->remove();

21

Kohana PHP Object Relational Mapping guide

Appendix A - Full Files On the following pages I provide my finished files in full, which should hopefully help some of you to get going quickly. If you have any comments about the files (such as incorrect code), you’re welcome to fix it and post it back on my blog (http://sam.clark.name) as I’ll be keeping this document up to date.

customers.sql SQL Code for the customers table 20. 21. 22. 23. 24. 25. 26. 27.

CREATE TABLE `customers` ( `id` INT( 12 ) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Unique id', `title` TEXT NOT NULL COMMENT 'Title', `firstname` TEXT NOT NULL COMMENT 'Firstname', `surname` TEXT NOT NULL COMMENT 'Surname', `email` TEXT NOT NULL COMMENT 'Email Address', PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = 'A very simple customer table'

customer_addresses.sql SQL Code for the customer_addresses table 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12.

CREATE TABLE `customer_addresses` ( `id` INT( 12 ) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Unique id', `customer_id` INT( 12 ) NOT NULL COMMENT 'The id of the customer', `type` TEXT NOT NULL COMMENT 'Type of address, home, work etc', `property` TEXT NOT NULL COMMENT 'Property name or number', `line1` TEXT NOT NULL COMMENT 'First line', `line2` TEXT NOT NULL COMMENT 'Second line', `city` TEXT NOT NULL COMMENT 'City', `postalcode` TEXT NOT NULL COMMENT 'Post code', `country` TEXT NOT NULL COMMENT 'Country', PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = 'A very simple address table'

22

Kohana PHP Object Relational Mapping guide

addresses.sql SQL Code for the addresses table (Many to many relationship) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

CREATE TABLE `addresses` ( `id` INT( 12 ) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Unique id', `type` TEXT NOT NULL COMMENT 'Type of address, home, work etc', `property` TEXT NOT NULL COMMENT 'Property name or number', `line1` TEXT NOT NULL COMMENT 'First line', `line2` TEXT NOT NULL COMMENT 'Second line', `city` TEXT NOT NULL COMMENT 'City', `postalcode` TEXT NOT NULL COMMENT 'Post code', `country` TEXT NOT NULL COMMENT 'Country', PRIMARY KEY ( `id` ) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = 'A very simple address table'

customers_addresses.sql SQL Code for the customers_addresses pivot table (Many to many relationship) 1. 2. 3. 4. 5.

CREATE TABLE `customers_addresses` ( `customer_id` INT( 12 ) UNSIGNED NOT NULL COMMENT 'Customer id', `address_id` INT( 12 ) UNSIGNED NOT NULL COMMENT 'Address id', PRIMARY KEY (`customer_id`,`address_id`) ) ENGINE = MYISAM CHARACTER SET utf8 COLLATE utf8_general_ci COMMENT = 'A very simple customers pivot table'

23

Kohana PHP Object Relational Mapping guide

application/models/customer.php PHP code for Customer_Model (Many to many relationship) 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19.



}

function __set( $key, $value ) if( $key === ‘title’ || $key === ‘firstname’ || $key === ‘surname’ ) { // Ensure the title, firstname or surname are formatted }

$value = ucwords(strtolower($value));

parent::__set( $key, $value );

application/models/customer_address.php PHP code for Customer_Address_Model (Many to one relationship) 1. 2. 3. 4. 5. 6. 7. 8. 9.



application/models/address.php PHP code for Address_Model (Many to many relationship) 1. 2. 3. 4. 5. 6. 7. 8. 9.



24

Kohana PHP Object Relational Mapping guide

application/controllers/customer.php PHP code for Customer_Controller 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. 36. 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53.

Suggest Documents