CC-2166: Packaging Improvements. Moved the Zend app into airtime_mvc. It is now installed to /var/www/airtime. Storage is now set to /srv/airtime/stor. Utils are now installed to /usr/lib/airtime/utils/. Added install/airtime-dircheck.php as a simple test to see if everything is install/uninstalled correctly.

This commit is contained in:
Paul Baranowski 2011-04-14 18:55:04 -04:00
parent 514777e8d2
commit b11cbd8159
4546 changed files with 138 additions and 51 deletions

View file

@ -0,0 +1,164 @@
= Installing Propel =
[[PageOutline]]
Propel is available as a [http://pear.php.net/manual/en/installation.getting.php PEAR] package, as a "traditional" tgz or zip package, and as a checkout from a Subversion repository. Whatever installation method you may choose, getting Propel to work is pretty straightforward.
== Prerequisites ==
Propel requirements are very light, allowing it to run on most PHP platforms:
* [http://www.php.net/ PHP 5.2.4] or newer, with the DOM (libxml2) module enabled
* A supported database (MySQL, MS SQL Server, PostgreSQL, SQLite, Oracle)
'''Tip''': Propel uses the PDO and SPL components, which are bundled and enabled by default in PHP5.
== Propel Components ==
The Propel library is made of two components: a '''generator''', and a '''runtime library'''. These components are not co-dependent, and can be installed independently from each other.
The generator is needed to build the object model, but is not required for running applications that use Propel.
The runtime classes provide the shared functionality that is used by the Propel-generated object model classes. These are necessary to run applications that use Propel to access the database.
Usually, both the generator and the runtime components are installed on development environments, while the actual test or production servers need only the runtime components installed. For your first contact with Propel, just install both.
== Installing Propel ==
=== Installing Propel From PEAR ===
In order to install the Propel packages, you must add the `pear.propelorm.org` channel to your PEAR environment. Once the channel is discovered, you can install the generator package, or the runtime package, or both. Use the '-a' option to let PEAR download and install dependencies.
{{{
#!sh
> pear channel-discover pear.propelorm.org
> pear install -a propel/propel_generator
> pear install -a propel/propel_runtime
}}}
Propel is now installed, and you can test it by following the instructions of the '''Testing Propel Installation''' section at the end of this page.
Tip: If you want to install non-stable versions of Propel, change your `preferred_state` PEAR environment variable before installoing the Propel packages. Valid states include 'stable', 'beta', 'alpha', and 'devel':
{{{
#!sh
> pear config-set preferred_state beta
}}}
=== Dependencies for Tarball and Subversion Versions ===
The Propel generator uses [http://phing.info/ Phing 2.3.3] to manage command line tasks; both the generator and the runtime classes use [http://pear.php.net/package/Log/ PEAR Log] to log events.
If you choose to install Propel via PEAR, these components will be automatically installed as dependencies. If you choose to install Propel from a tarball or a Subversion checkout, you'll have to install them manually:
{{{
#!sh
> pear channel-discover pear.phing.info
> pear install phing/phing
> pear install Log
}}}
Refer to their respective websites for alternative installation strategies for Phing and Log.
=== Installing Propel From Subversion ===
Installing from SVN trunk ensures that you have the most up-to-date source code.
{{{
#!sh
> svn checkout http://svn.propelorm.org/branches/1.5 /usr/local/propel
}}}
This will export both the generator and runtime components to your local `propel` directory. In addition, you'll also get Propel documentation and unit tests - that's why this method is the preferred installation method for Propel contributors.
Once this is done, you'll need to setup your PHP environment to use this library - see the '''Setting Up PHP for Propel''' section below.
Note: `branches/1.5` is currently more uptodate code than `trunk`; trunk is what will become 2.0, however it has had very little work done to it in a long time.
=== Installing Propel From a Tarball ===
Download a tarball of each of the Propel components from the Propel website, and uncompress them into the location that best suits your need. For instance, in Linux:
{{{
#!sh
> cd /usr/local
> mkdir propel
> cd propel
> wget http://pear.propelorm.org/get/propel_generator-1.5.0.tgz
> tar zxvf propel_generator-1.5.0.tgz
> wget http://pear.propelorm.org/get/propel_runtime-1.5.0.tgz
> tar zxvf propel_runtime-1.5.0.tgz
}}}
Once this is done, you'll need to setup your PHP environment to use this library.
== Setting Up PHP for the Propel Generator ==
The following instructions are only required if you installed Propel from a tarball, or from Subversion.
The Propel generator component bundles a `propel-gen` sh script (and a `propel-gen.bat` script for Windows). This script simplifies the commandline invocation of the Propel generator by hiding any references to Phing.
You can call it directly from the command line:
{{{
#!sh
> /usr/local/propel/generator/bin/propel-gen
}}}
In order to allow an easier execution the script, you can also:
* add the propel generator's `bin/` directory to your PATH,
* or copy the `propel-gen` script to a location on your PAH,
* or (on Linux systems) create a symlink. For example:
{{{
#!sh
> cd /usr/local/bin
> ln -s /usr/local/propel/generator/bin/propel-gen propel-gen
}}}
== Testing Propel Installation ==
You can test that the '''Propel generator''' component is properly installed by calling the `propel-gen` script from the CLI:
{{{
#!sh
> propel-gen
}}}
The script should output a few lines before displaying a 'BUILD FAILED' message, which is normal - you haven't defined a database model yet.
You can test that the '''Propel runtime''' component is properly installed by requiring the `Propel.php` script, as follows:
{{{
#!php
<?php
// PEAR installation
require_once 'propel/Propel.php';
// manual installation
require_once '/usr/local/propel/runtime/lib/Propel.php';
// Propel setup code ... (to be discussed later)
}}}
At this point, Propel should be setup and ready to use. You can follow the steps in the [wiki:Documentation/1.5/BuildTime Build Guide] to try it out.
== Troubleshooting ==
=== PHP Configuration ===
Propel requires the following settings in `php.ini`:
||'''Variable'''||'''Value'''||
||ze1_compatibility_mode||Off||
||magic_quotes_gpc||Off||
||magic_quotes_sybase||Off||
=== PEAR Directory In Include Path ===
If you choose to install Propel via PEAR, and if it's your first use of PEAR, the PEAR directory may not be on your PHP `include_path`. Check the PEAR documentation for details on how to do that.
=== Getting Help ===
If you can't manage to install Propel, don't hesitate to ask for help. See [wiki:Support] for details on getting help.

View file

@ -0,0 +1,350 @@
= The Build Time =
[[PageOutline]]
The initial step in every Propel project is the "build". During build time, a developer describes the structure of the datamodel in a XML file called the "schema". From this schema, Propel generates PHP classes, called "model classes", made of object-oriented PHP code optimized for a given RMDBS. The model classes are the primary interface to find and manipulate data in the database in Propel.
The XML schema can also be used to generate SQL code to setup your database. Alternatively, you can generate the schema from an existing database (this is described in another chapter of the documentation - see the [wiki:Documentation/1.5/Existing-Database reverse engineering chapter] for more details).
During build time, a developer also defines the connection settings for communicating with the database.
To illustrate Propel's build abilities, this chapter uses the data structure of a bookstore as an example. It is made of three tables: a `book` table, with a foreign key to two other tables, `author` and `publisher`.
== Describing Your Database as XML Schema ==
Propel generates PHP classes based on a ''relational'' description of your data model. This "schema" uses XML to describe tables, columns and relationships. The schema syntax closely follows the actual structure of the database.
Create a `bookstore` directory. This will be the root of the bookstore project.
=== Database Connection Name ===
Create a file called `schema.xml` in the new `bookstore/` directory.
The root tag of the XML schema is the `<database>` tag:
{{{
#!xml
<?xml version="1.0" encoding="UTF-8"?>
<database name="bookstore" defaultIdMethod="native">
<!-- table definitions go here -->
</database>
}}}
The `name` attribute defines the name of the connection that Propel uses for the tables in this schema. It is not necessarily the name of the actual database. In fact, Propel uses a second file to link a connection name with real connection settings (like databae name, user and password). This `runtime-conf.xml` file will be explained later in this chapter.
The `defaultIdMethod` attribute indicates that the tables in this schema use the database's "native" auto-increment/sequence features to handle id columns that are set to auto-increment.
'''Tip''': You can define several schemas for a single project. Just make sure that each of the schema filenames end with `schema.xml`.
=== Tables And Columns ===
Within the `<database>` tag, Propel expects one `<table>` tag for each table:
{{{
#!xml
<?xml version="1.0" encoding="UTF-8"?>
<database name="bookstore" defaultIdMethod="native">
<table name="book" phpName="Book">
<!-- column and foreign key definitions go here -->
</table>
<table name="author" phpName="Author">
<!-- column and foreign key definitions go here -->
</table>
<table name="publisher" phpName="Publisher">
<!-- column and foreign key definitions go here -->
</table>
</database>
}}}
This time, the `name` attributes are the real table names. The `phpName` is the name that Propel will use for the generated PHP class. By default, Propel uses a CamelCase version of the table name as its phpName - that means that you could omit the `phpName` attribute in the example above.
Within each set of `<table>` tags, define the columns that belong to that table:
{{{
#!xml
<?xml version="1.0" encoding="UTF-8"?>
<database name="bookstore" defaultIdMethod="native">
<table name="book" phpName="Book">
<column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true"/>
<column name="title" type="varchar" size="255" required="true" />
<column name="isbn" type="varchar" size="24" required="true" phpName="ISBN"/>
<column name="publisher_id" type="integer" required="true"/>
<column name="author_id" type="integer" required="true"/>
</table>
<table name="author" phpName="Author">
<column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true"/>
<column name="first_name" type="varchar" size="128" required="true"/>
<column name="last_name" type="varchar" size="128" required="true"/>
</table>
<table name="publisher" phpName="Publisher">
<column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true" />
<column name="name" type="varchar" size="128" required="true" />
</table>
</database>
}}}
Each column has a `name` (the one used by the database), and an optional `phpName` attribute. Once again, the Propel default behavior is to use a CamelCase version of the `name` as `phpName` when not specified.
Each column also requires a `type`. The XML schema is database agnostic, so the column types and attributes are probably not exactly the same as the one you use in your own database. But Propel knows how to map the schema types with SQL types for many database vendors. Existing Propel column types are boolean, tinyint, smallint, integer, bigint, double, float, real, decimal, char, varchar, longvarchar, date, time, timestamp, blob, and clob. Some column types use a `size` (like `varchar` and `int`), some have unlimited size (`longvarchar`, `clob`, `blob`).
As for the other column attributes, `required`, `primaryKey`, and `autoIncrement`, they mean exactly what their names suppose.
'''Tip''': Propel supports namespaces (for PHP > 5.3). If you specify a `namespace` attribute in a `<table>` element, the generated PHP classes for this table will use this namespace.
=== Foreign Keys ===
A table can have several `<foreign-key>` tags, describing foreign keys to foreign tables. Each `<foreign-key>` tag consists of one or more mappings between a local column and a foreign column.
{{{
#!xml
<?xml version="1.0" encoding="UTF-8"?>
<database name="bookstore" defaultIdMethod="native">
<table name="book" phpName="Book">
<column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true"/>
<column name="title" type="varchar" size="255" required="true" />
<column name="isbn" type="varchar" size="24" required="true" phpName="ISBN"/>
<column name="publisher_id" type="integer" required="true"/>
<column name="author_id" type="integer" required="true"/>
<foreign-key foreignTable="publisher" phpName="Publisher" refPhpName="Book">
<reference local="publisher_id" foreign="id"/>
</foreign-key>
<foreign-key foreignTable="author">
<reference local="author_id" foreign="id"/>
</foreign-key>
</table>
<table name="author" phpName="Author">
<column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true"/>
<column name="first_name" type="varchar" size="128" required="true"/>
<column name="last_name" type="varchar" size="128" required="true"/>
</table>
<table name="publisher" phpName="Publisher">
<column name="id" type="integer" required="true" primaryKey="true" autoIncrement="true" />
<column name="name" type="varchar" size="128" required="true" />
</table>
</database>
}}}
A foreign key represents a relationship. Just like a table or a column, a relationship has a `phpName`. By default, Propel uses the `phpName` of the foreign table as the `phpName` of the relation. The `refPhpName` defines the name of the relation as seen from the foreign table.
There are many more attributes and elements available to describe a datamodel. Propel's documentation provides a complete [wiki:Documentation/1.5/Schema reference of the schema syntax], together with a [source:branches/1.5/generator/resources/dtd/database.dtd DTD] and a [source:branches/1.5/generator/resources/xsd/database.xsd XSD] schema for its validation.
== Building The Model ==
=== Setting Up Build Configuration ===
The build process is highly customizable. Whether you need the generated classes to inherit one of your classes rather than Propel's base classes, or to enable/disable some methods in the generated classes, pretty much every customization is possible. Of course, Propel provides sensible defaults, so that you actually need to define only two settings for the build process to start: the RDBMS you are going to use, and a name for your project.
Propel expects the build configuration to be stored in a file called `build.properties`, and stored at the same level as the `schema.xml`. Here is an example for a MySQL database:
{{{
#!ini
# Database driver
propel.database = mysql
# Project name
propel.project = bookstore
}}}
Use your own database vendor driver, chosen among pgsql, mysql, sqlite, mssql, and oracle.
You can learn more about the available build settings and their possible values in the [wiki:Documentation/1.5/BuildConfiguration build configuration reference].
=== Using the `propel-gen` Script To Build The Model ===
The Propel generator uses the `propel-gen` script, as seen in the previous chapter. This executable expects a command name as its argument.
Open a terminal and browse to the `bookstore/` directory, where you saved the two previous files (`schema.xml`, and `build.properties`). Then use the `propel-gen` script to call the "Object Model generator" command using its shortcut - "om":
{{{
> cd /path/to/bookstore
> propel-gen om
}}}
You should normally see a some colored lines appear in the terminal, logging all the class generation, and ending with "BUILD FINISHED". If not, look for red lines in the log and follow the directions in the error messages.
=== Generated Object Model ===
The "om" command added a new directory in the `bookstore/` project, called `build/`. The generated model classes are located under the `classes/bookstore/` subdirectory:
{{{
> cd /path/to/bookstore
> cd build/classes/bookstore/
> ls
om/
map/
Author.php
AuthorPeer.php
AuthorQuery.php
Book.php
BookPeer.php
BookQuery.php
Publisher.php
PublisherPeer.php
PublisherQuery.php
}}}
For every table in the database, Propel creates 3 PHP classes:
* a ''model'' class (e.g. `Book`), which represents a row in the database;
* a ''peer'' class (e.g. `BookPeer`), offering static constants and methods mostly for compatibility with previous Propel versions;
* a ''query'' class (e.g. `BookQuery`), used to operate on a table to retrieve and update rows
Propel uses the `phpName` attribute of each table as the base for the PHP class names.
All these classes are empty, but they inherit from `Base` classes that you will find under the `om/` directory:
{{{
#!php
<?php
require 'om/BaseBook.php';
class Book extends BaseBook
{
}
}}}
These empty classes are called ''stub'' classes. This is where you will add your own model code. These classes are generated only once by Propel ; on the other hand, the ''base'' classes they extend are overwritten every time you call the `om` command, and that happens a lot in the course of a project, because the schema evolves with your needs.
In addition to these classes, Propel generates one `TableMap` class for each table under the `map/` directory. You will probably never use the map classes directly, but Propel needs them to get metadata information about the table structure at runtime.
'''Tip''': Never add any code of your own to the classes generated by Propel in the `om/` and `map/` directories; this code would be lost next time you call the `propel-gen` script.
Basically, all that means is that despite the fact that Propel generates ''seven'' classes for each table, you should only care about two of them: the model class and the query class.
== Building The Database ==
To save you the burden of defining your model twice, Propel can initialize a database based on the schema, by creating the tables and foreign keys.
=== Building The SQL File ===
Once again, use the `propel-gen` script to generate the SQL files necessary to create the tables, this time with the "sql" command:
{{{
> cd /path/to/bookstore
> propel-gen sql
}}}
The generated SQL definition can be found in the `build/sql/schema.sql` file. The code is optimized for the database driver defined in the `build.properties`.
=== Using The SQL File ===
Create the database and setup the access permissions using your favorite database client. For instance, to create the `my_db_name` database with MySQL, type:
{{{
> mysqladmin -u root -p create my_db_name
}}}
Now you can use the generated code directly:
{{{
> mysql -u root -p my_db_name < build/sql/schema.sql
}}}
'''Tip''': The `schema.sql` file will DROP any existing table before creating them, which will effectively erase your database.
Depending on which RDBMS you are using, it may be normal to see some errors (e.g. "unable to DROP...") when you first run this command. This is because some databases have no way of checking to see whether a database object exists before attempting to DROP it (MySQL is a notable exception). It is safe to disregard these errors, and you can always run the script a second time to make sure that the errors are no longer present.
=== Inserting SQL With `propel-gen` ===
As an alternative to using the generated sql code directly, you can ask Propel to insert it directly into your database. Start by defining the database connection settings in the `build.properties`, as follows:
{{{
# Connection parameters
propel.database.url = mysql:host=localhost;dbname=my_db_name
propel.database.user = my_db_user
propel.database.password = my_db_password
# Other examples:
# propel.database.url = sqlite:/path/to/bookstore.db
# propel.database.url = pgsql:host=localhost dbname=my_db_name user=my_db_user password=my_db_password
}}}
The `propel.database.url` setting should be a PDO DSN (see the [http://www.php.net/pdo PDO documentation] for more information about vendor-specific DSN). The `user` and `password` are only necessary for the `mysql` and `oracle` drivers.
Then use the `propel-gen` script with the "insert-sql" command to connect to the database and inject the generated SQL code:
{{{
> cd /path/to/bookstore
> propel-gen insert-sql
}}}
== Runtime Connection Settings ==
The database and PHP classes are now ready to be used. But they don't know yet how to communicate with each other at runtime. You must add a configuration file so that the generated object model classes and the shared Propel runtime classes can connect to the database, and log the Propel activity.
=== Writing The XML Runtime Configuration ===
Create a file called `runtime-conf.xml` at the root of the `bookstore` project, using the following content:
{{{
#!xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<!-- Uncomment this if you have PEAR Log installed
<log>
<type>file</type>
<name>/path/to/propel.log</name>
<ident>propel-bookstore</ident>
<level>7</level>
</log>
-->
<propel>
<datasources default="bookstore">
<datasource id="bookstore">
<adapter>mysql</adapter> <!-- sqlite, mysql, myssql, oracle, or pgsql -->
<connection>
<dsn>mysql:host=localhost;dbname=my_db_name</dsn>
<user>my_db_user</user>
<password>my_db_password</password>
</connection>
</datasource>
</datasources>
</propel>
</config>
}}}
Notice how the `id` attribute of the `<datasource>` tag matches the connection name defined in the `<database>` tag of the `schema.xml`. This is how Propel maps a database description to a connection.
Replace the `<adapter>` and the `<connection>` settings wit hthe ones of your database.
See the [wiki:Documentation/1.5/RuntimeConfiguration runtime configuration reference] for a more detailed explanation of this file.
'''Tip''': If you uncomment the `<log>` section, Propel will attempt to instantiate the `Log` class (from the [http://pear.php.net/package/Log/ PEAR Log] package) with the specified parameters and use that to log queries. Propel's statement logging happens at the DEBUG level (7); errors and warnings are logged at the appropriate (non-debug) level.
=== Building the Runtime Configuration ===
For performance reasons, Propel prefers to use a PHP version of the connection settings rather than the XML file you just defined. So you must use the `propel-gen` script one last time to build the PHP version of the `runtime-conf.xml` configuration:
{{{
> cd /path/to/bookstore
> propel-gen convert-conf
}}}
The resulting file can be found under `build/conf/bookstore-conf.php`, where "bookstore" is the name of the project you defined in `build.properties`.
'''Tip''': As you saw, a Propel project setup requires that you call three commands with the `propel-gen` script: `om`, `sql`, and `convert-conf`. This is so usual that if you call the `propel-gen` script with no parameter, it will execute these three commands in a row:
{{{
> cd /path/to/bookstore
> propel-gen
}}}
== Setting Up Propel ==
This is the final step: initialize Propel in your PHP script. You may wish to do this step in an init or setup script that is included at the beginning of your PHP scripts.
Here is a sample initialization file:
{{{
#!php
<?php
// Include the main Propel script
require_once 'propel/Propel.php';
// Initialize Propel with the runtime configuration
Propel::init("/path/to/bookstore/build/conf/bookstore-conf.php");
// Add the generated 'classes' directory to the include path
set_include_path("/path/to/bookstore/build/classes" . PATH_SEPARATOR . get_include_path());
}}}
Now you are ready to start using your model classes!

View file

@ -0,0 +1,319 @@
= Basic C.R.U.D. Operations =
[[PageOutline]]
In this chapter, you will learn how to perform basic C.R.U.D. (Create, Retrieve, Update, Delete) operations on your database using Propel.
== Creating Rows ==
To add new data to the database, instantiate a Propel-generated object and then call the `save()` method. Propel will generate the appropriate INSERT SQL from the instantiated object.
But before saving it, you probably want to define the value for its columns. For that purpose, Propel has generated a `setXXX()` method for each of the columns of the table in the model object. So in its simplest form, inserting a new row looks like the following:
{{{
#!php
<?php
/* initialize Propel, etc. */
$author = new Author();
$author->setFirstName('Jane');
$author->setLastName('austen');
$author->save();
}}}
The column names used in the `setXXX()` methods correspond to the `phpName` attribute of the `<column>` tag in your schema, or to a CamelCase version of the column name if the `phpName` is not set.
In the background, the call to `save()` results in the following SQL being executed on the database:
{{{
#!sql
INSERT INTO author (first_name, last_name) VALUES ('Jane', 'Austen');
}}}
== Reading Object Properties ==
Propel maps the columns of a table into properties of the generated objects. For each property, you can use a generated getter to access it.
{{{
#!php
<?php
echo $author->getId(); // 1
echo $author->getFirstName(); // 'Jane'
echo $author->getLastName(); // 'austen'
}}}
The `id` column was set automatically by the database, since the `schema.xml` defines it as an `autoIncrement` column. The value is very easy to retrieve once the object is saved: just call the getter on the column phpName.
These calls don't issue a database query, since the `Author` object is already loaded in memory.
== Retrieving Rows ==
Retrieving objects from the database, also referred to as ''hydrating'' objects, is essentially the process of executing a SELECT query against the database and populating a new instance of the appropriate object with the contents of each returned row.
In Propel, you use the generated Query objects to select existing rows from the database.
=== Retrieving by Primary Key ===
The simplest way to retrieve a row from the database, is to use the generated `findPK()` method. It simply expects the value of the primary key of the row to be retrieved.
{{{
#!php
<?php
$q = new AuthorQuery();
$firstAuthor = $q->findPK(1);
// now $firstBook is an Author object, or NULL if no match was found.
}}}
This issues a simple SELECT SQL query. For instance, for MySQL:
{{{
#!sql
SELECT author.id, author.first_name, author.last_name
FROM `author`
WHERE author.id = 1
LIMIT 1;
}}}
When the primary key consists of more than one column, `findPK()` accepts multiple parameters, one for each primary key column.
'''Tip''': Every generated Query objects offers a factory method called `create()`. This methods creates a new instance of the query, and allows you to write queries in a single line:
{{{
#!php
<?php
$firstAuthor = AuthorQuery::create()->findPK(1);
}}}
You can also select multiple objects based on their primary keys, by calling the generated `findPKs()` method. It takes an array of primary keys as a parameter:
{{{
#!php
<?php
$selectedAuthors = AuthorQuery::create()->findPKs(array(1,2,3,4,5,6,7));
// $selectedAuthors is a collection of Author objects
}}}
=== Querying the Database ===
To retrieve rows other than by the primary key, use the Query's `find()` method.
An empty Query object carries no condition, and returns all the rows of the table
{{{
#!php
<?php
$authors = AuthorQuery::create()->find();
// $authors contains a collection of Author objects
// one object for every row of the author table
foreach($authors as $author) {
echo $author->getFirstName();
}
}}}
To add a simple condition on a given column, use one of the generated `filterByXXX()` methods of the Query object, where `XXX` is a column phpName. Since `filterByXXX()` methods return the current query object, you can continue to add conditions or end the query with the result of the method call. For instance, to filter by first name:
{{{
#!php
<?php
$authors = AuthorQuery::create()
->filterByFirstName('Jane')
->find();
}}}
When you pass a value to a `filterByXXX()` method, Propel uses the column type to escape this value in PDO. This protects you from SQL injection risks.
You can also easily limit and order the results on a query. Once again, the Query methods return the current Query object, so you can easily chain them:
{{{
#!php
<?php
$authors = AuthorQuery::create()
->orderByLastName()
->limit(10)
->find();
}}}
`find()` always returns a collection of objects, even if there is only one result. If you know that you need a single result, use `findOne()` instead of `find()`. It will add the limit and return a single object instead of an array:
{{{
#!php
<?php
$author = AuthorQuery::create()
->filterByFirstName('Jane')
->findOne();
}}}
'''Tip''': Propel provides magic methods for this simple use case. So you can write the above query as:
{{{
#!php
<?php
$author = AuthorQuery::create()->findOneByFirstName('Jane');
}}}
The Propel Query API is very powerful. The next chapter will teach you to use it to add conditions on related objects. If you can't wait, jump to the [wiki:Documentation/1.5/ModelCriteria Query API reference].
=== Using Custom SQL ===
The `Query` class provides a relatively simple approach to constructing a query. Its database neutrality and logical simplicity make it a good choice for expressing many common queries. However, for a very complex query, it may prove more effective (and less painful) to simply use a custom SQL query to hydrate your Propel objects.
As Propel uses PDO to query the underlying database, you can always write custom queries using the PDO syntax. For instance, if you have to use a sub-select:
{{{
#!php
<?php
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$sql = "SELECT * FROM book WHERE id NOT IN "
."(SELECT book_review.book_id FROM book_review"
." INNER JOIN author ON (book_review.author_id=author.ID)"
." WHERE author.last_name = :name)";
$stmt = $con->prepare($sql);
$stmt->execute(array(':name' => 'Tolstoy');
}}}
With only a little bit more work, you can also populate `Book` objects from the resulting statement. Create a new `PropelObjectCollection` for the `Book` model, and call the `format()` method using the statement:
{{{
#!php
<?php
$coll = new PropelObjectCollection();
$coll->setModelName('Book');
$books = $coll->format($stmt);
// $books contains a collection of Book objects
}}}
There are a few important things to remember when using custom SQL to populate Propel:
* The resultset columns must be numerically indexed
* The resultset must contain all columns in the object
* The resultset must have columns ''in the same order'' as they are defined in the `schema.xml` file
== Updating Objects ==
Updating database rows basically involves retrieving objects, modifying the contents, and then saving them. In practice, for Propel, this is a combination of what you've already seen in the previous sections:
{{{
#!php
<?php
$author = AuthorQuery::create()->findOneByFirstName('Jane');
$author->setLastName('Austen');
$author->save();
}}}
Alternatively, you can update several rows based on a Query using the query object's `update()` method:
{{{
#!php
<?php
AuthorQuery::create()
->filterByFirstName('Jane')
->update(array('LastName' => 'Austen'));
}}}
This last method is better for updating several rows at once, or if you didn't retrieve the objects before.
== Deleting Objects ==
Deleting objects works the same as updating them. You can either delete an existing object:
{{{
#!php
<?php
$author = AuthorQuery::create()->findOneByFirstName('Jane');
$author->delete();
}}}
Or use the `delete()` method in the query:
{{{
#!php
<?php
AuthorQuery::create()
->filterByFirstName('Jane')
->delete();
}}}
'''Tip''': A deleted object still lives in the PHP code. It is marked as deleted and cannot be saved anymore, but you can still read its properties:
{{{
#!php
<?php
echo $author->isDeleted(); // true
echo $author->getFirstName(); // 'Jane'
}}}
== Termination Methods ==
The Query methods that don't return the current query object are called "Termination Methods". You've alread seen come of them: `find()`, `findOne()`, `update()`, `delete()`. There are two more termination methods that you should know about:
{{{
#!php
<?php
// count() returns the number of results of the query.
$nbAuthors = AuthorQuery::create()->count();
// You could also count the number of results from a find(), but that would be less effective,
// since it implies hydrating objects just to count them
// paginate() returns a paginated list of results
$authorPager = AuthorQuery::create()->paginate($page = 1, $maxPerPage = 10);
// This method will compute an offset and a limit
// based on the number of the page and the max number of results per page.
// The result is a PropelModelPager object, over which you can iterate:
foreach ($authorPager as $author) {
echo $author->getFirstName();
}
// a pager object gives more information
echo $pager->getNbResults(); // total number of results if not paginated
echo $pager->haveToPaginate(); // return true if the total number of results exceeds the maximum per page
echo $pager->getFirstIndex(); // index of the first result in the page
echo $pager->getLastIndex(); // index of the last result in the page
$links = $pager->getLinks(5); // array of page numbers around the current page; useful to display pagination controls
}}}
== Collections And On-Demand Hydration ==
The `find()` method of generated Model Query objects returns a `PropelCollection` object. You can use this object just like an array of model objects, iterate over it using `foreach`, access the objects by key, etc.
{{{
#!php
<?php
$authors = AuthorQuery::create()
->limit(5)
->find();
foreach ($authors as $author) {
echo $authors->getFirstName();
}
}}}
The advantage of using a collection instead of an array is that Propel can hydrate model objects on demand. Using this feature, you'll never fall short of memory when retrieving a large number of results. Available through the `setFormatter()` method of Model Queries, on-demand hydration is very easy to trigger:
{{{
#!php
<?php
$authors = AuthorQuery::create()
->limit(50000)
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) // just add this line
->find();
foreach ($authors as $author) {
echo $author->getFirstName();
}
}}}
In this example, Propel will hydrate the `Author` objects row by row, after the `foreach` call, and reuse the memory between each iteration. The consequence is that the above code won't use more memory when the query returns 50,000 results than when it returns 5.
`ModelCriteria::FORMAT_ON_DEMAND` is one of the many formatters provided by the Query objects. You can also get a collection of associative arrays instead of objects, if you don't need any of the logic stored in your model object, by using `ModelCriteria::FORMAT_ARRAY`.
The [wiki:Documentation/1.5/ModelCriteria Query API reference] describes each formatter, and how to use it.
== Propel Instance Pool ==
Propel keeps a list of the objects that you already retrieved in memory to avoid calling the same request twice in a PHP script. This list is called the instance pool, and is automatically populated from your past requests:
{{{
#!php
<?php
// first call
$author1 = AuthorQuery::create()->findPk(1);
// Issues a SELECT query
...
// second call
$author2 = AuthorQuery::create()->findPk(1);
// Skips the SQL query and returns the existing $author1 object
}}}

View file

@ -0,0 +1,386 @@
= Basic Relationships =
[[PageOutline]]
The definition of foreign keys in your schema allows Propel to add smart methods to the generated model and query objects. In practice, these generated methods mean that you will never actually have to deal with primary and foreign keys yourself. It makes the task of dealing with relations extremely straightforward.
== Inserting A Related Row ==
Propel creates setters for related objects that simplify the foreign key handling. You don't actually have to define a foreign key value. Instead, just set a related object, as follows:
{{{
#!php
<?php
$author = new Author();
$author->setFirstName("Leo");
$author->setLastName("Tolstoy");
$author->save();
$book = new Book();
$book->setTitle("War & Peace");
// associate the $author object with the current $book
$book->setAuthor($author);
$book->save();
}}}
Propel generates the `setAuthor()` method based on the `phpName` attribute of the `<foreign-key>` element in the schema. When the attribute is not set, Propel uses the `phpName` of the related table instead.
Internally, the call to `Book::setAuthor($author)` translates into `Book::setAuthorId($author->getId())`. But you don't actually have to save a Propel object before associating it to another. In fact, Propel automatically "cascades" INSERT statements when a new object has other related objects added to it.
For one-to-many relationships - meaning, from the other side of a many-to-one relationship - the process is a little different. In the previous example, one `Book` has one `Author`, but one `Author` has many `Books`. From the `Author` point of view, a one-to-many relationships relates it to `Book`. So Propel doesn't generate an `Author::setBook()`, but rather an `Author::addBook()`:
{{{
#!php
<?php
$book = new Book();
$book->setTitle("War & Peace");
// associate the $author object with the current $book
$book->save();
$author = new Author();
$author->setFirstName("Leo");
$author->setLastName("Tolstoy");
$author->addBook($book);
$author->save();
}}}
The result is the same in the database - the `author_id` column of the `book` row is correctly set to the `id` of the `author` row.
== Save Cascade ==
As a matter of fact, you don't need to `save()` an object before relating it. Propel knows which objects are related to each other, and is capable of saving all the unsaved objects if they are related to each other.
The following example shows how to create new `Author` and `Publisher` objects, which are then added to a new `Book` object; all 3 objects are saved when the `Book::save()` method is eventually invoked.
{{{
#!php
<?php
/* initialize Propel, etc. */
$author = new Author();
$author->setFirstName("Leo");
$author->setLastName("Tolstoy");
// no need to save the author yet
$publisher = new Publisher();
$publisher->setName("Viking Press");
// no need to the publisher yet
$book = new Book();
$book->setTitle("War & Peace");
$book->setIsbn("0140444173");
$book->setPublisher($publisher);
$book->setAuthor($author);
$book->save(); // saves all 3 objects!
}}}
In practice, Propel '''cascades''' the `save()` action to the related objects.
== Reading Related Object Properties ==
Just like the related object setters, Propel generates a getter for every relation:
{{{
#!php
<?php
$book = BookQuery()::create()->findPk(1);
$author = $book->getAuthor();
echo $author->getFirstName(); // 'Leo'
}}}
Since a relationship can also be seen from the other end, Propel allows the foreign table to retrieve the related objects as well:
{{{
#!php
<?php
$author = AuthorQuery::create()->findPk(1);
$books = $author->getBooks();
foreach ($books as $book) {
echo $book->getTitle();
}
}}}
Notice that Propel generated a `getBooks()` method returning an array of `Book` objects, rather than a `getBook()` method. This is because the definition of a foreign key defines a many-to-one relationship, seen from the other end as a one-to-many relationship.
'''Tip''': Propel also generates a `countBooks()` methods to get the number of related objects without hydrating all the `Book` objects. for performance reasons, you should prefer this method to `count($author->getBooks())`.
Getters for one-to-many relationship accept an optional query object. This allows you to hydrate related objects, or retrieve only a subset of the related objects, or to reorder the list of results:
{{{
#!php
<?php
$query = BookQuery::create()
->orderByTitle()
->joinWith('Book.Publisher');
$books = $author->getBooks($query);
}}}
== Using Relationships In A Query ==
=== Finding Records Related To Another One ===
If you need to find objects related to a model object that you already have, you can take advantage of the generated `filterByXXX()` methods in the query objects, where `XXX` is a relation name:
{{{
#!php
<?php
$author = AuthorQuery::create()->findPk(1);
$books = BookQuery::create()
->filterByAuthor($author)
->orderByTitle()
->find();
}}}
You don't need to specify that the `author_id` column of the `Book` object should match the `id` column of the `Author` object. Since you already defined the foreign key mapping in your schema, Propel knows enough to figure it out.
=== Embedding Queries ===
In SQL queries, relationships often translate to a JOIN statement. Propel abstracts this relational logic in the query objects, by allowing you to ''embed'' a related query into another.
In practice, Propel generates one `useXXXQuery()` method for every relation in the Query objects. So the `BookQuery` class offers a `useAuthorQuery()` and a `usePublisherQuery()` method. These methods return a new Query instance of the related query class, that you can eventually merge into the main query by calling `endUse()`.
To illustrate this, let's see how to write the following SQL query with the Propel Query API:
{{{
#!sql
SELECT book.*
FROM book INNER JOIN author ON book.AUTHOR_ID = author.ID
WHERE book.ISBN = '0140444173' AND author.FIRST_NAME = 'Leo'
ORDER BY book.TITLE ASC
LIMIT 10;
}}}
That would simply give:
{{{
#!php
<?php
$books = BookQuery::create()
->filterByISBN('0140444173')
->useAuthorQuery() // returns a new AuthorQuery instance
->filterByFirstName('Leo') // this is an AuthorQuery method
->endUse() // merges the Authorquery in the main Bookquery and returns the BookQuery
->orderByTitle()
->limit(10)
->find();
}}}
Propel knows the columns to use in the `ON` clause from the definition of foreign keys in the schema. The ability to use methods of a related Query object allows you to keep your model logic where it belongs.
Of course, you can embed several queries to issue a query of any complexity level:
{{{
#!php
<?php
// Find all authors of books published by Viking Press
$authors = AuthorQuery::create()
->useBookQuery()
->usePublisherQuery()
->filterByName('Viking Press')
->endUse()
->endUse()
->find();
}}}
You can see how the indentation of the method calls provide a clear explanation of the embedding logic. That's why it is a good practice to format your Propel queries with a single method call per line, and to add indentation every time a `useXXXQuery()` method is used.
== Many-to-Many Relationships ==
Databases typically use a cross-reference table, or junction table, to materialize the relationship. For instance, if the `user` and `group` tables are related by a many-to-many relationship, this happens through the rows of a `user_group` table. To inform Propel about the many-to-many relationship, set the `isCrossRef` attribute of the cross reference table to true:
{{{
#!xml
<table name="user">
<column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
<column name="name" type="VARCHAR" size="32"/>
</table>
<table name="group">
<column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
<column name="name" type="VARCHAR" size="32"/>
</table>
<table name="user_group" isCrossRef="true">
<column name="user_id" type="INTEGER" primaryKey="true"/>
<column name="group_id" type="INTEGER" primaryKey="true"/>
<foreign-key foreignTable="user">
<reference local="user_id" foreign="id"/>
</foreign-key>
<foreign-key foreignTable="group">
<reference local="group_id" foreign="id"/>
</foreign-key>
</table>
}}}
Once you rebuild your model, the relationship is seen as a one-to-many relationship from both the `User` and the `Group` models. That means that you can deal with adding and reading relationships the same way as you usually do:
{{{
#!php
<?php
$user = new User();
$user->setName('John Doe');
$group = new Group();
$group->setName('Anonymous');
// relate $user and $group
$user->addGroup($group);
// save the $user object, the $group object, and a new instance of the UserGroup class
$user->save();
}}}
The same happens for reading related objects ; Both ends see the relationship as a one-to-many relationship:
{{{
#!php
<?php
$users = $group->getUsers();
$nbUsers = $group->countUsers();
$groups = $user->getGroups();
$nbGroups = $user->countGroups();
}}}
Just like regular related object getters, these generated methods accept an optional query object, to further filter the results.
To facilitate queries, Propel also adds new methods to the `UserQuery` and `GroupQuery` classes:
{{{
#!php
<?php
$users = UserQuery::create()
->filterByGroup($group)
->find();
$groups = GroupQuery::create()
->filterByUser($user)
->find();
}}}
== One-to-One Relationships ==
Propel supports the special case of one-to-one relationships. These relationships are defined when the primary key is also a foreign key. For example :
{{{
#!xml
<table name="bookstore_employee" description="Employees of a bookstore">
<column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
<column name="name" type="VARCHAR" size="32"/>
</table>
<table name="bookstore_employee_account" description="Bookstore employees' login credentials">
<column name="employee_id" type="INTEGER" primaryKey="true"/>
<column name="login" type="VARCHAR" size="32"/>
<column name="password" type="VARCHAR" size="100"/>
<foreign-key foreignTable="bookstore_employee">
<reference local="employee_id" foreign="id"/>
</foreign-key>
</table>
}}}
Because the primary key of the `bookstore_employee_account` is also a foreign key to the `bookstore_employee` table, Propel interprets this as a one-to-one relationship and will generate singular methods for both sides of the relationship (`BookstoreEmployee::getBookstoreEmployeeAccount()`, and `BookstoreEmployeeAccount::getBookstoreEmployee()`).
== On-Update and On-Delete Triggers =
Propel also supports the ''ON UPDATE'' and ''ON DELETE'' aspect of foreign keys. These properties can be specified in the `<foreign-key>` tag using the `onUpdate` and `onDelete` attributes. Propel supports values of `CASCADE`, `SETNULL`, and `RESTRICT` for these attributes. For databases that have native foreign key support, these trigger events will be specified at the datbase level when the foreign keys are created. For databases that do not support foreign keys, this functionality will be emulated by Propel.
{{{
#!xml
<table name="review">
<column name="review_id" type="INTEGER" primaryKey="true" required="true"/>
<column name="reviewer" type="VARCHAR" size="50" required="true"/>
<column name="book_id" required="true" type="INTEGER"/>
<foreign-key foreignTable="book" onDelete="CASCADE">
<reference local="book_id" foreign="id"/>
</foreign-key>
</table>
}}}
In the example above, the `review` rows will be automatically removed if the related `book` row is deleted.
== Minimizing Queries ==
Even if you use a foreign query, Propel will issue new queries when you fetch related objects:
{{{
#!php
<?php
$book = BookQuery::create()
->useAuthorQuery()
->filterByFirstName('Leo')
->endUse()
->findOne();
$author = $book->getAuthor(); // Needs another database query
}}}
Propel allows you to retrieve the main object together with related objects in a single query. You just the `with()` method to specify which objects the main object should be hydrated with.
{{{
#!php
<?php
$book = BookQuery::create()
->useAuthorQuery()
->filterByFirstName('Leo')
->endUse()
->with('Author')
->findOne();
$author = $book->getAuthor(); // Same result, with no supplementary query
}}}
Since the call to `with()` adds the columns of the related object to the SELECT part of the query, and uses these columns to populate the related object, that means that a query using `with()` is slower and consumes more memory. So use it only when you actually need the related objects afterwards.
If you don't want to add a filter on a related object but still need to hydrate it, calling `useXXXQuery()`, `endUse()`, and then `with()` can be a little cumbersome. For this case, Propel provides a proxy method called `joinWith()`. It expects a string made of the initial query name and the foreign query name. For instance:
{{{
#!php
<?php
$book = BookQuery::create()
->joinWith('Book.Author')
->findOne();
$author = $book->getAuthor(); // Same result, with no supplementary query
}}}
`with()` and `joinWith()` are not limited to immediate relationships. As a matter of fact, just like you can nest `use()` calls, you can call `with()` several times to populate a chain of objects:
{{{
#!php
<?php
$review = ReviewQuery::create()
->joinWith('Review.Book')
->joinWith('Book.Author')
->joinWith('Book.Publisher')
->findOne();
$book = $review->getBook() // No additional query needed
$author = $book->getAuthor(); // No additional query needed
$publisher = $book->getPublisher(); // No additional query needed
}}}
So `with()` is very useful to minimize the number of database queries. As soon as you see that the number of queries necessary to perform an action is proportional to the number of results, adding a `with()` call is the trick to get down to a more reasonnable query count.
'''Tip''': `with()` also works for left joins on one-to-many relationships, but you musn't use a `limit()` in the query in this case. This is because Propel has no way to determine the actual number of rows of the main object in such a case.
{{{
#!php
<?php
// this works
$authors = AuthorQuery::create()
->leftJoinWith('Author.Book')
->find();
// this does not work
$authors = AuthorQuery::create()
->leftJoinWith('Author.Book')
->limit(5)
->find();
}}}
However, it is quite easy to achieve hydration of related objects with only one additional query:
{{{
#!php
<?php
// $authors is a PropelObjectCollection
$authors = AuthorQuery::create()->find();
$authors->populateRelation('Book');
// now you can iterate over each author's book without further queries
foreach ($authors as $author) {
foreach ($authors->getBooks() as $book) { // no database query, the author already has a Books collection
// do stuff with $book and $author
}
}
}}}

View file

@ -0,0 +1,253 @@
= Validators =
[[PageOutline]]
Validators help you to validate an input before perstisting it to the database. In Propel, validators are rules describing what type of data a column accepts. Validators are referenced in the `schema.xml` file, using `<validator>` tags.
Validators are applied at the PHP level, they are not created as constraints on the database itself. That means that if you also use another language to work with the database, the validator rules will not be enforced.
You can also apply multiple rule entries per validator entry in the schema.xml file.
== Overview ==
In the following example, the `username` column is defined to have a minimum length of 4 characters:
{{{
#!xml
<table name="user">
<column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
<column name="username" type="VARCHAR" size="34" required="true" />
<validator column="username">
<rule name="minLength" value="4" message="Username must be at least ${value} characters !" />
</validator>
</table>
}}}
Every column rule is represented by a `<rule>` tag. A `<validator>` is a set of `<rule>` tags bound to a column.
At runtime, you can validate an instance of the model by calling the `validate()` method:
{{{
#!php
<?php
$user = new User();
$user->setUsername("foo"); // only 3 in length, which is too short...
if ($objUser->validate()) {
// no validation errors, so the data can be persisted
$user->save();
} else {
// Something went wrong.
// Use the validationFailures to check what
$failures = $objUser->getValidationFailures();
foreach($failures as $failure) {
echo $objValidationFailure->getMessage() . "<br />\n";
}
}
}}}
`validate()` returns a boolean. If the validation failed, you can access the array `ValidationFailed` objects by way of the `getValidationFailures()` method. Each `ValidationFailed` instance gives access to the column, the messagen and the validator that caused the failure.
== Core Validators ==
Propel bundles a set of validatorts that should help you deal with the most common cases.
=== !MatchValidator ===
The `MatchValidator` is used to run a regular expression of choice against the column. Note that this is a `preg`, not `ereg` (check [http://www.php.net/preg_match the preg_match documentation] for more information about regexps).
{{{
#!xml
<validator column="username">
<!-- allow strings that match the email adress pattern -->
<rule
name="match"
value="/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9])+(\.[a-zA-Z0-9_-]+)+$/"
message="Please enter a valid email address." />
</validator>
}}}
=== !NotMatchValidator ===
Opposite of `MatchValidator, this validator returns false if the regex returns true
{{{
#!xml
<column name="ISBN" type="VARCHAR" size="20" required="true" />
<validator column="ISBN">
<!-- disallow everything that's not a digit or minus -->
<rule
name="notMatch"
value="/[^\d-]+/"
message="Please enter a valid ISBN" />
</validator>
}}}
=== !MaxLengthValidator ===
When you want to limit the size of the string to be inserted in a column, use the `MaxLengthValidator`. Internally, it uses `strlen()` to get the length of the string. For instance, some database completely ignore the lentgh of `LONGVARCHAR` columns; you can enforce it using a validator:
{{{
#!xml
<column name="comment" type="LONGVARCHAR" required="true" />
<validator column="comment">
<rule
name="maxLength"
value="1024"
message="Comments can be no larger than ${value} in size" />
</validator>
}}}
'''Tip''': If you have specified the `size` attribute in the `<column>` tag, you don't have to specify the `value` attribute in the validator rule again, as this is done automatically.
=== !MinLengthValidator ===
{{{
#!xml
<column name="username" type="VARCHAR" size="34" required="true" />
<validator column="username">
<rule
name="minLength"
value="4"
message="Username must be at least ${value} characters !" />
</validator>
}}}
=== !MaxValueValidator ===
To limit the value of an integer column, use the `MaxValueValidator`. Note that this validator uses a non-strict comparison ('less than or equal'):
{{{
#!xml
<column name="security_level" type="INTEGER" required="true" />
<validator column="security_level">
<rule
name="maxValue"
value="1000"
message="Maximum security level is ${value} !" />
</validator>
}}}
=== !MinValueValidator ===
{{{
#!xml
<column name="cost" type="INTEGER" required="true" />
<validator column="cost">
<rule
name="minValue"
value="0"
message="Products can cost us negative $ can they?" />
</validator>
}}}
'''Tip''': You can run multiple validators against a single column.
{{{
#!xml
<column name="security_level" type="INTEGER" required="true" default="10" />
<validator column="security_level" translate="none">
<rule
name="minValue"
value="0"
message="Invalid security level, range: 0-10" />
<rule
name="maxValue"
value="10"
message="Invalid security level, range: 0-10" />
</validator>
}}}
=== !RequiredValidator ===
This validtor checks the same rule as a `required=true` on the column at the database level. However it will not give you a clean error to work with.
{{{
#!xml
<column name="username" type="VARCHAR" size="25" required="true" />
<validator column="username">
<rule
name="required"
message="Username is required." />
</validator>
}}}
=== !UniqueValidator ===
To check whether the value already exists in the table, use the `UniqueValidator`:
{{{
#!xml
<column name="username" type="VARCHAR" size="25" required="true" />
<validator column="username">
<rule
name="unique"
message="Username already exists !" />
</validator>
}}}
=== !ValidValuesValidator ===
This rule restricts the valid values to a list delimited by a pipe ('|').
{{{
#!xml
<column name="address_type" type="VARCHAR" required="true" default="delivery" />
<validator column="address_type">
<rule
name="validValues"
value="account|delivery"
message="Please select a valid address type." />
</validator>
}}}
=== !TypeValidator ===
Restrict values to a certain PHP type using the `TypeValidator`:
{{{
#!xml
<column name="username" type="VARCHAR" size="25" required="true" />
<validator column="username">
<rule
name="type"
value="string"
message="Username must be a string" />
</validator>
}}}
== Adding A Custom Validator ==
You can easily add a custom validator. A validator is a class extending `BasicValidator` providing a public `isValid()` method. For instance:
{{{
#!php
<?php
require_once 'propel/validator/BasicValidator.php';
/**
* A simple validator for email fields.
*
* @package propel.validator
*/
class EmailValidator implements BasicValidator
{
public function isValid(ValidatorMap $map, $str)
{
return preg_match('/^([^@\s]+)@((?:[-a-z0-9]+\.)+[a-z]{2,})$/i', $str) !== 0;
}
}
}}}
The `ValidatorMap` instance passed as parameter gives you access to the rules attribute as defined in the `<rule>` tag. So `$map->getValue()` returns the `value` attribute.
'''Tip''': Make sure that `isValid()` returns a boolean, so really true or false. Propel is very strict about this. Returning a mixed value just won't do.
To enable the new validator on a column, add a corresponding `<rule>` in your schema and use 'class' as the rule `name`.
{{{
#!xml
<validator column="<column_name>">
<rule name="class" class="my.dir.EmailValidator" message="Invalid e-mail address!" />
</validator>
}}}
The `class` attribute of the `<rule>` tag should contain a path to the validator class accessible from the include_path, where the directory separator is replaced by a dot.

View file

@ -0,0 +1,291 @@
= Transactions =
[[PageOutline]]
Database transactions are the key to assure the data integrity and the performance of database queries. Propel uses transactions internally, and provides a simple API to use them in your own code.
'''Tip''': If the [http://en.wikipedia.org/wiki/ACID ACID] acronym doesn't ring a bell, you should probably learn some [http://en.wikipedia.org/wiki/Database_transaction fundamentals about database transactions] before reading further.
== Wrapping Queries Inside a Transaction ==
Propel uses PDO as database abstraction layer, and therefore uses [http://www.php.net/manual/en/pdo.transactions.php PDO's built-in support for database transactions]. The syntax is the same, as you can see in the classical "money transfer" example:
{{{
#!php
<?php
public function transferMoney($fromAccountNumber, $toAccountNumber, $amount)
{
// get the PDO connection object from Propel
$con = Propel::getConnection(AccountPeer::DATABASE_NAME);
$fromAccount = AccountPeer::retrieveByPk($fromAccountNumber, $con);
$toAccount = AccountPeer::retrieveByPk($toAccountNumber, $con);
$con->beginTransaction();
try {
// remove the amount from $fromAccount
$fromAccount->setValue($fromAccount->getValue() - $amount);
$fromAccount->save($con);
// add the amount to $toAccount
$toAccount->setValue($toAccount->getValue() + $amount);
$toAccount->save($con);
$con->commit();
} catch (Exception $e) {
$con->rollback();
throw $e;
}
}
}}}
The transaction statements are `beginTransaction()`, `commit()` and `rollback()`, which are methods of the PDO connection object. Transaction methods are typically used inside a `try/catch` block. The exception is rethrown after rolling back the transaction: That ensures that the user knows that something wrong happenned.
In this example, if something wrong happens while saving either one of the two accounts, an `Exception` is thrown, and the whole operation is rolled back. That means that the transfer is cancelled, with an insurance that the money hasn't vanished (that's the A in ACID, which stands for "Atomicity"). If both account modifications work as expected, the whole transaction is committed, meaning that the data changes enclosed in the transaction are persisted in the database.
Tip: In order to build a transaction, you need a connection object. The connection object for a Propel model is always available through `Propel::getConnection([ModelName]Peer::DATABASE_NAME)`.
== Denormalization And Transactions ==
Another example of the use of transactions is for [http://en.wikipedia.org/wiki/Denormalization denormalized schemas].
For instance, suppose that you have an `Author` model with a one to many relationship to a `Book` model. every time you need to display the number of books written by an author, you call `countBooks()` on the author object, which issues a new query to the database:
{{{
#!php
<ul>
<?php foreach ($authors as $author): ?>
<li><?php echo $author->getName() ?> (<?php echo $author->countBooks() ?> books)</li>
<?php endforeach; ?>
</ul>
}}}
If you have a large number of authors and books, this simple code snippet can be a real performance blow to your application. The usual way to optimize it is to ''denormalize'' your schema by storing the number of books by each author in a new `nb_books` column, in the `author` table.
{{{
#!xml
<table name="book">
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
<column name="title" type="VARCHAR" required="true" />
<column name="nb_books" type="INTEGER" default="0" />
</table>
}}}
You must update this new column every time you save or delete a `Book` object; this will make write queries a little slower, but read queries much faster. Fortunately, Propel model objects support pre- and post- hooks for the `save()` and `delete()` methods, so this is quite easy to implement:
{{{
#!php
<?php
class Book extends BaseBook
{
public function postSave(PropelPDO $con)
{
$this->updateNbBooks($con);
}
public function postDelete(PropelPDO $con)
{
$this->updateNbBooks($con);
}
public function updateNbBooks(PropelPDO $con)
{
$author = $this->getAuthor();
$nbBooks = $author->countBooks($con);
$author->setNbBooks($nbBooks);
$author->save($con);
}
}
}}}
The `BaseBook::save()` method wraps the actual database INSERT/UPDATE query inside a transaction, together with any other query registered in a pre- or post- save hook. That means that when you save a book, the `postSave()` code is executed in the same transaction as the actual `$book->save()` method. Everything happens as is the code was the following:
{{{
#!php
<?php
class Book extends BaseBook
{
public function save(PropelPDO $con)
{
$con->beginTransaction();
try {
// insert/update query for the current object
$this->doSave($con);
// postSave hook
$author = $this->getAuthor();
$nbBooks = $author->countBooks($con);
$author->setNbBooks($nbBooks);
$author->save($con);
$con->commit();
} catch (Exception $e) {
$con->rollback();
throw $e;
}
}
}
}}}
In this example, the `nb_books` column of the `author` table will always we synchronized with the number of books. If anything happens during the transaction, the saving of the book is rolled back, as well as the `nb_books` column update. The transaction serves to preserve data consistency in a denormalized schema ("Consistency" stands for the C in ACID).
'''Tip''': Check the [wiki:Documentation/1.5/Behaviors behaviors documentation] for details about the pre- and post- hooks in Propel model objects.
== Nested Transactions ==
Some RDBMS offer the ability to nest transactions, to allow partial rollback of a set of transactions. PDO does not provide this ability at the PHP level; nevertheless, Propel emulates nested transactions for all supported database engines:
{{{
#!php
<?php
function deleteBooksWithNoPrice(PropelPDO $con)
{
$con->beginTransaction();
try {
$c = new Criteria();
$c->add(BookPeer::PRICE, null, Criteria::ISNULL);
BookPeer::doDelete($c, $con);
$con->commit();
} catch (Exception $e) {
$con->rollback();
throw $e;
}
}
function deleteAuthorsWithNoEmail(PropelPDO $con)
{
$con->beginTransaction();
try {
$c = new Criteria();
$c->add(AuthorPeer::EMAIL, null, Criteria::ISNULL);
AuthorPeer::doDelete($c, $con);
$con->commit();
} catch (Exception $e) {
$con->rollback();
throw $e;
}
}
function cleanup(PropelPDO $con)
{
$con->beginTransaction();
try {
deleteBooksWithNoPrice($con);
deleteAuthorsWithNoEmail($con);
$con->commit();
} catch (Exception $e) {
$con->rollback();
throw $e;
}
}
}}}
All three functions alter data in a transaction, ensuring data integrity for each. In addition, the `cleanup()` function actually executes two nested transactions inside one main transaction.
Propel deals with this case by seeing only the outermost transaction, and ignoring the `beginTransaction()`, `commit()` and `rollback()` statements of nested transactions. If nothing wrong happens, then the last `commit()` call (after both `deleteBooksWithNoPrice()` and `deleteAuthorsWithNoEmail()` end) triggers the actual database commit. However, if an exception is thrown in either one of these nested transactions, it is escalated to the main `catch` statement in `cleanup()` so that the entire transaction (starting at the main `beginTransaction()`) is rolled back.
So you can use transactions everywhere it's necessary in your code, without worrying about nesting them. Propel will always commit or rollback everything altogether, whether the RDBMS supports nested transactions or not.
'''Tip''': This allows you to wrap all your application code inside one big transaction for a better integrity.
== Using Transactions To Boost Performance ==
A database transaction has a cost in terms of performance. In fact, for simple data manipulation, the cost of the transaction is more important than the cost of the query itself. Take the following example:
{{{
#!php
<?php
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
for ($i=0; $i<2002; $i++)
{
$book = new Book();
$book->setTitle($i . ': A Space Odyssey');
$book->save($con);
}
}}}
As explained earlier, Propel wraps every save operation inside a transaction. In terms of execution time, this is very expensive. Here is how the above code would translate to MySQL in an InnodDB table:
{{{
#!sql
BEGIN;
INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'0: A Space Odyssey');
COMMIT;
BEGIN;
INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'1: A Space Odyssey');
COMMIT;
BEGIN;
INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'2: A Space Odyssey');
COMMIT;
...
}}}
You can take advantage of Propel's nested transaction capabilities to encapsulate the whole loop inside one single transaction. This will reduce the execution time drastically:
{{{
#!php
<?php
$con = Propel::getConnection(BookPeer::DATABASE_NAME);
$con->beginTransaction();
for ($i=0; $i<2002; $i++)
{
$book = new Book();
$book->setTitle($i . ': A Space Odyssey');
$book->save($con);
}
$con->commit();
}}}
The transactions inside each `save()` will become nested, and therefore not translated into actual database transactions. Only the outmost transaction will become a database transaction. So this will translate to MySQL as:
{{{
#!sql
BEGIN;
INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'0: A Space Odyssey');
INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'1: A Space Odyssey');
INSERT INTO book (`ID`,`TITLE`) VALUES (NULL,'2: A Space Odyssey');
...
COMMIT;
}}}
In practice, encapsulating a large amount of simple queries inside a single transaction significantly improves performance.
Tip: Until the final `commit()` is called, most database engines lock updated rows, or even tables, to prevent any query outside the transaction from seeing the partially committed data (this is how transactions preserve Isolation, which is the I in ACID). That means that large transactions will queue every other queries for potentially a long time. Consequently, use large transactions only when concurrency is not a requirement.
== Why Is The Connection Always Passed As Parameter? ==
All the code examples in this chapter show the connection object passed a a parameter to Propel methods that trigger a database query:
{{{
#!php
<?php
$con = Propel::getConnection(AccountPeer::DATABASE_NAME);
$fromAccount = AccountPeer::retrieveByPk($fromAccountNumber, $con);
$fromAccount->setValue($fromAccount->getValue() - $amount);
$fromAccount->save($con);
}}}
The same code works without explicitely passing the connection object, because Propel knows how to get the right connection from a Model:
{{{
#!php
<?php
$fromAccount = AccountPeer::retrieveByPk($fromAccountNumber);
$fromAccount->setValue($fromAccount->getValue() - $amount);
$fromAccount->save();
}}}
However, it's a good practice to pass the connection explicitely, and for three reasons:
* Propel doesn't need to look for a connection object, and this results in a tiny boost in performance.
* You can use a specific connection, which is required in distributed (master/slave) environments, in order to distinguish read and write operations.
* Most importantly, transactions are tied to a single connection. You can't enclose two queries using different connections in a single transaction. So it's very useful to identify the connection you want to use for every query, as Propel will throw an exception if you use the wrong connection.
== Limitations ==
* Currently there is no support for row locking (e.g. `SELECT blah FOR UPDATE`).
* You must rethrow the exception caught in the `catch` statement of nested transactions, otherwise there is a risk that the global rollback doesn't occur.
* True nested transactions, with partial rollback, are only possible in MSSQL, and can be emulated in other RDBMS through savepoints. This feature may be added to Propel in the future, but for the moment, only the outermost PHP transaction triggers a database transaction.
* If you rollback a partially executed transaction and ignore the exception thrown, there are good chances that some of your objects are out of sync with the database. The good practice is to always let a transaction exception escalate until it stops the script execution.

View file

@ -0,0 +1,280 @@
= Behaviors =
[[PageOutline]]
Behaviors are a great way to package model extensions for reusability. They are the powerful, versatile, fast, and help you organize your code in a better way.
== Pre and Post Hooks For `save()` And `delete()` Methods ==
The `save()` and `delete()` methods of your generated objects are easy to override. In fact, Propel looks for one of the following methods in your objects and executes them when needed:
{{{
#!php
<?php
// save() hooks
preInsert() // code executed before insertion of a new object
postInsert() // code executed after insertion of a new object
preUpdate() // code executed before update of an existing object
postUpdate() // code executed after update of an existing object
preSave() // code executed before saving an object (new or existing)
postSave() // code executed after saving an object (new or existing)
// delete() hooks
preDelete() // code executed before deleting an object
postDelete() // code executed after deleting an object
}}}
For example, you may want to keep track of the creation date of every row in the `book` table. In order to achieve this behavior, you can add a `created_at` column to the table in `schema.xml`:
{{{
#!xml
<table name="book">
...
<column name="created_at" type="timestamp" />
</table>
}}}
Then, you can force the update of the `created_at` column before every insertion as follows:
{{{
#!php
<?php
class Book extends BaseBook
{
public function preInsert(PropelPDO $con = null)
{
$this->setCreatedAt(time());
return true;
}
}
}}}
Whenever you call `save()` on a new object, Propel now executes the `preInsert()` method on this objects and therefore update the `created_at` column:
{{{
#!php
<?php
$b = new Book();
$b->setTitle('War And Peace');
$b->save();
echo $b->getCreatedAt(); // 2009-10-02 18:14:23
}}}
If you implement `preInsert()`, `preUpdate()`, `preSave()` or `preDelete()`, these methods must return a boolean value. This determines whether the action (save or delete) may proceed.
'''Tip''': Since this feature adds a small overhead to write operations, you can deactivate it completely in your build properties by setting `propel.addHooks` to `false`.
{{{
#!ini
# -------------------
# TEMPLATE VARIABLES
# -------------------
propel.addHooks = false
}}}
== Introducing Behaviors ==
When several of your custom model classes end up with similar methods added, it is time to refactor the common code.
For example, you may want to add the same ability you gave to `Book` to all the other objects in your model. Let's call this the "Timestampable behavior", because then all of your rows have a timestamp marking their creation. In order to achieve this behavior, you have to repeat the same operations on every table. First, add a `created_at` column to the other tables:
{{{
#!xml
<table name="book">
...
<column name="created_at" type="timestamp" />
</table>
<table name="author">
...
<column name="created_at" type="timestamp" />
</table>
}}}
Then, add a `preInsert()` hook to the object stub classes:
{{{
#!php
<?php
class Book extends BaseBook
{
public function preInsert()
{
$this->setCreatedAt(time());
}
}
class Author extends BaseAuthor
{
public function preInsert()
{
$this->setCreatedAt(time());
}
}
}}}
Even if the code of this example is very simple, the repetition of code is already too much. Just imagine a more complex behavior, and you will understand that using the copy-and-paste technique soon leads to a maintenance nightmare.
Propel offers three ways to achieve the refactoring of the common behavior. The first one is to use a custom builder during the build process. This can work if all of your models share one single behavior. The second way is to use table inheritance. The inherited methods then offer limited capabilities. And the third way is to use Propel behaviors. This is the right way to refactor common model logic.
Behaviors are special objects that use events called during the build process to enhance the generated model classes. Behaviors can add attributes and methods to both the Peer and model classes, they can modify the course of some of the generated methods, and they can even modify the structure of a database by adding columns or tables.
For instance, Propel bundles a behavior called `timestampable`, which does exatcly the same thing as described above. But instead of adding columns and methods by hand, all you have to do is to declare it in a `<behavior>` tag in your `schema.xml`, as follows:
{{{
#!xml
<table name="book">
...
<behavior name="timestampable" />
</table>
<table name="author">
...
<behavior name="timestampable" />
</table>
}}}
Then rebuild your model, and there you go: two columns, `created_at` and `updated_at`, were automatically added to both the `book` and `author` tables. Besides, the generated `BaseBook` and `BaseAuthor` classes already contain the code necessary to auto-set the current time on creation and on insertion.
== Bundled Behaviors ==
Propel currently bundles several behaviors. Check the behavior documentation for details on usage:
* [wiki:Documentation/1.5/Behaviors/aggregate_column aggregate_column]
* [wiki:Documentation/1.5/Behaviors/alternative_coding_standards alternative_coding_standards]
* [wiki:Documentation/1.5/Behaviors/auto_add_pk auto_add_pk]
* [wiki:Documentation/1.5/Behaviors/timestampable timestampable]
* [wiki:Documentation/1.5/Behaviors/sluggable sluggable]
* [wiki:Documentation/1.5/Behaviors/soft_delete soft_delete]
* [wiki:Documentation/1.5/Behaviors/sortable sortable]
* [wiki:Documentation/1.5/Behaviors/nested_set nested_set]
* [wiki:Documentation/1.5/Behaviors/query_cache query_cache]
* And [wiki:Documentation/1.5/Inheritance#ConcreteTableInheritance concrete_inheritance], documented in the Inheritance Chapter even if it's a behavior
Behaviors bundled with Propel require no further installation and work out of the box.
== Customizing Behaviors ==
Behaviors often offer some parameters to tweak their effect. For instance, the `timestampable` behavior allows you to customize the names of the columns added to store the creation date and the update date. The behavior customization occurs in the `schema.xml`, inside `<parameter>` tags nested in the `<behavior>` tag. So let's set the behavior to use `created_on` instead of `created_at` for the creation date column name (and same for the update date column):
{{{
#!xml
<table name="book">
...
<behavior name="timestampable">
<parameter name="create_column" value="created_on" />
<parameter name="update_column" value="updated_on" />
</behavior>
</table>
}}}
If the columns already exist in your schema, a behavior is smart enough not to add them one more time.
{{{
#!xml
<table name="book">
...
<column name="created_on" type="timestamp" />
<column name="updated_on" type="timestamp" />
<behavior name="timestampable">
<parameter name="create_column" value="created_on" />
<parameter name="update_column" value="updated_on" />
</behavior>
</table>
}}}
== Using Third-Party Behaviors ==
As a Propel behavior can be packaged into a single class, behaviors are quite easy to reuse and distribute across several projects. All you need to do is to copy the behavior file into your project, and declare it in `build.properties`, as follows:
{{{
#!ini
# ----------------------------------
# B E H A V I O R S E T T I N G S
# ----------------------------------
propel.behavior.timestampable.class = propel.engine.behavior.timestampable.TimestampableBehavior
# Add your custom behavior pathes here
propel.behavior.formidable.class = path.to.FormidableBehavior
}}}
Propel will then find the `FormidableBehavior` class whenever you use the `formidable` behavior in your schema:
{{{
#!xml
<table name="author">
...
<behavior name="timestampable" />
<behavior name="formidable" />
</table>
}}}
'''Tip''': If you use autoloading during the build process, and if the behavior classes benefit from the autoloading, then you don't even need to declare the path to the behavior class.
== Applying a Behavior To All Tables ==
You can add a `<behavior>` tag directly under the `<database>` tag. That way, the behavior will be applied to all the tables of the database.
{{{
#!xml
<database name="propel">
<behavior name="timestampable" />
<table name="book">
...
</table>
<table name="author">
...
</table>
</database>
}}}
In this example, both the `book` and `author` table benefit from the `timestampable` behavior, and therefore automatically update their `created_at` and `updated_at` columns upon saving.
Going one step further, you can even apply a behavior to all the databases of your project, provided the behavior doesn't need parameters - or can use default parameters. To add a behavior to all databases, simply declare it in the project's `build.properties` under the `propel.behavior.default` key, as follows:
{{{
#!ini
propel.behavior.default = soft_delete, timestampable
}}}
== Writing a Behavior ==
Behaviors can modify their table, and even add another table, by implementing the `modifyTable` method. In this method, use `$this->getTable()` to retrieve the table buildtime model and manipulate it.
Behaviors can add code to the generated model object by implementing one of the following methods:
{{{
objectAttributes() // add attributes to the object
objectMethods() // add methods to the object
preInsert() // add code to be executed before insertion of a new object
postInsert() // add code to be executed after insertion of a new object
preUpdate() // add code to be executed before update of an existing object
postUpdate() // add code to be executed after update of an existing object
preSave() // add code to be executed before saving an object (new or existing)
postSave() // add code to be executed after saving an object (new or existing)
preDelete() // add code to be executed before deleting an object
postDelete() // add code to be executed after deleting an object
objectCall() // add code to be executed inside the object's __call()
objectFilter(&$script) // do whatever you want with the generated code, passed as reference
}}}
Behaviors can also add code to the generated query objects by implementing one of the following methods:
{{{
queryAttributes() // add attributes to the query class
queryMethods() // add methods to the query class
preSelectQuery() // add code to be executed before selection of a existing objects
preUpdateQuery() // add code to be executed before update of a existing objects
postUpdateQuery() // add code to be executed after update of a existing objects
preDeleteQuery() // add code to be executed before deletion of a existing objects
postDeleteQuery() // add code to be executed after deletion of a existing objects
queryFilter(&$script) // do whatever you want with the generated code, passed as reference
}}}
Behaviors can also add code to the generated peer objects by implementing one of the following methods:
{{{
staticAttributes() // add static attributes to the peer class
staticMethods() // add static methods to the peer class
preSelect() // adds code before every select query
peerFilter(&$script) // do whatever you want with the generated code, passed as reference
}}}
Check the behaviors bundled with Propel to see how to implement your own behavior.

View file

@ -0,0 +1,448 @@
= Logging And Debugging =
[[PageOutline]]
Propel provides tools to monitor and debug your model. Whether you need to check the SQL code of slow queries, or to look for error messages previously thrown, Propel is your best friend for finding and fixing problems.
== Propel Logs ==
Propel uses the logging facility configured in `runtime-conf.xml` to record errors, warnings, and debug information.
By default Propel will attempt to use the Log framework that is distributed with PEAR. If you are not familiar with it, check its [http://www.indelible.org/php/Log/guide.html online documentation]. It is also easy to configure Propel to use your own logging framework -- or none at all.
=== Logger Configuration ===
The Propel log handler is configured in the `<log>` section of your project's `runtime-conf.xml` file. Here is the accepted format for this section with the default values that Propel uses:
{{{
#!xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<config>
<log>
<type>file</type>
<name>./propel.log</name>
<ident>propel</ident>
<level>7</level> <!-- PEAR_LOG_DEBUG -->
<conf></conf>
</log>
<propel>
...
</propel>
</config>
}}}
Using these parameters, Propel creates a ''file'' Log handler in the background, and keeps it for later use:
{{{
#!php
<?php
Propel::$logger = Log::singleton($type = 'file', $name = './propel.log', $ident = 'propel', $conf = array(), $level = PEAR_LOG_DEBUG);
}}}
The meaning of each of the `<log>` nested elements may vary, depending on which log handler you are using. Refer to the [http://www.indelible.org/php/Log/guide.html#standard-log-handlers PEAR::Log] documentation for more details on log handlers configuration and options.
Note that the `<level>` tag needs to correspond to the integer represented by one of the `PEAR_LOG_*` constants:
||'''Constant'''||'''Value'''||'''Description'''
||PEAR_LOG_EMERG||0||System is unusable||
||PEAR_LOG_ALERT||1||Immediate action required||
||PEAR_LOG_CRIT||2||Critical conditions||
||PEAR_LOG_ERR||3||Error conditions||
||PEAR_LOG_WARNING||4||Warning conditions||
||PEAR_LOG_NOTICE||5||Normal but significant||
||PEAR_LOG_INFO||6||Informational||
||PEAR_LOG_DEBUG||7||Debug-level messages||
=== Logging Messages ===
Use the static `Propel::log()` method to log a message using the configured log handler:
{{{
#!php
<?php
$myObj = new MyObj();
$myObj->setName('foo');
Propel::log('uh-oh, something went wrong with ' . $myObj->getName(), Propel::LOG_ERROR);
}}}
You can log your own messages from the generated model objects by using their `log()` method, inherited from `BaseObject`:
{{{
#!php
<?php
$myObj = new MyObj();
$myObj->log('uh-oh, something went wrong', Propel::LOG_ERROR);
}}}
The log messages will show up in the log handler defined in `runtime-conf.xml` (`propel.log` file by default) as follows:
{{{
Oct 04 00:00:18 [error] uh-oh, something went wrong with foo
Oct 04 00:00:18 [error] MyObj: uh-oh, something went wrong
}}}
Tip: All serious errors coming from the Propel core do not only issue a log message, they are also thrown as `PropelException`.
=== Using An Alternative PEAR Log Handler ===
In many cases you may wish to integrate Propel's logging facility with the rest of your web application. In `runtime-conf.xml`, you can customize a different PEAR logger. Here are a few examples:
'''Example 1:''' Using 'display' container (for output to HTML)
{{{
#!xml
<log>
<type>display</type>
<level>6</level> <!-- PEAR_LOG_INFO -->
</log>
}}}
'''Example 2:''' Using 'syslog' container
{{{
#!xml
<log>
<type>syslog</type>
<name>8</name> <!-- LOG_USER -->
<ident>propel</ident>
<level>6</level>
</log>
}}}
=== Using A Custom Logger ===
If you omit the `<log>` section of your `runtime-conf.xml`, then Propel will not setup ''any'' logging for you. In this case, you can set a custom logging facility and pass it to Propel at runtime.
Here's an example of how you could configure your own logger and then set Propel to use it:
{{{
#!php
<?php
require_once 'MyLogger.php';
$logger = new MyLogger();
require_once 'propel/Propel.php';
Propel::setLogger($logger);
Propel::init('/path/to/runtime-conf.php');
}}}
Your custom logger could be any object that implements a basic logger interface. Check the `BasicLogger` interface provided with the Propel runtime to see the methods that a logger must implement in order to be compatible with Propel. You do not actually have to implement this interface, but all the specified methods must be present in your container.
Let's see an example of a simple log container suitable for use with Propel:
{{{
#!php
<?php
class MyLogger implements BasicLogger
{
public function emergency($m)
{
$this->log($m, Propel::LOG_EMERG);
}
public function alert($m)
{
$this->log($m, Propel::LOG_ALERT);
}
public function crit($m)
{
$this->log($m, Propel::LOG_CRIT);
}
public function err($m)
{
$this->log($m, Propel::LOG_ERR);
}
public function warning($m)
{
$this->log($m, Propel::LOG_WARNING);
}
public function notice($m)
{
$this->log($m, Propel::LOG_NOTICE);
}
public function info($m)
{
$this->log($m, Propel::LOG_INFO);
}
public function debug($m)
{
$this->log($m, Propel::LOG_DEBUG);
}
public function log($message, $priority)
{
$color = $this->priorityToColor($priority);
echo '<p style="color: ' . $color . '">$message</p>';
}
private function priorityToColor($priority)
{
switch($priority) {
case Propel::LOG_EMERG:
case Propel::LOG_ALERT:
case Propel::LOG_CRIT:
case Propel::LOG_ERR:
return 'red';
break;
case Propel::LOG_WARNING:
return 'orange';
break;
case Propel::LOG_NOTICE:
return 'green';
break;
case Propel::LOG_INFO:
return 'blue';
break;
case Propel::LOG_DEBUG:
return 'grey';
break;
}
}
}
}}}
Tip: There is also a bundled `MojaviLogAdapter` class which allows you to use a Mojavi logger with Propel.
== Debugging Database Activity ==
By default, Propel uses `PropelPDO` for database connections. This class, which extends PHP's `PDO`, offers a debug mode to keep track of all the database activity, including all the executed queries.
=== Enabling The Debug Mode ===
The debug mode is disabled by default, but you can enable it at runtime as follows:
{{{
#!php
<?php
$con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
$con->useDebug(true);
}}}
You can also disable the debug mode at runtime, by calling `PropelPDO::useDebug(false)`. Using this method, you can choose to enable the debug mode for only one particular query, or for all queries.
Alternatively, you can ask Propel to always enable the debug mode for a particular connection by using the `DebugPDO` class instead of the default `PropelPDO` class. This is accomplished in the `runtime-conf.xml` file, in the `<classname>` tag of a given datasource connection (see the [wiki:Documentation/1.5/RuntimeConfiguration runtime configuration reference] for more details).
{{{
#!xml
<?xml version="1.0"?>
<config>
<propel>
<datasources default="bookstore">
<datasource id="bookstore">
<adapter>sqlite</adapter>
<connection>
<!-- the classname that Propel should instantiate, must be PropelPDO subclass -->
<classname>DebugPDO</classname>
}}}
'''Tip''': You can use your own connection class there, but make sure that it extends `PropelPDO` and not only `PDO`. Propel requires certain fixes to PDO API that are provided by `PropelPDO`.
=== Counting Queries ===
In debug mode, `PropelPDO` keeps track of the number of queries that are executed. Use `PropelPDO::getQueryCount()` to retrieve this number:
{{{
#!php
<?php
$con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
$myObjs = MyObjPeer::doSelect(new Criteria(), $con);
echo $con->getQueryCount(); // 1
}}}
Tip: You cannot use persistent connections if you want the query count to work. Actually, the debug mode in general requires that you don't use persistent connections in order for it to correctly log bound values and count executed statements.
=== Retrieving The Latest Executed Query ===
For debugging purposes, you may need the SQL code of the latest executed query. It is available at runtime in debug mode using `PropelPDO::getLastExecutedQuery()`, as follows:
{{{
#!php
<?php
$con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
$myObjs = MyObjPeer::doSelect(new Criteria(), $con);
echo $con->getLastExecutedQuery(); // 'SELECT * FROM my_obj';
}}}
Tip: You can also get a decent SQL representation of the criteria being used in a SELECT query by using the `Criteria->toString()` method.
Propel also keeps track of the queries executed directly on the connection object, and displays the bound values correctly.
{{{
#!php
<?php
$con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
$stmt = $con->prepare('SELECT * FROM my_obj WHERE name = :p1');
$stmt->bindValue(':p1', 'foo');
$stmt->execute();
echo $con->getLastExecutedQuery(); // 'SELECT * FROM my_obj where name = "foo"';
}}}
'''Tip''': The debug mode is intended for development use only. Do not use it in production environment, it logs too much information for a production server, and adds a small overhead to the database queries.
== Full Query Logging ==
The combination of the debug mode and a logging facility provides a powerful debugging tool named ''full query logging''. If you have properly configured a log handler, enabling the debug mode (or using `DebugPDO`) automatically logs the executed queries into Propel's default log file:
{{{
Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO publisher (`ID`,`NAME`) VALUES (NULL,'William Morrow')
Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO author (`ID`,`FIRST_NAME`,`LAST_NAME`) VALUES (NULL,'J.K.','Rowling')
Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO book (`ID`,`TITLE`,`ISBN`,`PRICE`,`PUBLISHER_ID`,`AUTHOR_ID`) VALUES (NULL,'Harry Potter and the Order of the Phoenix','043935806X',10.99,53,58)
Oct 04 00:00:18 propel-bookstore [debug] INSERT INTO review (`ID`,`REVIEWED_BY`,`REVIEW_DATE`,`RECOMMENDED`,`BOOK_ID`) VALUES (NULL,'Washington Post','2009-10-04',1,52)
...
Oct 04 00:00:18 propel-bookstore [debug] SELECT bookstore_employee_account.EMPLOYEE_ID, bookstore_employee_account.LOGIN FROM `bookstore_employee_account` WHERE bookstore_employee_account.EMPLOYEE_ID=25
}}}
By default, Propel logs all SQL queries, together with the date of the query and the name of the connection.
=== Setting The Data To Log ===
The full query logging feature can be configured either in the `runtime-conf.xml` configuration file, or using the runtime configuration API.
In `runtime-conf.xml`, tweak the feature by adding a `<debugpdo>` tag under `<propel>`:
{{{
#!xml
<?xml version="1.0"?>
<config>
<log>
...
</log>
<propel>
<datasources default="bookstore">
...
</datasources>
<debugpdo>
<logging>
<details>
<method>
<enabled>true</enabled>
</method>
<time>
<enabled>true</enabled>
</time>
<mem>
<enabled>true</enabled>
</mem>
</details>
</logging>
</debugpdo>
</propel>
</config>
}}}
To accomplish the same configuration as above at runtime, change the settings in your main include file, after `Propel::init()`, as follows:
{{{
#!php
<?php
$config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
$config->setParameter('debugpdo.logging.details.method.enabled', true);
$config->setParameter('debugpdo.logging.details.time.enabled', true);
$config->setParameter('debugpdo.logging.details.mem.enabled', true);
}}}
Let's see a few of the provided parameters.
=== Logging More Connection Messages ===
`PropelPDO` can log queries, but also connection events (open and close), and transaction events (begin, commit and rollback). Since Propel can emulate nested transactions, you may need to know when an actual `COMMIT` or `ROLLBACK` is issued.
To extend which methods of `PropelPDO` do log messages in debug mode, customize the `'debugpdo.logging.methods'` parameter, as follows:
{{{
#!php
<?php
$allMethods = array(
'PropelPDO::__construct', // logs connection opening
'PropelPDO::__destruct', // logs connection close
'PropelPDO::exec', // logs a query
'PropelPDO::query', // logs a query
'PropelPDO::prepare', // logs the preparation of a statement
'PropelPDO::beginTransaction', // logs a transaction begin
'PropelPDO::commit', // logs a transaction commit
'PropelPDO::rollBack', // logs a transaction rollBack (watch out for the capital 'B')
'DebugPDOStatement::execute', // logs a query from a prepared statement
'DebugPDOStatement::bindValue' // logs the value and type for each bind
);
$config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
$config->setParameter('debugpdo.logging.methods', $allMethods);
}}}
By default, only the messages coming from `PropelPDO::exec`, `PropelPDO::query`, and `DebugPDOStatement::execute` are logged.
=== Logging Execution Time And Memory ===
In debug mode, Propel counts the time and memory necessary for each database query. This very valuable data can be added to the log messages on demand, by adding the following configuration:
{{{
#!php
<?php
$config = Propel::getConfiguration(PropelConfiguration::TYPE_OBJECT);
$config->setParameter('debugpdo.logging.details.time.enabled', true);
$config->setParameter('debugpdo.logging.details.mem.enabled', true);
}}}
Enabling the options shown above, you get log output along the lines of:
{{{
Feb 23 16:41:04 Propel [debug] time: 0.000 sec | mem: 1.4 MB | SET NAMES 'utf8'
Feb 23 16:41:04 Propel [debug] time: 0.002 sec | mem: 1.6 MB | SELECT COUNT(tags.NAME) FROM tags WHERE tags.IMAGEID = 12
Feb 23 16:41:04 Propel [debug] time: 0.012 sec | mem: 2.4 MB | SELECT tags.NAME, image.FILENAME FROM tags LEFT JOIN image ON tags.IMAGEID = image.ID WHERE image.ID = 12
}}}
The order in which the logging details are enabled is significant, since it determines the order in which they will appear in the log file.
=== Complete List Of Logging Options ===
The following settings can be customized at runtime or in the configuration file:
||'''Parameter'''||'''Default'''||'''Meaning'''||
||`debugpdo.logging.enabled`||`true`||Should any logging take place||
||`debugpdo.logging.innerglue`||`": "`||String to use for combining the title of a detail and its value||
||`debugpdo.logging.outerglue`||`" | "`||String to use for combining details together on a log line||
||`debugpdo.logging.realmemoryusage`||`false`||Parameter to [http://www.php.net/manual/en/function.memory-get-usage.php memory_get_usage()] and [http://www.php.net/manual/en/function.memory-get-peak-usage.php memory_get_peak_usage()] calls||
||`debugpdo.logging.methods`||[http://propel.propelorm.org/browser/branches/1.5/runtime/classes/propel/util/DebugPDO.php#L151 array(...)]||An array of method names `Class::method`) to be included in method call logging||
||`debugpdo.logging.details.slow.enabled`||`false`||Enables flagging of slow method calls||
||`debugpdo.logging.details.slow.threshold`||`0.1`||Method calls taking more seconds than this threshold are considered slow||
||`debugpdo.logging.details.time.enabled`||`false`||Enables logging of method execution times||
||`debugpdo.logging.details.time.precision`||`3`||Determines the precision of the execution time logging||
||`debugpdo.logging.details.time.pad`||`10`||How much horizontal space to reserve for the execution time on a log line||
||`debugpdo.logging.details.mem.enabled`||`false`||Enables logging of the instantaneous PHP memory consumption||
||`debugpdo.logging.details.mem.precision`||`1`||Determines the precision of the memory consumption logging||
||`debugpdo.logging.details.mem.pad`||`9`||How much horizontal space to reserve for the memory consumption on a log line||
||`debugpdo.logging.details.memdelta.enabled`||`false`||Enables logging differences in memory consumption before and after the method call||
||`debugpdo.logging.details.memdelta.precision`||`1`||Determines the precision of the memory difference logging||
||`debugpdo.logging.details.memdelta.pad`||`10`||How much horizontal space to reserve for the memory difference on a log line||
||`debugpdo.logging.details.mempeak.enabled`||`false`||Enables logging the peak memory consumption thus far by the currently executing PHP script||
||`debugpdo.logging.details.mempeak.precision`||`1`||Determines the precision of the memory peak logging||
||`debugpdo.logging.details.mempeak.pad`||`9`||How much horizontal space to reserve for the memory peak on a log line||
||`debugpdo.logging.details.querycount.enabled`||`false`||Enables logging of the number of queries performed by the DebugPDO instance thus far||
||`debugpdo.logging.details.querycount.pad`||`2`||How much horizontal space to reserve for the query count on a log line||
||`debugpdo.logging.details.method.enabled`||`false`||Enables logging of the name of the method call||
||`debugpdo.logging.details.method.pad`||`28`||How much horizontal space to reserve for the method name on a log line||
=== Changing the Log Level ===
By default the connection log messages are logged at the `Propel::LOG_DEBUG` level. This can be changed by calling the `setLogLevel()` method on the connection object:
{{{
#!php
<?php
$con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
$con->setLogLevel(Propel::LOG_INFO);
}}}
Now all queries and bind param values will be logged at the INFO level.
=== Configuring a Different Full Query Logger ===
By default the `PropelPDO` connection logs queries and binds param values using the `Propel::log()` static method. As explained above, this method uses the log storage configured by the `<log>` tag in the `runtime-conf.xml` file.
If you would like the queries to be logged using a different logger (e.g. to a different file, or with different ident, etc.), you can set a logger explicitly on the connection at runtime, using `Propel::setLogger()`:
{{{
#!php
<?php
$con = Propel::getConnection(MyObjPeer::DATABASE_NAME);
$logger = Log::factory('syslog', LOG_LOCAL0, 'propel', array(), PEAR_LOG_INFO);
$con->setLogger($logger);
}
}}}
This will not affect the general Propel logging, but only the full query logging. That way you can log the Propel error and warnings in one file, and the SQL queries in another file.

View file

@ -0,0 +1,329 @@
= Inheritance =
[[PageOutline]]
Developers often need one model table to extend another model table. Inheritance being an object-oriented notion, it doesn't have a true equivalent in the database world, so this is something an ORM must emulate. Propel offers two types of table inheritance: [http://www.martinfowler.com/eaaCatalog/singleTableInheritance.html Single Table Inheritance], which is the most efficient implementations from a SQL and query performance perspective, but is limited to a small number of inherited fields ; and [http://www.martinfowler.com/eaaCatalog/concreteTableInheritance.html Concrete Table Inheritance], which provides the most features but adds a small overhead on write queries.
== Single Table Inheritance ==
In this implementation, one table is used for all subclasses. This has the implication that your table must have all columns needed by the main class and subclasses. Propel will create stub subclasses.
Let's illustrate this idea with an example. Consider an object model with three classes, `Book`, `Essay`, and `Comic` - the first class being parent of the other two. With single table inheritance, the data of all three classes is stored in one table, named `book`.
=== Schema Definition ===
A table using Single Table Inheritance requires a column to identify which class should be used to represent the ''table'' row. Classically, this column is named `class_key` - but you can choose whatever name fits your taste. The column needs the `inheritance="single"` attribute to make Propel understand that it's the class key column. Note that this 'key' column must be a real column in the table.
{{{
#!xml
<table name="book">
<column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
<column name="title" type="VARCHAR" size="100"/>
<column name="class_key" type="INTEGER" inheritance="single">
<inheritance key="1" class="Book"/>
<inheritance key="1" class="Essay" extends="Book"/>
<inheritance key="2" class="Comic" extends="Book"/>
</column>
</table>
}}}
Once you rebuild your model, Propel generated all three model classes (`Book`, `Essay`, and `Comic`) and three query classes (`BookQuery`, `EssayQuery`, and `ComicQuery`). The `Essay` and `Comic` classes extend the `Book` class, the `EssayQuery` and `ComicQuery` classes extend `BookQuery`.
'''Tip''': An inherited class can extend another inherited class. That mean that you can add a `Manga` kind of book that extends `Comic` instead of `Book`.
=== Using Inherited Objects ===
Use inherited objects just like you use regular Propel model objects:
{{{
#!php
<?php
$book = new Book();
$book->setTitle('War And Peace');
$book->save();
$essay = new Essay();
$essay->setTitle('On the Duty of Civil Disobedience');
$essay->save();
$comic = new Comic();
$comic->setTitle('Little Nemo In Slumberland');
$comic->save();
}}}
Inherited objects share the same properties and methods by default, but you can add your own logic to each of the generated classes.
Behind the curtain, Propel sets the `class_key` column based on the model class. So the previous code stores the following rows in the database:
{{{
id | title | class_key
---|-----------------------------------|----------
1 | War And Peace | Book
2 | On the Duty of Civil Disobedience | Essay
3 | Little Nemo In Slumberland | Comic
}}}
Incidentally, that means that you can add new classes manually, even if they are not defined as `<inheritance>` tags in the `schema.xml`:
{{{
#!php
<?php
class Novel extends Book
{
public function __construct()
{
parent::__construct();
$this->setClassKey('Novel');
}
}
$novel = new Novel();
$novel->setTitle('Harry Potter');
$novel->save();
}}}
=== Retrieving Inherited objects ===
In order to retrieve books, use the Query object of the main class, as you would usually do. Propel will hydrate children objects instead of the parent object when necessary:
{{{
#!php
<?php
$books = BookQuery::create()->find();
foreach ($books as $book) {
echo get_class($book) . ': ' . $book->getTitle() . "\n";
}
// Book: War And Peace
// Essay: On the Duty of Civil Disobedience
// Comic: Little Nemo In Slumberland
// Novel: Harry Potter
}}}
If you want to retrieve only objects of a certain class, use the inherited query classes:
{{{
#!php
<?php
$comic = ComicQuery::create()
->findOne();
echo get_class($comic) . ': ' . $comic->getTitle() . "\n";
// Comic: Little Nemo In Slumberland
}}}
'''Tip''': You can override the base peer's `getOMClass()` to return the classname to use based on more complex logic (or query).
=== Abstract Entities ===
If you wish to enforce using subclasses of an entity, you may declare a table "abstract" in your XML data model:
{{{
#!xml
<table name="book" abstract="true">
...
}}}
That way users will only be able to instanciate `Essay` or `Comic` books, but not `Book`.
== Concrete Table Inheritance ==
Concrete Table Inheritance uses one table for each class in the hierarchy. Each table contains columns for the class and all its ancestors, so any fields in a superclass are duplicated across the tables of the subclasses.
Propel implements Concrete Table Inheritance through a behavior.
=== Schema Definition ===
Once again, this is easier to understand through an example. In a Content Management System, content types are often organized in a hierarchy, each subclass adding more fields to the superclass. So let's consider the following schema, where the `article` and `video` tables use the same fields as the main `content` tables, plus additional fields:
{{{
#!xml
<table name="content">
<column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
<column name="title" type="VARCHAR" size="100"/>
<column name="category_id" required="false" type="INTEGER" />
<foreign-key foreignTable="category" onDelete="cascade">
<reference local="category_id" foreign="id" />
</foreign-key>
</table>
<table name="category">
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
<column name="name" type="VARCHAR" size="100" primaryString="true" />
</table>
<table name="article">
<column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
<column name="title" type="VARCHAR" size="100"/>
<column name="body" type="VARCHAR" size="100"/>
<column name="category_id" required="false" type="INTEGER" />
<foreign-key foreignTable="category" onDelete="cascade">
<reference local="category_id" foreign="id" />
</foreign-key>
</table>
<table name="video">
<column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
<column name="title" type="VARCHAR" size="100"/>
<column name="resource_link" type="VARCHAR" size="100"/>
<column name="category_id" required="false" type="INTEGER" />
<foreign-key foreignTable="category" onDelete="cascade">
<reference local="category_id" foreign="id" />
</foreign-key>
</table>
}}}
Since the columns of the main table are copied to the child tables, this schema is a simple implementation of Concrete Table Inheritance. This is something that you can write by hand, but the repetition makes it tedious. Instead, you should let the `concrete_inheritance` behavior do it for you:
{{{
#!xml
<table name="content">
<column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
<column name="title" type="VARCHAR" size="100"/>
<column name="category_id" required="false" type="INTEGER" />
<foreign-key foreignTable="category" onDelete="cascade">
<reference local="category_id" foreign="id" />
</foreign-key>
</table>
<table name="category">
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
<column name="name" type="VARCHAR" size="100" primaryString="true" />
</table>
<table name="article">
<behavior name="concrete_inheritance">
<parameter name="extends" value="content" />
</behavior>
<column name="body" type="VARCHAR" size="100"/>
</table>
<table name="video">
<behavior name="concrete_inheritance">
<parameter name="extends" value="content" />
</behavior>
<column name="resource_link" type="VARCHAR" size="100"/>
</table>
}}}
'''Tip''': The `concrete_inheritance` behavior copies columns, foreign keys, indices and validators.
=== Using Inherited Model Classes ===
For each of the tables in the schema above, Propel generates a Model class:
{{{
#!php
<?php
// create a new Category
$cat = new Category();
$cat->setName('Movie');
$cat->save();
// create a new Article
$art = new Article();
$art->setTitle('Avatar Makes Best Opening Weekend in the History');
$art->setCategory($cat);
$art->setContent('With $232.2 million worldwide total, Avatar had one of the best-opening weekends in the history of cinema.');
$art->save();
// create a new Video
$vid = new Video();
$vid->setTitle('Avatar Trailer');
$vid->setCategory($cat);
$vid->setResourceLink('http://www.avatarmovie.com/index.html')
$vid->save();
}}}
And since the `concrete_inheritance` behavior tag defines a parent table, the `Article` and `Video` classes extend the `Content` class (same for the generated Query classes):
{{{
#!php
<?php
// methods of the parent model are accessible to the child models
class Content extends BaseContent
{
public function getCategoryName()
{
return $this->getCategory()->getName();
}
}
echo $art->getCategoryName(); // 'Movie'
echo $vid->getCategoryName(); // 'Movie'
// methods of the parent query are accessible to the child query
class ContentQuery extends BaseContentQuery
{
public function filterByCategoryName($name)
{
return $this
->useCategoryQuery()
->filterByName($name)
->endUse();
}
}
$articles = ArticleQuery::create()
->filterByCategoryName('Movie')
->find();
}}}
That makes of Concrete Table Inheritance a powerful way to organize your model logic and to avoid repetition, both in the schema and in the model code.
=== Data Replication ===
By default, every time you save an `Article` or a `Video` object, Propel saves a copy of the `title` and `category_id` columns in a `Content` object. Consequently, retrieving objects regardless of their child type becomes very easy:
{{{
#!php
<?php
$conts = ContentQuery::create()->find();
foreach ($conts as $content) {
echo $content->getTitle() . "(". $content->getCategoryName() ")/n";
}
// Avatar Makes Best Opening Weekend in the History (Movie)
// Avatar Trailer (Movie)
}}}
Propel also creates a one-to-one relationship between a object and its parent copy. That's why the schema definition above doesn't define any primary key for the `article` and `video` tables: the `concrete_inheritance` behavior creates the `id` primary key which is also a foreign key to the parent `id` column. So once you have a parent object, getting the child object is just one method call away:
{{{
#!php
<?php
class Article extends BaseArticle
{
public function getPreview()
{
return $this->getContent();
}
}
class Movie extends BaseMovie
{
public function getPreview()
{
return $this->getResourceLink();
}
}
$conts = ContentQuery::create()->find();
foreach ($conts as $content) {
echo $content->getTitle() . "(". $content->getCategoryName() ")/n"
if ($content->hasChildObject()) {
echo ' ' . $content->getChildObject()->getPreview(), "\n";
}
// Avatar Makes Best Opening Weekend in the History (Movie)
// With $232.2 million worldwide total, Avatar had one of the best-opening
// weekends in the history of cinema.
// Avatar Trailer (Movie)
// http://www.avatarmovie.com/index.html
}}}
The `hasChildObject()` and `getChildObject()` methods are automatically added by the behavior to the parent class. Behind the curtain, the saved `content` row has an additional `descendant_column` field allowing it to use the right model for the job.
'''Tip''' You can disable the data replication by setting the `copy_data_to_parent` parameter to "false". In that case, the `concrete_inheritance` behavior simply modifies the table at buildtime and does nothing at runtime. Also, with `copy_data_to_parent` disabled, any primary key copied from the parent table is not turned into a foreign key:
{{{
#!xml
<table name="article">
<behavior name="concrete_inheritance">
<parameter name="extends" value="content" />
<parameter name="copy_data_to_parent" value="false" />
</behavior>
<column name="body" type="VARCHAR" size="100"/>
</table>
// results in
<table name="article">
<column name="body" type="VARCHAR" size="100"/>
<column name="id" type="INTEGER" primaryKey="true" autoIncrement="true"/>
<column name="title" type="VARCHAR" size="100"/>
<column name="category_id" required="false" type="INTEGER" />
<foreign-key foreignTable="category" onDelete="cascade">
<reference local="category_id" foreign="id" />
</foreign-key>
</table>
}}}