Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 401 lines (244 sloc) 20.979 kb
ca39b6f @j4mie Initial commit
j4mie authored
1 Paris
2 =====
3
2255b39 @j4mie Add link to website
j4mie authored
4 [http://j4mie.github.com/idiormandparis/](http://j4mie.github.com/idiormandparis/)
5
ca39b6f @j4mie Initial commit
j4mie authored
6 A lightweight Active Record implementation for PHP5.
7
459e25c @j4mie Documentation
j4mie authored
8 Built on top of [Idiorm](http://github.com/j4mie/idiorm/).
ca39b6f @j4mie Initial commit
j4mie authored
9
6e95dce @j4mie Add note about PHP version compatibility
j4mie authored
10 Tested on PHP 5.2.0+ - may work on earlier versions with PDO and the correct database drivers.
11
ca39b6f @j4mie Initial commit
j4mie authored
12 Released under a [BSD license](http://en.wikipedia.org/wiki/BSD_licenses).
13
84cf78f @j4mie Add "Features" section to README
j4mie authored
14 Features
15 --------
16
17 * Extremely simple configuration.
18 * Exposes the full power of [Idiorm](http://github.com/j4mie/idiorm/)'s fluent query API.
19 * Supports associations.
20 * Simple mechanism to encapsulate common queries in filter methods.
21 * Built on top of [PDO](http://php.net/pdo).
22 * Uses [prepared statements](http://uk.php.net/manual/en/pdo.prepared-statements.php) throughout to protect against [SQL injection](http://en.wikipedia.org/wiki/SQL_injection) attacks.
23 * Database agnostic. Currently supports SQLite and MySQL. May support others, please give it a try!
24
e9d4bb7 @j4mie Add changelog
j4mie authored
25 Changelog
26 ---------
27
28 #### 1.0.0 - released 2010-12-01
29
30 * Initial release
31
94c14f9 @j4mie Correct version
j4mie authored
32 #### 1.1.0 - released 2011-01-24
e9d4bb7 @j4mie Add changelog
j4mie authored
33
34 * Add `is_dirty` method
35
ed75ae6 @j4mie Update changelog
j4mie authored
36 #### 1.1.1 - released 2011-01-30
37
38 * Fix incorrect tests, see issue #12
39
ca39b6f @j4mie Initial commit
j4mie authored
40 Philosophy
41 ----------
42
7dcf73e @j4mie Add custom filter functionality and documentation
j4mie authored
43 Paris is built with the same *less is more* philosophy as [Idiorm](http://github.com/j4mie/idiorm/).
ca39b6f @j4mie Initial commit
j4mie authored
44
45 Let's See Some Code
46 -------------------
459e25c @j4mie Documentation
j4mie authored
47
48 ### Setup ###
49
50 Paris requires [Idiorm](http://github.com/j4mie/idiorm/). Install Idiorm and Paris somewhere in your project directory, and `require` both.
51
52 require_once 'your/path/to/idiorm.php';
53 require_once 'your/path/to/paris.php';
54
55 Then, you need to tell Idiorm how to connect to your database. **For full details of how to do this, see [Idiorm's documentation](http://github.com/j4mie/idiorm/).**
56
57 Briefly, you need to pass a *Data Source Name* connection string to the `configure` method of the ORM class.
58
59 ORM::configure('sqlite:./example.db');
60
84930c3 @j4mie Add MySQL connection example. Thanks to jordanlev for the suggestion
j4mie authored
61 You may also need to pass a username and password to your database driver, using the `username` and `password` configuration options. For example, if you are using MySQL:
62
63 ORM::configure('mysql:host=localhost;dbname=my_database');
64 ORM::configure('username', 'database_user');
65 ORM::configure('password', 'top_secret');
459e25c @j4mie Documentation
j4mie authored
66
67 ### Model Classes ###
68
69 You should create a model class for each entity in your application. For example, if you are building an application that requires users, you should create a `User` class. Your model classes should extend the base `Model` class:
70
71 class User extends Model {
72 }
73
74 Paris takes care of creating instances of your model classes, and populating them with *data* from the database. You can then add *behaviour* to this class in the form of public methods which implement your application logic. This combination of data and behaviour is the essence of the [Active Record pattern](http://martinfowler.com/eaaCatalog/activeRecord.html).
75
76 ### Database Tables ###
77
78 Your `User` class should have a corresponding `user` table in your database to store its data.
79
80 By default, Paris assumes your class names are in *CapWords* style, and your table names are in *lowercase_with_underscores* style. It will convert between the two automatically. For example, if your class is called `CarTyre`, Paris will look for a table named `car_tyre`.
81
82 To override this default behaviour, add a **public static** property to your class called `$_table`:
83
84 class User extends Model {
85 public static $_table = 'my_user_table';
86 }
87
328dda6 @j4mie Add support for specifying custom ID column on classes
j4mie authored
88 ### ID Column ###
89
90 Paris requires that your database tables have a unique primary key column. By default, Paris will use a column called `id`. To override this default behaviour, add a **public static** property to your class called `$_id_column`:
91
92 class User extends Model {
93 public static $_id_column = 'my_id_column';
94 }
95
7e08e7e @j4mie Add note about Paris not respecting Idiorm's ID column configuration
j4mie authored
96 **Note** - Paris has its *own* default ID column name mechanism, and does not respect column names specified in Idiorm's configuration.
97
459e25c @j4mie Documentation
j4mie authored
98 ### Querying ###
99
100 Querying allows you to select data from your database and populate instances of your model classes. Queries start with a call to a static *factory method* on the base `Model` class that takes a single argument: the name of the model class you wish to use for your query. This factory method is then used as the start of a *method chain* which gives you full access to [Idiorm](http://github.com/j4mie/idiorm/)'s fluent query API. **See Idiorm's documentation for details of this API.**
101
102 For example:
103
104 $users = Model::factory('User')
105 ->where('name', 'Fred')
106 ->where_gte('age', 20)
107 ->find_many();
108
109 You can also use the same shortcut provided by Idiorm when looking up a record by its primary key ID:
110
111 $user = Model::factory('User')->find_one($id);
112
113 The only differences between using Idiorm and using Paris for querying are as follows:
114
115 1. You do not need to call the `for_table` method to specify the database table to use. Paris will supply this automatically based on the class name (or the `$_table` static property, if present).
116
117 2. The `find_one` and `find_many` methods will return instances of *your model subclass*, instead of the base `ORM` class. Like Idiorm, `find_one` will return a single instance or `false` if no rows matched your query, while `find_many` will return an array of instances, which may be empty if no rows matched.
118
7dcf73e @j4mie Add custom filter functionality and documentation
j4mie authored
119 3. Custom filtering, see next section.
120
459e25c @j4mie Documentation
j4mie authored
121 You may also retrieve a count of the number of rows returned by your query. This method behaves exactly like Idiorm's `count` method:
122
123 $count = Model::factory('User')->where_lt('age', 20)->count();
124
67174ae @j4mie Add has_one, has_many and belongs_to associations. Code, docs, tests.
j4mie authored
125 ### Associations ###
126
127 Paris provides a simple API for one-to-one, one-to-many and many-to-many relationships (associations) between models. It takes a different approach to many other ORMs, which use associative arrays to add configuration metadata about relationships to model classes. These arrays can often be deeply nested and complex, and are therefore quite error-prone.
128
129 Instead, Paris treats the act of querying across a relationship as a *behaviour*, and supplies a family of helper methods to help generate such queries. These helper methods should be called from within *methods* on your model classes which are named to describe the relationship. These methods return ORM instances (rather than actual Model instances) and so, if necessary, the relationship query can be modified and added to before it is run.
130
131 #### Summary ####
132
133 The following list summarises the associations provided by Paris, and explains which helper method supports each type of association:
134
135 ##### One-to-one #####
136
137 Use `has_one` in the base, and `belongs_to` in the associated model.
138
139 ##### One-to-many #####
140
141 Use `has_many` in the base, and `belongs_to` in the associated model.
142
143 ##### Many-to-many #####
144
145 Use `has_many_through` in both the base and associated models.
146
e591289 @j4mie README tweaks
j4mie authored
147 Below, each association helper method is discussed in detail.
148
67174ae @j4mie Add has_one, has_many and belongs_to associations. Code, docs, tests.
j4mie authored
149 #### Has-one ####
150
151 One-to-one relationships are implemented using the `has_one` method. For example, say we have a `User` model. Each user has a single `Profile`, and so the `user` table should be associated with the `profile` table. To be able to find the profile for a particular user, we should add a method called `profile` to the `User` class (note that the method name here is arbitrary, but should describe the relationship). This method calls the protected `has_one` method provided by Paris, passing in the class name of the related object. The `profile` method should return an ORM instance ready for (optional) further filtering.
152
153 class Profile extends Model {
154 }
155
156 class User extends Model {
157 public function profile() {
158 return $this->has_one('Profile');
159 }
160 }
161
162 The API for this method works as follows:
163
f4103cc @j4mie Improve associations docs
j4mie authored
164 // Select a particular user from the database
165 $user = Model::factory('User')->find_one($user_id);
166
167 // Find the profile associated with the user
168 $profile = $user->profile()->find_one();
67174ae @j4mie Add has_one, has_many and belongs_to associations. Code, docs, tests.
j4mie authored
169
170 By default, Paris assumes that the foreign key column on the related table has the same name as the current (base) table, with `_id` appended. In the example above, Paris will look for a foreign key column called `user_id` on the table used by the `Profile` class. To override this behaviour, add a second argument to your `has_one` call, passing the name of the column to use.
171
e591289 @j4mie README tweaks
j4mie authored
172 #### Has many ####
67174ae @j4mie Add has_one, has_many and belongs_to associations. Code, docs, tests.
j4mie authored
173
174 One-to-many relationships are implemented using the `has_many` method. For example, say we have a `User` model. Each user has several `Post` objects. The `user` table should be associated with the `post` table. To be able to find the posts for a particular user, we should add a method called `posts` to the `User` class (note that the method name here is arbitrary, but should describe the relationship). This method calls the protected `has_many` method provided by Paris, passing in the class name of the related objects. **Pass the model class name literally, not a pluralised version**. The `posts` method should return an ORM instance ready for (optional) further filtering.
175
176 class Post extends Model {
177 }
178
179 class User extends Model {
180 public function posts() {
181 return $this->has_many('Post'); // Note we use the model name literally - not a pluralised version
182 }
183 }
184
185 The API for this method works as follows:
186
f4103cc @j4mie Improve associations docs
j4mie authored
187 // Select a particular user from the database
188 $user = Model::factory('User')->find_one($user_id);
189
190 // Find the posts associated with the user
191 $posts = $user->posts()->find_many();
67174ae @j4mie Add has_one, has_many and belongs_to associations. Code, docs, tests.
j4mie authored
192
193 By default, Paris assumes that the foreign key column on the related table has the same name as the current (base) table, with `_id` appended. In the example above, Paris will look for a foreign key column called `user_id` on the table used by the `Post` class. To override this behaviour, add a second argument to your `has_many` call, passing the name of the column to use.
194
e591289 @j4mie README tweaks
j4mie authored
195 #### Belongs to ####
67174ae @j4mie Add has_one, has_many and belongs_to associations. Code, docs, tests.
j4mie authored
196
197 The 'other side' of `has_one` and `has_many` is `belongs_to`. This method call takes identical parameters as these methods, but assumes the foreign key is on the *current* (base) table, not the related table.
198
199 class Profile extends Model {
200 public function user() {
201 return $this->belongs_to('User');
202 }
203 }
204
205 class User extends Model {
206 }
207
208 The API for this method works as follows:
209
f4103cc @j4mie Improve associations docs
j4mie authored
210 // Select a particular profile from the database
211 $profile = Model::factory('Profile')->find_one($profile_id);
212
213 // Find the user associated with the profile
214 $user = $profile->user()->find_one();
67174ae @j4mie Add has_one, has_many and belongs_to associations. Code, docs, tests.
j4mie authored
215
65bd387 @j4mie Add has_many_through method. Code, docs, tests.
j4mie authored
216 Again, Paris makes an assumption that the foreign key on the current (base) table has the same name as the related table with `_id` appended. In the example above, Paris will look for a column named `user_id`. To override this behaviour, pass a second argument to the `belongs_to` method, specifying the name of the column on the current (base) table to use.
217
e591289 @j4mie README tweaks
j4mie authored
218 #### Has many through ####
65bd387 @j4mie Add has_many_through method. Code, docs, tests.
j4mie authored
219
220 Many-to-many relationships are implemented using the `has_many_through` method. This method has only one required argument: the name of the related model. Supplying further arguments allows us to override default behaviour of the method.
221
222 For example, say we have a `Book` model. Each `Book` may have several `Author` objects, and each `Author` may have written several `Books`. To be able to find the authors for a particular book, we should first create an intermediary model. The name for this model should be constructed by concatenating the names of the two related classes, in alphabetical order. In this case, our classes are called `Author` and `Book`, so the intermediate model should be called `AuthorBook`.
223
77adca7 @j4mie Add note about validation to README. See issue #2
j4mie authored
224 We should then add a method called `authors` to the `Book` class (note that the method name here is arbitrary, but should describe the relationship). This method calls the protected `has_many_through` method provided by Paris, passing in the class name of the related objects. **Pass the model class name literally, not a pluralised version**. The `authors` method should return an ORM instance ready for (optional) further filtering.
65bd387 @j4mie Add has_many_through method. Code, docs, tests.
j4mie authored
225
226 class Author extends Model {
f4103cc @j4mie Improve associations docs
j4mie authored
227 public function books() {
228 return $this->has_many_through('Book');
229 }
65bd387 @j4mie Add has_many_through method. Code, docs, tests.
j4mie authored
230 }
231
232 class Book extends Model {
233 public function authors() {
234 return $this->has_many_through('Author');
235 }
236 }
237
f4103cc @j4mie Improve associations docs
j4mie authored
238 class AuthorBook extends Model {
239 }
240
65bd387 @j4mie Add has_many_through method. Code, docs, tests.
j4mie authored
241 The API for this method works as follows:
242
f4103cc @j4mie Improve associations docs
j4mie authored
243 // Select a particular book from the database
244 $book = Model::factory('Book')->find_one($book_id);
245
246 // Find the authors associated with the book
247 $authors = $book->authors()->find_many();
248
249 // Get the first author
250 $first_author = $authors[0];
251
252 // Find all the books written by this author
253 $first_author_books = $first_author->books()->find_many();
65bd387 @j4mie Add has_many_through method. Code, docs, tests.
j4mie authored
254
255 ##### Overriding defaults #####
256
257 The `has_many_through` method takes up to four arguments, which allow us to progressively override default assumptions made by the method.
258
259 **First argument: associated model name** - this is mandatory and should be the name of the model we wish to select across the association.
260
261 **Second argument: intermediate model name** - this is optional and defaults to the names of the two associated models, sorted alphabetically and concatenated.
262
263 **Third argument: custom key to base table on intermediate table** - this is optional, and defaults to the name of the base table with `_id` appended.
264
265 **Fourth argument: custom key to associated table on intermediate table** - this is optional, and defaults to the name of the associated table with `_id` appended.
67174ae @j4mie Add has_one, has_many and belongs_to associations. Code, docs, tests.
j4mie authored
266
27cfbca @j4mie Custom filters can now accept arguments. Improve filter docs
j4mie authored
267 ### Filters ###
7dcf73e @j4mie Add custom filter functionality and documentation
j4mie authored
268
14fe7fa @j4mie Another typo in docs
j4mie authored
269 It is often desirable to create reusable queries that can be used to extract particular subsets of data without repeating large sections of code. Paris allows this by providing a method called `filter` which can be chained in queries alongside the existing Idiorm query API. The filter method takes the name of a **public static** method on the current Model subclass as an argument. The supplied method will be called at the point in the chain where `filter` is called, and will be passed the `ORM` object as the first parameter. It should return the ORM object after calling one or more query methods on it. The method chain can then be continued if necessary.
7dcf73e @j4mie Add custom filter functionality and documentation
j4mie authored
270
27cfbca @j4mie Custom filters can now accept arguments. Improve filter docs
j4mie authored
271 It is easiest to illustrate this with an example. Imagine an application in which users can be assigned a role, which controls their access to certain pieces of functionality. In this situation, you may often wish to retrieve a list of users with the role 'admin'. To do this, add a static method called (for example) `admins` to your Model class:
7dcf73e @j4mie Add custom filter functionality and documentation
j4mie authored
272
273 class User extends Model {
274 public static function admins($orm) {
275 return $orm->where('role', 'admin');
276 }
277 }
278
279 You can then use this filter in your queries:
280
281 $admin_users = Model::factory('User')->filter('admins')->find_many();
282
283 You can also chain it with other methods as normal:
284
285 $young_admins = Model::factory('User')
286 ->filter('admins')
287 ->where_lt('age', 18)
288 ->find_many();
289
27cfbca @j4mie Custom filters can now accept arguments. Improve filter docs
j4mie authored
290 #### Filters with arguments ####
291
292 You can also pass arguments to custom filters. Any additional arguments passed to the `filter` method (after the name of the filter to apply) will be passed through to your custom filter as additional arguments (after the ORM instance).
293
294 For example, let's say you wish to generalise your role filter (see above) to allow you to retrieve users with any role. You can pass the role name to the filter as an argument:
295
296 class User extends Model {
297 public static function has_role($orm, $role) {
298 return $orm->where('role', $role);
299 }
300 }
301
302 $admin_users = Model::factory('User')->filter('has_role', 'admin')->find_many();
303 $guest_users = Model::factory('User')->filter('has_role', 'guest')->find_many();
304
d6d24fa @j4mie Tiny typo in docs
j4mie authored
305 These examples may seem simple (`filter('has_role', 'admin')` could just as easily be achieved using `where('role', 'admin')`), but remember that filters can contain arbitrarily complex code - adding `raw_where` clauses or even complete `raw_query` calls to perform joins, etc. Filters provide a powerful mechanism to hide complexity in your model's query API.
27cfbca @j4mie Custom filters can now accept arguments. Improve filter docs
j4mie authored
306
459e25c @j4mie Documentation
j4mie authored
307 ### Getting data from objects, updating and inserting data ###
308
309 The model instances returned by your queries now behave exactly as if they were instances of Idiorm's raw `ORM` class.
310
311 You can access data:
312
313 $user = Model::factory('User')->find_one($id);
314 echo $user->name;
315
316 Update data and save the instance:
317
318 $user = Model::factory('User')->find_one($id);
319 $user->name = 'Paris';
320 $user->save();
321
a055cc9 @j4mie Add documentation on creating new (empty) model instances. Closes iss…
j4mie authored
322 To create a new (empty) instance, use the `create` method:
323
324 $user = Model::factory('User')->create();
325 $user->name = 'Paris';
326 $user->save();
327
3edc37f @j4mie Add is_dirty method
j4mie authored
328 To check whether a property has been changed since the object was created (or last saved), call the `is_dirty` method:
329
330 $name_has_changed = $person->is_dirty('name'); // Returns true or false
331
459e25c @j4mie Documentation
j4mie authored
332 Of course, because these objects are instances of your base model classes, you can also call methods that you have defined on them:
333
334 class User extends Model {
335 public function full_name() {
336 return $this->first_name . ' ' . $this->last_name;
337 }
338 }
339
340 $user = Model::factory('User')->find_one($id);
341 echo $user->full_name();
342
343 To delete the database row associated with an instance of your model, call its `delete` method:
344
345 $user = Model::factory('User')->find_one($id);
346 $user->delete();
347
b961e70 @j4mie Add wrappers for as_array method to base Model class
j4mie authored
348 You can also get the all the data wrapped by a model subclass instance using the `as_array` method. This will return an associative array mapping column names (keys) to their values.
349
350 The `as_array` method takes column names as optional arguments. If one or more of these arguments is supplied, only matching column names will be returned.
351
352 class Person extends Model {
353 }
354
355 $person = Model::factory('Person')->create();
356
357 $person->first_name = 'Fred';
358 $person->surname = 'Bloggs';
359 $person->age = 50;
360
361 // Returns array('first_name' => 'Fred', 'surname' => 'Bloggs', 'age' => 50)
362 $data = $person->as_array();
363
364 // Returns array('first_name' => 'Fred', 'age' => 50)
365 $data = $person->as_array('first_name', 'age');
366
77adca7 @j4mie Add note about validation to README. See issue #2
j4mie authored
367 ### A word on validation ###
368
369 It's generally considered a good idea to centralise your data validation in a single place, and a good place to do this is inside your model classes. This is preferable to handling validation alongside form handling code, for example. Placing validation code inside models means that if you extend your application in the future to update your model via an alternative route (say a REST API rather than a form) you can re-use the same validation code.
370
371 Despite this, Paris doesn't provide any built-in support for validation. This is because validation is potentially quite complex, and often very application-specific. Paris is deliberately quite ignorant about your actual data - it simply executes queries, and gives you the responsibility of making sure the data inside your models is valid and correct. Adding a full validation framework to Paris would probably require more code than Paris itself!
372
373 However, there are several simple ways that you could add validation to your models without any help from Paris. You could override the `save()` method, check the data is valid, and return `false` on failure, or call `parent::save()` on success. You could create your own subclass of the `Model` base class and add your own generic validation methods. Or you could write your own external validation framework which you pass model instances to for checking. Choose whichever approach is most suitable for your own requirements.
374
459e25c @j4mie Documentation
j4mie authored
375 ### Configuration ###
376
daba5a5 @j4mie Correct configuration section of README
j4mie authored
377 The only configuration options provided by Paris itself are the `$_table` and `$_id_column` static properties on model classes. To configure the database connection, you should use Idiorm's configuration system via the `ORM::configure` method. **See [Idiorm's documentation](http://github.com/j4mie/idiorm/) for full details.**
bc9e549 @j4mie Add note about logging to README
j4mie authored
378
0a0e01b @j4mie Add documentation on transactions. Closes issue #8
j4mie authored
379 ### Transactions ###
380
381 Paris (or Idiorm) doesn't supply any extra methods to deal with transactions, but it's very easy to use PDO's built-in methods:
382
383 // Start a transaction
384 ORM::get_db()->beginTransaction();
385
386 // Commit a transaction
387 ORM::get_db()->commit();
388
389 // Roll back a transaction
390 ORM::get_db()->rollBack();
391
392 For more details, see [the PDO documentation on Transactions](http://www.php.net/manual/en/pdo.transactions.php).
393
bc9e549 @j4mie Add note about logging to README
j4mie authored
394 ### Query logging ###
395
396 Idiorm can log all queries it executes. To enable query logging, set the `logging` option to `true` (it is `false` by default).
397
398 ORM::configure('logging', true);
399
400 When query logging is enabled, you can use two static methods to access the log. `ORM::get_last_query()` returns the most recent query executed. `ORM::get_query_log()` returns an array of all queries executed.
Something went wrong with that request. Please try again.