Professional Documents
Culture Documents
http://sam.clark.name
Kohana PHP Object Relational Mapping guide
Contents
Introduction 3
add 21
remove 21
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/.
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
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
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.
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
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.
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.
You could also achieve this by adding this __destruct() method to your Customer_Model.
Or you could set auto_save within your __construct() method in your Customer_Model.
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
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.
This sets up the Customer_Controller class with three methods. Now we can concentrate on
the individual methods in turn.
Now to set up the default behaviour by adding some code to the index() method.
8
Kohana PHP Object Relational Mapping guide
When run, this method will output a list of all registered customers. It currently is not very clever
because it will throw an error if there are no customers in the database, but you could fix that by
checking how many results find_all() returned.
Here is what the index() method is doing. First of all, it creates a new instance of our
Customer_Model. The next line uses ORM’s powerful db builder 1 syntax to find all records,
ordered alphabetically by surname. As we are assigning the result back to our Customer_Model
instance $customers, this instance is replaced by the result of the query. Of course you can
assign the results to another variable if desired.
Once the results are collected, we want to output the results. Using an ordered list, the last lines
of code output each customer record (Surname, Firstname) to a buffer $output. Finally the
buffer is printed using echo.
http://<yourservername>/customer/
The view() method takes one argument, which is the id of the record you wish to load. If no id is
supplied then the output informs the user of their mistake - you could use a 404 error here if you
liked, but I prefer to be a little more informative.
If an id is supplied, a new Customer_Model instance is created using the id submitted. With the
data loaded, we can populate our $output with the full name and email of the customer. Finally
we can echo our output.
This isn’t fully robust as we should check to see if the id supplied is valid, but I’ll come back to
this later when I add more methods to Customer_Model.
Our edit method is going to either load an existing record and allow the user to edit it, or if
record id is omitted then the user will be creating a new record. I am going to use another
Kohana PHP helper called Forge to do this and you can read more about all of this at http://
doc.kohanaphp.com/addons/forge . Forge creates and processes forms for you and can perform
validation using Kohana PHP’s own validate module.
10
Kohana PHP Object Relational Mapping guide
The edit() method is certainly the most complicated, but then it has to do the most. I will step
through what is happening here in blocks.
First we create a new Forge instance and then set up some fields; one hidden id; four inputs for
title, firstname, surname and email; finally a submit button to send the form.
11
Kohana PHP Object Relational Mapping guide
Next we check if the form is valid, which can only be true if the form is submitted and if the form
input is valid using the rules defined setting up the form. The code first establishes the edit type.
If the $edit_form->id value is false, then this is a new customer record. Otherwise the customer
record is loaded before the values are updated. Once all of the fields customer are updated
within the object, the customer instance is saved. ORM handles the difference in SQL between
UPDATE and INSERT for us.
12
Kohana PHP Object Relational Mapping guide
If no form has been submitted, then the form we defined at the top of the edit() method is
printed.
35. else
36. {
37. echo $edit_form->render();
38. }
http://<yourservername>/customer/edit/[<record id>]
If you supply the optional id then you’ll edit an existing record, otherwise you will create a new
record.
It should be noted that this is a very basic. You should do more to protect from XSS and other
malicious input, as well as better error handling if arguments are not supplied. Validation of the
inputs is handled by Forge and it will automatically output the form with highlighted fields if
your input was incorrect, which is why use of Forge is highly recommended.
13
Kohana PHP Object Relational Mapping guide
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.
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
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.
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
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.
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. <?php defined('SYSPATH') or die('No direct script access.');
2.
3. class Customer_Model extends ORM {
4.
5. // Relationships
6. $has_many = array(‘addresses’);
7.
8. public function __construct( $id = FALSE )
9. {
10. parent::__construct( $id );
11. }
12.
13. public function __get( $key )
14. {
15. return parent::__get( $key );
16. }
17.
18. public function __set( $key, $value )
19. {
20. if( $key === ‘title’ || $key === ‘firstname’ || $key === ‘surname’ )
21. {
22. // Ensure the title, firstname or surname are formatted
correctly
23. $value = ucwords(strtolower($value));
24. }
25.
26. parent::__set( $key, $value );
27. }
28. }
29. ?>
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.
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.
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.
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.
A new file called address.php should be created within the application/models folder with the
code below.
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”.
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.
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
find_related
$parent->find_related_$child
add
$parent->add_$child( $instance )
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( )
21
Kohana PHP Object Relational Mapping guide
customers.sql
SQL Code for the customers table
customer_addresses.sql
SQL Code for the customer_addresses table
22
Kohana PHP Object Relational Mapping guide
addresses.sql
SQL Code for the addresses table (Many to many relationship)
customers_addresses.sql
SQL Code for the customers_addresses pivot table (Many to many relationship)
23
Kohana PHP Object Relational Mapping guide
application/models/customer.php
PHP code for Customer_Model (Many to many relationship)
application/models/customer_address.php
PHP code for Customer_Address_Model (Many to one relationship)
application/models/address.php
PHP code for Address_Model (Many to many relationship)
24
Kohana PHP Object Relational Mapping guide
application/controllers/customer.php
PHP code for Customer_Controller
25
Kohana PHP Object Relational Mapping guide
26