CC-5895: Upgrade Propel to 1.7
Remove propel library from repo
This commit is contained in:
parent
41ff0cce67
commit
efb2a5ea7d
|
@ -1,107 +0,0 @@
|
|||
= Changelog Of The Propel 1.5 Branch =
|
||||
|
||||
== 2010-06-17: Version 1.5.2 ==
|
||||
|
||||
* [1810] Changed default table type keyword to ENGINE for MySQL (closes #969)
|
||||
* [1809] Added a way to read virtual columns starting with a lowercase character (closes #993)
|
||||
* [1808] Added connection object to the FK getter (closes #1018)
|
||||
* [1807] Fixed namespace issue with `soft_delete` behavior (closes #1015)
|
||||
* [1806] Fixed issue with instance pooling and soft_delete behavior (closes #1016)
|
||||
* [1805] Added namespace declaration to model class interface (closes #1014)
|
||||
* [1804] Improved generated class code when using namespaces (refs #683)
|
||||
* [1803] Documented namespace.autoPackage build property (refs #1005)
|
||||
* [1802] Added support for package autosetting based on namespace attribute (refs #1005)
|
||||
* [1801] Fixed related instance pooling clear in case of an emulated on delete cascade / set null (refs #1012)
|
||||
* [1800] Fixed onDelete cascade and setnull for self-referencing foreign keys (closes #1012)
|
||||
* [1799] Fixed `ModelCriteria::find()` throws `Exception` instead of `PropelException`
|
||||
* [1798] Fixed hard-to-debug unit test exception message
|
||||
* [1797] Fixed cascade deletion emulation when `Criteria` is modified by `doSelect()` (closes #1008)
|
||||
* [1796] Added `ModelCriteria::findOneOrCreate()` (closes #1009)
|
||||
* [1795] Fixed `delete()` called in iterator breaks on demand formatter (closes #1006)
|
||||
* [1794] Fixed double iteration on Propel collection (closes #1004) (patch from jeremyp)
|
||||
* [1793] Documented namespaces (refs #683)
|
||||
* [1792] Added support for namespaces in many-to-many relationships (refs #683)
|
||||
* [1791] Added support for namespaces in single table inheritance (refs #683)
|
||||
* [1790] Added mention of a common error code in runtime settings documentation
|
||||
* [1789] Documented the simple templating system (refs #1002)
|
||||
* [1788] Allowed namespace tests to run alongside normal tests (refs #683)
|
||||
* [1787] Fixed `PropelObjectCollection::toArray()` when the collection is empty (closes #1001)
|
||||
* [1786] Fixed runtime doc typo
|
||||
* [1785] Refactored the `aggregate_column` behavior to take advantage of the buildtime simple templating engine (refs #1002, #995)
|
||||
* [1784] Added simple templating engine for behaviors (refs #1002)
|
||||
* [1783] Added a !HowTo on writing behaviors (should have been published in the blog, but Posterous is having troubles with code samples)
|
||||
* [1782] Improved namespace support in generated `TableMap` classes (refs #683)
|
||||
* [1781] Introducing Model Namespaces (PHP 5.3 only) (WIP) (refs #683)
|
||||
* [1780] Fixed generated `filterByXXX()` for string columns when using custom comparison
|
||||
* [1779] Added `aggregate_column` behavior (refs #995)
|
||||
* [1778] Refactored `ForeignKey` class in generator
|
||||
* [1777] [doc] Fixed typo in CRUD chapter
|
||||
* [1776] Fixed generated relation names for tables with symmetrical foreign keys (closes #968)
|
||||
* [1775] Fixed generated relation names for tables with more than one self-referencing foreign key (closes #972)
|
||||
* [1774] Fixed copy of foreign keys with hardcoded refPhpName in concrete inheritance behavior (closes #988)
|
||||
* [1773] Changing runtime autoload strategy (closes #974):
|
||||
* Using absolute path in core autoloading
|
||||
* introducing `PropelAutoloader` for models
|
||||
* removing the need for include path change in installation docs
|
||||
* [1772] Added failed SQL query to `BasePeer` exception messages (closes #979)
|
||||
* [1771] Documented the schema autosuggest feature in supported IDEs
|
||||
* [1770] Expanded the schema XSD annotations for easier schema autocompletion
|
||||
* [1769] showcasing link to XSD file in schema to allow autocompletion on NetBeans
|
||||
* [1768] Fixed typos in `ModelCriteria` doc (closes #978) (patch from Frosty)
|
||||
* [1767] Fixed typo in install doc (closes #576)
|
||||
* [1766] Fixed schema DTD does not validate schemas without behaviors (closes #973)
|
||||
* [1765] Added the ability to comment the generated SQL query from a Criteria (closes #970)
|
||||
* [1764] Fixed limitation in schema size when transformation or external schema is included (closes #971)
|
||||
* [1763] Fixed limitation in schema size when no transformation nor external schema is included (closes #971)
|
||||
|
||||
== 2010-05-10: Version 1.5.1 ==
|
||||
|
||||
* [1759] Moved ModelWith runtime class to formatter directory
|
||||
* [1758] Fixed warning with new StringReader
|
||||
* [1757] Reduced console logging when building an up-to-date schema
|
||||
* [1756] Parsing schemas as strings instead of files (closes #967)
|
||||
* [1755] Reverting r1548 to allow inclusion of external schemas (refs #967)
|
||||
* [1754] Documented custom defaultJoin type (refs #870) (closes #936)
|
||||
* [1749] fix Criteria::addCond() example and php-doc (closes #964)
|
||||
* [1748] fix Join::addCondition() php-doc (closes #963)
|
||||
* [1747] Add getJoin() method to ModelCriteria (closes #961)
|
||||
* [1745] Fixed auto_add_pk behavior when using separate schemas (closes #956)
|
||||
* [1743] Refactored ModelCriteria::count() to allow query cache on counts
|
||||
* [1742] Fixed propel-gen executable on windows (closes #942)
|
||||
* [1741] disabled query cloning by default, you can enable it on a per query basis using keepQuery() (refs #953)
|
||||
* [1740] Fixed shallow Criteria cloning (refs #953)
|
||||
* [1739] Fixed overriding primary key in a new object (closes #960)
|
||||
* [1738] Fixed generated joinXXX() methods used in secondary Criteria (closes #958)
|
||||
* [1737] Fixed array hydration (refs #954, #959)
|
||||
* [1736] Added unit test to demonstrate Array Hydration regression (refs #959)
|
||||
* [1735] Fixed typo in MySQL DDL builder (closes #957)
|
||||
* [1734] fixed doc typos (patch from Frosty) (closes #955)
|
||||
* [1733] Refactored hydration schema
|
||||
* removed circular dependency between Criteria and Formatter (refs #891)
|
||||
* formatters now copy the necessary hydration data from the ModelCriteria
|
||||
* Should improve memory handling in large resultsets
|
||||
* removed PropelFormatter::setCriteria() and checkCriteria (refs #892)
|
||||
* [1732] refactored on demand hydration (refs #954), removed ModelJoin storage in ModelWith
|
||||
* [1731] Refactored Joined Array hydration (refs #954)
|
||||
* [1730] Changed Propel::enableInstancePooling() return value
|
||||
* [1729] Added a exception to explicit the limits of one-to-many joined hydration
|
||||
* [1728] Refactored joined object hydration
|
||||
* Now deals correctly with any join chain (refs #954)
|
||||
* Faster for large resultsets and long join chains
|
||||
* [1727] refactored BasePeer::doDelete() to handle table aliases and perform better (closes #949)
|
||||
* [1726] Small Criteria optimization
|
||||
* [1725] Fixed ModelCriteria::delete() fails when using true table alias (closes #949)
|
||||
* [1724] Allowed Merging of Criteria objects to combien conditions with an OR (closes #951)
|
||||
* [1723] Added the ability to reindex a collection (closes #851)
|
||||
* [1722] Gave a public way to remove an alias (useful when merging Criterias)
|
||||
* [1721] Added ModelCriteria::postUpdate() and ModelCriteria::postDelete() hooks (closes #945)
|
||||
* [1720] Fixed issue with instance pooling and composite fkeys in peer classes (closes #924)
|
||||
* [1719] Fixed E_STRICT warning in concrete table inheritance (closes #910)
|
||||
* [1718] Added unit tests for PropelObjectCollection::toKeyValue(), and made it just a little smarter (closes #943)
|
||||
* [1717] Fixed typo in Relationships doc closes #941)
|
||||
* [1716] Fixed reverse task and validators (closes #928)
|
||||
* [1715] Fixed phpDoc for Criteria::getCriterion() (closes #929)
|
||||
* [1714] Fixed regression in orderBy() used in conjunction with ignoreCase (closes #946)
|
||||
* [1712] Fixed concrete table inheritance with more than one level (closes #922)
|
||||
* [1711] Fixed filterByXXX() when passed an explicit Criteria::EQUAL (closes #944)
|
||||
* [1710] Fixed references to 1.4 pages in documentaton (closes #937)
|
|
@ -1,4 +0,0 @@
|
|||
I N S T A L L I N G P R O P E L
|
||||
==================================
|
||||
|
||||
See docs/guide/01-Installation.txt for detailed installation instructions.
|
|
@ -1,19 +0,0 @@
|
|||
Copyright (c) 2005-2010 Hans Lellelid, David Zuelke, Francois Zaninotto
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
|
@ -1,807 +0,0 @@
|
|||
= What's new in Propel 1.5? =
|
||||
|
||||
[[PageOutline]]
|
||||
|
||||
First and foremost, don't be frightened by the long list of new features that follows. Propel 1.5 is completely backwards compatible with Propel 1.4 and 1.3, so there is no hidden cost to benefit from these features. If you didn't do it already, upgrade the propel libraries, rebuild your model, and you're done - your application can now use the Propel 1.5 features.
|
||||
|
||||
== New Query API ==
|
||||
|
||||
This is the killer feature of Propel 1.5. It will transform the painful task of writing Criteria queries into a fun moment.
|
||||
|
||||
=== Model Queries ===
|
||||
|
||||
Along Model and Peer classes, Propel 1.5 now generates one Query class for each table. These Query classes inherit from Criteria, but have additional abilities since the Propel generator has a deep knowledge of your schema. That means that Propel 1.5 advises that you use ModelQueries instead of raw Criteria.
|
||||
|
||||
Model queries have smart filter methods for each column, and termination methods on their own. That means that instead of writing:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$c = new Criteria();
|
||||
$c->add(BookPeer::TITLE, 'War And Peace');
|
||||
$book = BookPeer::doSelectOne($c);
|
||||
}}}
|
||||
|
||||
You can write:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$q = new BookQuery();
|
||||
$q->filterByTitle('War And Peace');
|
||||
$book = $q->findOne();
|
||||
}}}
|
||||
|
||||
In addition, each Model Query class benefits from a factory method called `create()`, which returns a new instance of the query class. And the filter methods return the current query object. So it's even easier to write the previous query as follows:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$book = BookQuery::create()
|
||||
->filterByTitle('War And Peace');
|
||||
->findOne();
|
||||
}}}
|
||||
|
||||
The termination methods are `find()`, `findOne()`, `count()`, `paginate()`, `update()`, and `delete()`. They all accept a connection object as last parameter.
|
||||
|
||||
Remember that a Model Query IS a Criteria. So your Propel 1.4 code snippets still work:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$book = BookQuery::create()
|
||||
->addJoin(BookPeer::AUTHOR_ID, AuthorPeer::ID);
|
||||
->add(AuthorPeer::LAST_NAME, 'Tolstoi')
|
||||
->addAscendingOrderByColumn(BookPeer::TITLE)
|
||||
->findOne();
|
||||
}}}
|
||||
|
||||
But you will soon see that it's faster to use the generated methods of the Model Query classes:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$book = BookQuery::create()
|
||||
->useAuthorQuery();
|
||||
->filterByLastName('Tolstoi')
|
||||
->endUse()
|
||||
->orderByTitle()
|
||||
->findOne();
|
||||
}}}
|
||||
|
||||
That's right, you can embed a query into another; Propel guesses the join to apply from the foreign key declared in your schema.
|
||||
|
||||
That makes it very easy to package your own custom model logic into reusable query methods. After a while, your code can easily look like the following:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$books = BookQuery::create()
|
||||
->filterByPublisher($publisher)
|
||||
->cheap()
|
||||
->recent()
|
||||
->useAuthorQuery();
|
||||
->stillAlive()
|
||||
->famous()
|
||||
->endUse()
|
||||
->orderByTitle()
|
||||
->find();
|
||||
}}}
|
||||
|
||||
The Model Queries can understand `findByXXX()` method calls, where `'XXX'` is the phpName of a column of the model. That answers one of the most common customization need:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$book = BookQuery::create()->findOneByTitle('War And Peace');
|
||||
}}}
|
||||
|
||||
Eventually, these Query classes will replace the Peer classes; you should place all the code necessary to request or alter Model object in these classes. The Criteria/Peer way of doing queries still work exactly the same as in previous Propel versions, so your existing applications won't suffer from this update.
|
||||
|
||||
'''Tip''': Incidentally, if you use an IDE with code completion, you will see that writing a query has never been so easy.
|
||||
|
||||
=== 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
|
||||
$books = BookQuery::create()
|
||||
->limit(5)
|
||||
->find(); // $books is a PropelCollection object
|
||||
foreach ($books as $book) {
|
||||
echo $book->getTitle();
|
||||
}
|
||||
}}}
|
||||
|
||||
Propel also returns a `PropelCollection` object instead of an array when you use a getter for a one-to-many relationship:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$books = $author->getBooks(); // $books is a PropelCollection object
|
||||
}}}
|
||||
|
||||
If your code relies on list of objects being arrays, you will need to update it a little. The `PropelCollection` object provides a method for most common array operations:
|
||||
|
||||
{{{
|
||||
Array | Collection object
|
||||
------------------------ | -----------------------------------------
|
||||
foreach($books as $book) | foreach($books as $book)
|
||||
count($books) | count($books) or $books->count()
|
||||
$books[]= $book | $books[]= $book or $books->append($book)
|
||||
$books[0] | $books[0] or $books->getFirst()
|
||||
$books[123] | $books[123] or $books->offsetGet(123)
|
||||
unset($books[1]) | unset($books[1]) or $books->remove(1)
|
||||
empty($books) | $books->isEmpty()
|
||||
in_array($book, $books) | $books->contains($book)
|
||||
array_pop($books) | $books->pop()
|
||||
etc.
|
||||
}}}
|
||||
|
||||
'''Warning''': `empty($books)` always returns false when using a collection, even on a non-empty one. This is a PHP limitation. Prefer `$books->isEmpty()`, or `count($books)>0`.
|
||||
|
||||
'''Tip''': If you can't afford updating your code to support collections instead of arrays, you can still ask Propel to generate 1.4-compatible model objects by overriding the `propel.builder.object.class` setting in your `build.properties`, as follows:
|
||||
|
||||
{{{
|
||||
#!ini
|
||||
propel.builder.object.class = builder.om.PHP5ObjectNoCollectionBuilder
|
||||
}}}
|
||||
|
||||
The `PropelCollection` class offers even more methods that you will soon use a lot:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$books->getArrayCopy() // get the array inside the collection
|
||||
$books->toArray() // turn all objects to associative arrays
|
||||
$books->getPrimaryKeys() // get an array of the primary keys of all the objects in the collection
|
||||
$books->getModel() // return the model of the collection, e.g. 'Book'
|
||||
}}}
|
||||
|
||||
Another 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 again. Available through the `setFormatter()` method of Model Queries, on-demand hydration is very easy to trigger:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$books = BookQuery::create()
|
||||
->limit(50000)
|
||||
->setFormatter(ModelCriteria::FORMAT_ON_DEMAND) // just add this line
|
||||
->find();
|
||||
foreach ($books as $book) {
|
||||
echo $book->getTitle();
|
||||
}
|
||||
}}}
|
||||
|
||||
In this example, Propel will hydrate the `Book` 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 new 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:Users/Documentation/1.5/ModelCriteria documentation] describes each formatter, and how to use it.
|
||||
|
||||
=== Model Criteria ===
|
||||
|
||||
Generated Model Queries inherit from `ModelCriteria`, which extends your good old `Criteria`, and adds a few useful features. Basically, a `ModelCriteria` is a `Criteria` linked to a Model; by using the information stored in the generated TableMaps at runtime, `ModelCriteria` offers powerful methods to simplify the process of writing a query.
|
||||
|
||||
For instance, `ModelCriteria::where()` provides similar functionality to `Criteria::add()`, except that its [http://www.php.net/manual/en/pdostatement.bindparam.php PDO-like syntax] removes the burden of Criteria constants for comparators.
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$book = BookQuery::create()
|
||||
->where('Book.Title LIKE ?', 'War And P%')
|
||||
->findOne();
|
||||
}}}
|
||||
|
||||
Propel analyzes the clause passed as first argument of `where()` to determine which escaping to use for the value passed as second argument. In the above example, the `Book::TITLE` column is declared as `VARCHAR` in the schema, so Propel will bind the title as a string.
|
||||
|
||||
The `where()` method can also accept more complex clauses. You just need to explicit every column name as `'ModelClassName.ColumnPhpName'`, as follows:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$book = BookQuery::create()
|
||||
->where('UPPER(Book.Title) LIKE ?', 'WAR AND P%')
|
||||
->where('(Book.Price * 100) <= ?', 1500)
|
||||
->findOne();
|
||||
}}}
|
||||
|
||||
Another great addition of `ModelCriteria` is the `join()` method, which just needs the name of a related model to build a JOIN clause:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$books = BookQuery::create()
|
||||
->join('Book.Author')
|
||||
->where('CONCAT(Author.FirstName, " ", Author.LastName) = ?', 'Leo Tolstoi')
|
||||
->find();
|
||||
}}}
|
||||
|
||||
`ModelCriteria` has a built-in support for table aliases, which allows to setup a query using two joins on the same table, which was not possible with the `Criteria` object:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$books = BookQuery::create('b') // use 'b' as an alias for 'Book' in the query
|
||||
->join('b.Author a') // use 'a' as an alias for 'Author' in the query
|
||||
->where('CONCAT(a.FirstName, " ", a.LastName) = ?', 'Leo Tolstoi')
|
||||
->find();
|
||||
}}}
|
||||
|
||||
This syntax probably looks familiar, because it is very close to SQL. So you probably won't need long to figure out how to write a complex query with it. The documentation offers [wiki:Users/Documentation/1.5/ModelCriteria an entire chapter] dedicated to the new `ModelCriteria` class. Make sure you read it to see the power of this new query API.
|
||||
|
||||
=== Criteria Enhancements ===
|
||||
|
||||
Generated queries and ModelQueries are not the only ones to have received a lot of attention in Propel 1.5. The Criteria object itself sees a few improvements, that will ease the writing of queries with complex logic.
|
||||
|
||||
`Criteria::addOr()` operates the way you always expected it to. For instance, in Propel 1.4, `addOr()` resulted in a SQL `AND` if called on a column with no other condition:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// addOr() used to work on a column with an existing condition
|
||||
$c = new Criteria();
|
||||
$c->add(BookPeer::TITLE, '%Leo%', Criteria::LIKE);
|
||||
$c->addOr(BookPeer::TITLE, '%Tolstoi%', Criteria::LIKE);
|
||||
// translates in SQL as
|
||||
// WHERE (book.TITLE LIKE '%Leo%' OR book.TITLE LIKE '%Tolstoi%')
|
||||
|
||||
// addOr() used to fail on a column with no existing condition
|
||||
$c = new Criteria();
|
||||
$c->add(BookPeer::TITLE, '%Leo%', Criteria::LIKE);
|
||||
$c->addOr(BookPeer::ISBN, '1234', Criteria::EQUAL);
|
||||
// translates in SQL as
|
||||
// WHERE book.TITLE LIKE '%Leo%' AND book.ISBN = '1234'
|
||||
}}}
|
||||
|
||||
This is fixed in Propel 1.5. This means that you don't need to call upon the `Criterion` object for a simple OR clause:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// addOr() now works on a column with no existing condition
|
||||
$c = new Criteria();
|
||||
$c->add(BookPeer::TITLE, '%Leo%', Criteria::LIKE);
|
||||
$c->addOr(BookPeer::ISBN, '1234', Criteria::EQUAL);
|
||||
// translates in SQL as
|
||||
// WHERE (book.TITLE LIKE '%Leo%' OR book.ISBN = '1234')
|
||||
|
||||
// and it's much faster to write than
|
||||
$c = new Criteria();
|
||||
$c1 = $c->getNewCriterion(BookPeer::TITLE, '%Leo%', Criteria::LIKE);
|
||||
$c2 = $c->getNewCriterion(BookPeer::ISBN, '1234', Criteria::EQUAL);
|
||||
$c1->addOr($c2);
|
||||
$c->add($c1);
|
||||
}}}
|
||||
|
||||
`add()` and `addOr()` only allow simple logical operations on a single condition. For more complex logic, Propel 1.4 forced you to use Criterions again. This is no longer the case in Propel 1.5, which provides a new `Criteria::combine()` method. It expects an array of named conditions to be combined, and an operator. Use `Criteria::addCond()` to create a condition, instead of the usual `add()`:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$c = new Criteria();
|
||||
$c->addCond('cond1', BookPeer::TITLE, 'Foo', Criteria::EQUAL); // creates a condition named 'cond1'
|
||||
$c->addCond('cond2', BookPeer::TITLE, 'Bar', Criteria::EQUAL); // creates a condition named 'cond2'
|
||||
$c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR); // combine 'cond1' and 'cond2' with a logical OR
|
||||
// translates in SQL as
|
||||
// WHERE (book.TITLE = 'Foo' OR book.TITLE = 'Bar');
|
||||
}}}
|
||||
|
||||
`combine()` accepts more than two conditions at a time:
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$c = new Criteria();
|
||||
$c->addCond('cond1', BookPeer::TITLE, 'Foo', Criteria::EQUAL);
|
||||
$c->addCond('cond2', BookPeer::TITLE, 'Bar', Criteria::EQUAL);
|
||||
$c->addCond('cond3', BookPeer::TITLE, 'FooBar', Criteria::EQUAL);
|
||||
$c->combine(array('cond1', 'cond2', 'cond3'), Criteria::LOGICAL_OR);
|
||||
// translates in SQL as
|
||||
// WHERE ((book.TITLE = 'Foo' OR book.TITLE = 'Bar') OR book.TITLE = 'FooBar');
|
||||
}}}
|
||||
|
||||
`combine()` itself can return a named condition to be combined later. So it allows for any level of logical complexity:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$c = new Criteria();
|
||||
|
||||
$c->addCond('cond1', BookPeer::TITLE, 'Foo', Criteria::EQUAL);
|
||||
$c->addCond('cond2', BookPeer::TITLE, 'Bar', Criteria::EQUAL);
|
||||
$c->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR, 'cond12');
|
||||
|
||||
$c->addCond('cond3', BookPeer::ISBN, '1234', Criteria::EQUAL);
|
||||
$c->addCond('cond4', BookPeer::ISBN, '4567', Criteria::EQUAL);
|
||||
$c->combine(array('cond3', 'cond4'), Criteria::LOGICAL_OR, 'cond34');
|
||||
|
||||
$c->combine(array('cond12', 'cond34'), Criteria::LOGICAL_AND);
|
||||
|
||||
// WHERE (book.TITLE = 'Foo' OR book.TITLE = 'Bar')
|
||||
// AND (book.ISBN = '1234' OR book.ISBN = '4567');
|
||||
}}}
|
||||
|
||||
The new `combine()` method makes it much easier to handle logically complex criterions. The good news is that if your application code already uses the old Criterion way, it will continue to work with Propel 1.5 as all these changes are backwards compatible.
|
||||
|
||||
Of course, since Model Queries extend Criteria, this new feature is available for all your queries, with a slightly different syntax, in order to support column phpNames:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$books = Bookquery::create()
|
||||
->condition('cond1', 'Book.Title = ?', 'Foo')
|
||||
->condition('cond2', 'Book.Title = ?', 'Bar')
|
||||
->combine(array('cond1', 'cond2'), Criteria::LOGICAL_OR, 'cond12')
|
||||
->condition('cond3', 'Book.ISBN = ?', '1234')
|
||||
->condition('cond4', 'Book.ISBN = ?', '4567')
|
||||
->combine(array('cond3', 'cond4'), Criteria::LOGICAL_OR, 'cond34')
|
||||
->combine(array('cond12', 'cond34'), Criteria::LOGICAL_AND)
|
||||
->find();
|
||||
// WHERE (book.TITLE = 'Foo' OR book.TITLE = 'Bar')
|
||||
// AND (book.ISBN = '1234' OR book.ISBN = '4567');
|
||||
}}}
|
||||
|
||||
== Many-to-Many Relationships ==
|
||||
|
||||
At last, Propel generates the necessary methods to retrieve related objects in a many-to-many relationship. Since this feature is often needed, many developers already wrote these methods themselves. To avoid method collision, the generation of many-to-many getters is therefore optional.
|
||||
|
||||
All you have to do is to add the `isCrossRef` attribute to the cross reference table, and rebuild your model. For instance, if a `User` has many `Groups`, and the `Group` has many `Users`, the many-to-many relationship is materialized by a `user_group` cross reference table:
|
||||
|
||||
{{{
|
||||
#!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>
|
||||
}}}
|
||||
|
||||
Then, both end of the relationship see the other end through a one-to-many relationship. That means that you can deal with related objects just like you normally do, without ever creating instances of the cross reference object:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// create and relate objects as if they shared a one-to-many relationship
|
||||
$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();
|
||||
|
||||
// retrieve objects as if they shared a one-to-many relationship
|
||||
$groups = $user->getGroups();
|
||||
|
||||
// the model query also features a smart filter method for the relation
|
||||
$groups = GroupPeer::create()
|
||||
->filterByUser($user)
|
||||
->find();
|
||||
}}}
|
||||
|
||||
The syntax should be no surprise, since it's the same as the one for one-to-many relationships. Find more details about many-to-many relationships in the [wiki:Users/Documentation/1.5/Relationships relationships documentation].
|
||||
|
||||
== New Behaviors ==
|
||||
|
||||
The new behavior system, introduced in Propel 1.4, starts to unleash its true power with this release. Three new behaviors implement the most common customizations of object models: `nested_sets`, `sluggable`, and `sortable`.
|
||||
|
||||
=== Nested Set Behavior ===
|
||||
|
||||
Using the `treeMode` attribute in a schema, you could turn a Propel model into a hierarchical data store starting with Propel 1.3. This method is now deprecated in favor of a new `nested_set` behavior, that does eactly the same thing, but in a more extensible and effective way.
|
||||
|
||||
The main difference between the two implementations is performance. On the first levels of a large tree, the Propel 1.3 implementation of Nested sets used to consume a very large amount of memory and CPU to retrieve the siblings or the children of a given node. This is no longer true with the new behavior.
|
||||
|
||||
This performance boost comes at a small price: you must add a new "level" column to your nested set models, and let the behavior update this column for the whole tree.
|
||||
|
||||
For instance, if you used nested sets to keep a list of categories, the schema used to look like:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="category" treeMode="NestedSet">
|
||||
<column name="id" primaryKey="true" autoIncrement="true" type="INTEGER"/>
|
||||
<column name="left" nestedSetLeftKey="true" type="INTEGER"/>
|
||||
<column name="right" nestedSetLeftKey="true" type="INTEGER"/>
|
||||
<column name="name" required="true" type="VARCHAR" size="10" />
|
||||
</table>
|
||||
}}}
|
||||
|
||||
The upgrade path is then pretty straightforward:
|
||||
|
||||
1 - Update the schema, by removing the `treeMode` and `nestedSet` attributes and adding the `nested_set` behavior and the `tree_level` column:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="category">
|
||||
<column name="id" primaryKey="true" autoIncrement="true" type="INTEGER"/>
|
||||
<column name="left" type="INTEGER"/>
|
||||
<column name="right" type="INTEGER"/>
|
||||
<column name="tree_level" type="INTEGER"/>
|
||||
<column name="name" required="true" type="VARCHAR" size="10" />
|
||||
<behavior name="nested_set">
|
||||
<parameter name="left_column" value="left" />
|
||||
<parameter name="right_column" value="right" />
|
||||
<parameter name="level_column" value="tree_level" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
2 - Rebuild the model
|
||||
|
||||
3 - Change the parent class of your model classes (object and peer) that used the nested set `treeMode`:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// use
|
||||
class Category extends BaseCategory
|
||||
// instead of
|
||||
class Category extends BaseCategoryNestedSet
|
||||
|
||||
// use
|
||||
class CategoryPeer extends BaseCategoryPeer
|
||||
// instead of
|
||||
class CategoryPeer extends BaseCategoryNestedSetPeer
|
||||
}}}
|
||||
|
||||
4 - Add the level column to the database. For instance, in MySQL:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
ALTER TABLE `category` ADD COLUMN tree_level INTEGER;
|
||||
}}}
|
||||
|
||||
5 - Update the level value in the existing nodes, using the `fixLevels()` Peer method
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// run it once
|
||||
CategoryPeer::fixLevels();
|
||||
}}}
|
||||
|
||||
The nested set behavior implementation has a few added benefits:
|
||||
|
||||
* All the methods that execute several queries use transactions, so a database failure won't break a tree anymore
|
||||
* The methods retrieveing a list of nodes accept a Criteria as first parameter, to filter the results
|
||||
* New methods make it easier to work with trees: `retrieveRoots()`, `isDescendantOf()`, `isAncestorOf()`, `getBranch()`, `addChild()`, etc.
|
||||
* There is no longer any introspection at runtime (for instance to check scope support), resulting in yet another boost in performance
|
||||
* A few bugs were fixed (for instance in the use of `delete()`)
|
||||
* A node can be inserted to the tree after it is saved. This allows for better preparation of data before insertion in the tree
|
||||
* The new implementation is much more robust, thanks to a ''full unit testing coverage''. That's more than 350 unit tests to ensure that your trees won't ever break due to an incorrect piece of code in the nested sets.
|
||||
* The API was rethought to make it more intuitive - but with method proxies to keep BC
|
||||
|
||||
As a consequence, the use of `treeMode="NestedSet"` in a schema is deprecated. Check the new [wiki:Users/Documentation/1.5/Behaviors/nested_set nested_set behavior documentation] for more details.
|
||||
|
||||
=== Sluggable Behavior ===
|
||||
|
||||
This behavior answers a very common need: to give a model a unique string representation that can be used to make a user-friendly URL.
|
||||
|
||||
The classical example is that of a blog engine, where you need every record of a `post` table to have a unique URL. Simply enable the `sluggable` behavior in your schema and rebuild the model:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="post">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<column name="content" type="LONGVARCHAR"/>
|
||||
<behavior name="sluggable">
|
||||
<parameter name="slug_pattern" value="/posts/{Title}" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Now, every time you save a new `Post` object, Propel will compose its slug according to the pattern defined in the behavior parameter and save it in an additional `slug` column:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$post1 = new Post();
|
||||
$post1->setTitle('How Is Life On Earth?');
|
||||
$post1->setContent('Lorem Ipsum...');
|
||||
$post1->save();
|
||||
echo $post1->getSlug(); // '/posts/how-is-life-on-earth'
|
||||
}}}
|
||||
|
||||
Propel replaces every name enclosed between brackets in the slug pattern by the related column value. It also cleans up the string to make it URL-compatible, and ensures that it is unique.
|
||||
|
||||
If you use this slug in URLs, you will need to retrieve a `Post` object based on it. This is just a one-liner:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$post = PostQuery::create()->findOneBySlug('/posts/how-is-life-on-earth');
|
||||
}}}
|
||||
|
||||
There are many ways to customize the `sluggable` behavior to match the needs of your applications. Check the new [wiki:Users/Documentation/1.5/Behaviors/sluggable sluggable behavior documentation] for more details.
|
||||
|
||||
=== Concrete Table Inheritance Behavior ===
|
||||
|
||||
Propel has offered [wiki:Users/Documentation/1.5/Inheritance#SingleTableInheritance Single Table Inheritance] for a long time. But for complex table inheritance needs, it is necessary to provide [http://martinfowler.com/eaaCatalog/concreteTableInheritance.html Concrete Table Inheritance]. Starting with Propel 1.5, this inheritance implementation is supported through the new `concrete_inheritance` behavior.
|
||||
|
||||
In the following example, the `article` and `video` tables use this behavior to inherit the columns and foreign keys of their parent table, `content`:
|
||||
|
||||
{{{
|
||||
#!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>
|
||||
}}}
|
||||
|
||||
The behavior copies the columns of the parent table to the child tables. That means that the generated `Article` and `Video` models have a `Title` property and a `Category` relationship:
|
||||
|
||||
{{{
|
||||
#!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();
|
||||
}}}
|
||||
|
||||
If Propel stopped there, the `concrete_inheritance` behavior would only provide a shorcut to avoid repeating tags in the schema. But wait, there is more: the `Article` and `Video` classes actually extend the `Content` class:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
class Content extends BaseContent
|
||||
{
|
||||
public function getCategoryName()
|
||||
{
|
||||
return $this->getCategory()->getName();
|
||||
}
|
||||
}
|
||||
echo $art->getCategoryName(); // 'Movie'
|
||||
echo $vid->getCategoryName(); // 'Movie'
|
||||
}}}
|
||||
|
||||
And the true power of Propel's Concrete Table Inheritance is that 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)
|
||||
}}}
|
||||
|
||||
The resulting relational model is denormalized - in other terms, data is copied across tables - but the behavior takes care of everything for you. That allows for very effective read queries on complex inheritance structures.
|
||||
|
||||
Check out the brand new [wiki:Users/Documentation/1.5/Inheritance#ConcreteTableInheritance Inheritance Documentation] for more details on using and customizing this behavior.
|
||||
|
||||
=== Sortable Behavior ===
|
||||
|
||||
Have you ever enhanced a Propel Model to give it the ability to move up or down in an ordered list? The `sortable` behavior, new in Propel 1.5, offers exactly that... and even more.
|
||||
|
||||
As usual for behaviors, activate `sortable` in your `schema.yml`:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="task">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<column name="user_id" required="true" type="INTEGER" />
|
||||
<foreign-key foreignTable="user" onDelete="cascade">
|
||||
<reference local="user_id" foreign="id" />
|
||||
</foreign-key>
|
||||
<behavior name="sortable">
|
||||
<parameter name="use_scope" value="true" />
|
||||
<parameter name="scope_column" value="user_id" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Then rebuild your model, and you're done. You have just created an ordered task list for users:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// test users
|
||||
$paul = new User();
|
||||
$john = new User();
|
||||
|
||||
// create the tasks
|
||||
$t1 = new Task();
|
||||
$t1->setTitle('Wash the dishes');
|
||||
$t1->setUser($paul);
|
||||
$t1->save();
|
||||
echo $t1->getRank(); // 1
|
||||
$t2 = new Task();
|
||||
$t2->setTitle('Do the laundry');
|
||||
$t2->setUser($paul);
|
||||
$t2->save();
|
||||
echo $t2->getRank(); // 2
|
||||
$t3 = new Task();
|
||||
$t3->setTitle('Rest a little');
|
||||
$t3->setUser($john);
|
||||
$t3->save()
|
||||
echo $t3->getRank(); // 1, because John has his own task list
|
||||
|
||||
// retrieve the tasks
|
||||
$allPaulsTasks = TaskPeer::retrieveList($scope = $paul->getId());
|
||||
$allJohnsTasks = TaskPeer::retrieveList($scope = $john->getId());
|
||||
$t1 = TaskPeer::retrieveByRank($rank = 1, $scope = $paul->getId());
|
||||
$t2 = $t1->getNext();
|
||||
$t2->moveUp();
|
||||
echo $t2->getRank(); // 1
|
||||
echo $t1->getRank(); // 2
|
||||
}}}
|
||||
|
||||
This new behavior is fully unit tested and very customizable. Check out all you can do with `sortable` in the [wiki:Users/Documentation/1.5/Behaviors/sortable sortable behavior documentation].
|
||||
|
||||
=== Timestampable Behavior ===
|
||||
|
||||
This behavior is not new, since it was introduced in Propel 1.4. However, with the introduction of model queries, it gains specific query methods that will ease your work when retrieving objects based on their update date:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$books = BookQuery::create()
|
||||
->recentlyUpdated() // adds a minimum value for the update date
|
||||
->lastUpdatedFirst() // orders the results by descending update date
|
||||
->find();
|
||||
}}}
|
||||
|
||||
== Better `toArray()` ==
|
||||
|
||||
When you call `toArray()` on a model object, you can now ask for the related objects:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$bookArray = $book->toArray($keyType = BasePeer::TYPE_COLNAME, $includeLazyLoadColumns = true, $includeForeignObjects = true);
|
||||
print_r($bookArray);
|
||||
=> array(
|
||||
'Id' => 123,
|
||||
'Title' => 'War And Peace',
|
||||
'ISBN' => '3245234535',
|
||||
'AuthorId' => 456,
|
||||
'PublisherId' => 567
|
||||
'Author' => array(
|
||||
'Id' => 456,
|
||||
'FirstName' => 'Leo',
|
||||
'LastName' => 'Tolstoi'
|
||||
),
|
||||
'Publisher' => array(
|
||||
'Id' => 567,
|
||||
'Name' => 'Penguin'
|
||||
)
|
||||
)
|
||||
}}}
|
||||
|
||||
Only the related objects that were already hydrated appear in the result, so `toArray()` never issues additional queries. Together with the ability to return arrays instead of objects when using `PropelQuery`, this addition will help to debug and optimize model code.
|
||||
|
||||
== Better Oracle Support ==
|
||||
|
||||
The Oracle adapter for the generator, the reverse engineering, and the runtime components have been greatly improved. This should provide an easier integration of Propel with an Oracle database.
|
||||
|
||||
== Code Cleanup ==
|
||||
|
||||
=== Directory Structure Changes ===
|
||||
|
||||
The organization of the Propel runtime and generator code has been reworked, in order to make navigation across Propel classes easier for developers. End users should see no difference, apart if your `build.properties` references alternate builder classes in the Propel code. In that case, you will need to update your `build.properties` with the new paths. For instance, a reference to:
|
||||
|
||||
{{{
|
||||
#!ini
|
||||
propel.builder.peer.class = propel.engine.builder.om.php5.PHP5PeerBuilder
|
||||
}}}
|
||||
|
||||
Must be changed to:
|
||||
|
||||
{{{
|
||||
#!ini
|
||||
propel.builder.peer.class = builder.om.PHP5PeerBuilder
|
||||
}}}
|
||||
|
||||
Browse the Propel generator directory structure to find the classes you need.
|
||||
|
||||
=== DebugPDO Refactoring ===
|
||||
|
||||
To allow custom connection handlers, the debug code that was written in the `DebugPDO` class has been moved to `PropelPDO`. The change is completely backwards compatible, but makes it easier to connect to a database without using PDO.
|
||||
|
||||
During the change, the [wiki:Users/Documentation/1.5/07-Logging documentation about Propel logging and debugging features] was rewritten and should now be clearer.
|
||||
|
||||
== propel-gen Script Modifications ==
|
||||
|
||||
The `propel-gen` script no longer requires a path to the project directory if you call it from a project directory. That means that calling `propel-gen` with a single argument defaults to expecting a task name:
|
||||
|
||||
{{{
|
||||
> cd /path/to/my/project
|
||||
> propel-gen reverse
|
||||
}}}
|
||||
|
||||
By default, the `propel-gen` command called without a task name defaults to the `main` task (and builds the model, the SQL, and the generation).
|
||||
|
||||
Note: The behavior of the `propel-gen` script when called with one parameter differs from what it used to be in Propel 1.4, where the script expected a path in every situation. So the following syntax won't work anymore:
|
||||
|
||||
{{{
|
||||
> propel-gen /path/to/my/project
|
||||
}}}
|
||||
|
||||
Instead, use either:
|
||||
|
||||
{{{
|
||||
> cd /path/to/my/project
|
||||
> propel-gen
|
||||
}}}
|
||||
|
||||
or:
|
||||
|
||||
{{{
|
||||
> propel-gen /path/to/my/project main
|
||||
}}}
|
||||
|
||||
== License Change ==
|
||||
|
||||
Propel is more open-source than ever. To allow for an easier distribution, the open-source license of the Propel library changes from LGPL3 to MIT. This [http://en.wikipedia.org/wiki/MIT_License MIT License] is also known as the X11 License.
|
||||
|
||||
This change removes a usage restriction enforced by the LGPL3: you no longer need to release any modifications to the core Propel source code under a LGPL compatible license.
|
||||
|
||||
Of course, you still have the right to use, copy, modify, merge, publish, distribute, sublicense, and/or sell Propel. In other terms, you can do whatever you want with the Propel code, without worrying about the license, as long as you leave the LICENSE file within.
|
||||
|
||||
== Miscellaneous ==
|
||||
|
||||
* Generated model classes now offer a `fromArray()` and a `toArray()` method by default. This feature existed before, but was disabled by default in the `build.properties`. The `addGenericAccessors` and `addGenericMutators` settings are therefore enabled by default in Propel 1.5.
|
||||
* You can now prefix all the table names of a database schema by setting the `tablePrefix` attribute of the `<database>` tag.
|
||||
* The `addIncludes` build property introduced in Propel 1.4 is now set to `false` by default. That means that the runtime autoloading takes care of loading all classes at runtime, including generated Base classes.
|
||||
* A bugfix in the name generator for related object getter in tables with two foreign keys related to the same table may have introduced problems in applications relying on old (wrong) names. Check your generated base model classes for the `getXXXrelatedByYYY()` and modify the application code relying on it if it exists. A good rule of thumb to avoid problems in such case is to name your relations by using the `phpName` and `refPhpName` attributes in the `<foreign-key>` element in the schema.
|
||||
* XSL transformation of your schemas is no longer enabled by default. Turn the `propel.schema.transform` setting to `true` in your `build.properties` to enable it again. This change removes the requirement on the libxslt extention for Propel.
|
||||
* `ModelObject::addSelectColumns()` now accepts an additional parameter to allow the use of table aliases
|
||||
* Added `ModelObject::clear()` to reinitialize a model object
|
||||
* Added `ModelObject::isPrimaryKeyNull()` method to check of an object was hydrated with no values (in case of a left join)
|
||||
* Added `Criteria::addSelectModifier($modifier)` to add more than one select modifier (e.g. 'SQL_CALC_FOUND_ROWS', 'HIGH_PRIORITY', etc.)
|
||||
* Added `PeerClass::addGetPrimaryKeyFromRow()` to retrieve the Primary key from a result row
|
||||
* Added a new set of constants in the generated Peer class to list column names without the table name (this is `BasePeer::TYPE_RAW_COLNAME`)
|
||||
* Removed references to Creole in the code (Propel uses PDO instead of Creole since version 1.3)
|
|
@ -1,381 +0,0 @@
|
|||
<?xml version="1.0"?>
|
||||
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
|
||||
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>
|
||||
<xsl:strip-space elements="*"/>
|
||||
|
||||
<!--
|
||||
DB Designer XML to Propel Schema XML
|
||||
|
||||
==== Author: Jonathan Graham <jkgraham@gmail.com>
|
||||
==== Version: 0.5 (2008-01-25) (http://blog.tooleshed.com/?p=6)
|
||||
==== Description:
|
||||
This XSL will transform a DB Designer 4 database model XML file into a
|
||||
Propel database schema file. This allows you to design your database
|
||||
model using DB Designer 4 (models are saved in XML format) and then
|
||||
easily create the Propel database schema file.
|
||||
|
||||
The PROPEL properties that this XSL will translate are listed below.
|
||||
|
||||
TABLE: name, description
|
||||
COLUMN: name, primaryKey, required, type, size, scale, default, autoIncrement, description
|
||||
FOREIGN-KEY: foreignTable, name, onDelete
|
||||
REFERENCE: local, foreign
|
||||
INDEX: index (not related to FK), unique, fulltext
|
||||
|
||||
==== Usage:
|
||||
- Simply feed this XSL into your favorite XSLT engine along with your DB Designer
|
||||
XML model. The resulting output is a Propel database schema XML.
|
||||
|
||||
==== Collaboration:
|
||||
Peter Banik <peter@froggle.org> - UNIQUE TAG
|
||||
Benedicto Franco Jr. - MULTIPLE FOREIGN KEY, DATABASE NAME
|
||||
Martin Kreidenweis <martin@kreidenweis.com> - Bug fixes, INDEX
|
||||
Michiel Hakvoort - onDelete
|
||||
Michel D'HOOGE - FULLTEXT
|
||||
Oleg Marchuk <kingoleg@mail.ru> - version 0.5
|
||||
|
||||
==== Software:
|
||||
Propel: http://propel.phpdb.org/
|
||||
DB Designer 4: http://www.fabforce.net/dbdesigner4/
|
||||
|
||||
==== Copyright (c) 2004-2006, Jonathan Graham
|
||||
Licensed under the GNU Lesser General Public License (LGPL) - http://www.gnu.org/copyleft/lgpl.html.
|
||||
|
||||
==== Change Log
|
||||
version 0.1 (2004-11-08) - initial version
|
||||
version 0.2 (2006-10-18) - Added Peter and Benedicto's updates.
|
||||
version 0.3 (2006-11-05) - added non-unique-INDEXes and onDelete
|
||||
version 0.4 (2006-11-13) - added support for index names and FULLTEXT indexes, changed license to LGPL
|
||||
version 0.5 (2008-01-25) - added ENUM, GEOMETRY as BLOB, scale for DECIMAL; fixed size in ENUM and spaces in relation names
|
||||
|
||||
-->
|
||||
|
||||
<!-- ============================================================ DATABASE template -->
|
||||
<xsl:template match="/">
|
||||
<database defaultIdMethod="native">
|
||||
<xsl:attribute name="name">
|
||||
<xsl:value-of select="/DBMODEL/SETTINGS/GLOBALSETTINGS/@ModelName"/>
|
||||
</xsl:attribute>
|
||||
<xsl:apply-templates />
|
||||
</database>
|
||||
</xsl:template>
|
||||
|
||||
<!-- ============================================================ TABLES template -->
|
||||
<xsl:template match="/DBMODEL/METADATA/TABLES/TABLE">
|
||||
<table>
|
||||
<xsl:attribute name="name">
|
||||
<xsl:value-of select="@Tablename"/>
|
||||
</xsl:attribute>
|
||||
<xsl:if test="@Comments != ''">
|
||||
<xsl:attribute name="description">
|
||||
<xsl:value-of select="@Comments" />
|
||||
</xsl:attribute>
|
||||
</xsl:if>
|
||||
<xsl:apply-templates />
|
||||
</table>
|
||||
</xsl:template>
|
||||
|
||||
|
||||
<!-- ============================================================ COLUMNS template -->
|
||||
<xsl:template match="COLUMNS/COLUMN">
|
||||
<column>
|
||||
<!-- get data type -->
|
||||
<xsl:variable name="datatype">
|
||||
<xsl:call-template name="get_datatype">
|
||||
<xsl:with-param name="id"><xsl:value-of select="@idDatatype"/></xsl:with-param>
|
||||
</xsl:call-template>
|
||||
</xsl:variable>
|
||||
|
||||
<!-- remove parens from datatypeparams -->
|
||||
<xsl:variable name="dtpclean">
|
||||
<xsl:call-template name="clean_dataparams">
|
||||
<xsl:with-param name="dtp"><xsl:value-of select="@DatatypeParams"/></xsl:with-param>
|
||||
</xsl:call-template>
|
||||
</xsl:variable>
|
||||
|
||||
<!-- ==== name ==== -->
|
||||
<xsl:attribute name="name">
|
||||
<xsl:value-of select="@ColName"/>
|
||||
</xsl:attribute>
|
||||
|
||||
<!-- ==== type ==== -->
|
||||
<xsl:attribute name="type">
|
||||
<xsl:choose>
|
||||
<xsl:when test="$datatype = 'ENUM'">
|
||||
<xsl:value-of select="'CHAR'" />
|
||||
</xsl:when>
|
||||
<xsl:otherwise>
|
||||
<xsl:value-of select="$datatype"/>
|
||||
</xsl:otherwise>
|
||||
</xsl:choose>
|
||||
</xsl:attribute>
|
||||
|
||||
<xsl:if test="$dtpclean != ''">
|
||||
<!-- ==== size ==== -->
|
||||
<xsl:attribute name="size">
|
||||
<xsl:call-template name="get_datasize">
|
||||
<xsl:with-param name="dtpc"><xsl:value-of select="$dtpclean"/></xsl:with-param>
|
||||
<xsl:with-param name="dtype"><xsl:value-of select="$datatype"/></xsl:with-param>
|
||||
</xsl:call-template>
|
||||
</xsl:attribute>
|
||||
|
||||
<xsl:if test="contains('FLOAT,DOUBLE,DECIMAL',$datatype)">
|
||||
<!-- ==== scale ==== -->
|
||||
<xsl:attribute name="scale">
|
||||
<xsl:value-of select="substring-after($dtpclean,',')"/>
|
||||
</xsl:attribute>
|
||||
</xsl:if>
|
||||
|
||||
</xsl:if>
|
||||
|
||||
<!-- ==== primaryKey ==== -->
|
||||
<xsl:if test="@PrimaryKey = '1'">
|
||||
<xsl:attribute name="primaryKey">true</xsl:attribute>
|
||||
</xsl:if>
|
||||
|
||||
<!-- ==== required ==== -->
|
||||
<xsl:if test="@NotNull = '1'">
|
||||
<xsl:attribute name="required">true</xsl:attribute>
|
||||
</xsl:if>
|
||||
|
||||
<!-- ==== default ==== -->
|
||||
<xsl:if test="@DefaultValue != ''">
|
||||
<xsl:attribute name="default">
|
||||
<xsl:value-of select="@DefaultValue"/>
|
||||
</xsl:attribute>
|
||||
</xsl:if>
|
||||
|
||||
<!-- ==== autoIncrement ==== -->
|
||||
<xsl:if test="@AutoInc = '1'">
|
||||
<xsl:attribute name="autoIncrement">true</xsl:attribute>
|
||||
</xsl:if>
|
||||
|
||||
<!-- ==== description ==== -->
|
||||
<xsl:if test="@Comments != ''">
|
||||
<xsl:attribute name="description">
|
||||
<xsl:value-of select="@Comments"/>
|
||||
</xsl:attribute>
|
||||
</xsl:if>
|
||||
|
||||
</column>
|
||||
</xsl:template>
|
||||
|
||||
<!-- ============================================================ RELATIONS template -->
|
||||
<xsl:template match="RELATIONS_END/RELATION_END">
|
||||
|
||||
<xsl:variable name="id"><xsl:value-of select="@ID"/></xsl:variable>
|
||||
|
||||
<xsl:call-template name="show_ForeignKey">
|
||||
<xsl:with-param name="relation" select="/DBMODEL/METADATA/RELATIONS/RELATION[@ID=$id]"/>
|
||||
</xsl:call-template>
|
||||
|
||||
</xsl:template>
|
||||
|
||||
<!-- ============================================================ INDEX template -->
|
||||
<xsl:template match="INDICES/INDEX">
|
||||
<xsl:choose>
|
||||
<xsl:when test="@IndexKind = '1' and @FKRefDef_Obj_id='-1'">
|
||||
<index>
|
||||
<xsl:attribute name="name"><xsl:value-of select="@IndexName"/></xsl:attribute>
|
||||
<xsl:apply-templates select="INDEXCOLUMNS/INDEXCOLUMN" mode="normal"/>
|
||||
</index>
|
||||
</xsl:when>
|
||||
<xsl:when test="@IndexKind = '2'">
|
||||
<unique>
|
||||
<xsl:attribute name="name"><xsl:value-of select="@IndexName"/></xsl:attribute>
|
||||
<xsl:apply-templates select="INDEXCOLUMNS/INDEXCOLUMN" mode="unique"/>
|
||||
</unique>
|
||||
</xsl:when>
|
||||
<xsl:when test="@IndexKind = '3'">
|
||||
<index>
|
||||
<xsl:attribute name="name"><xsl:value-of select="@IndexName"/></xsl:attribute>
|
||||
<xsl:apply-templates select="INDEXCOLUMNS/INDEXCOLUMN" mode="normal"/>
|
||||
<vendor type="mysql">
|
||||
<parameter name="Index_type" value="FULLTEXT"/>
|
||||
</vendor>
|
||||
</index>
|
||||
</xsl:when>
|
||||
</xsl:choose>
|
||||
</xsl:template>
|
||||
|
||||
|
||||
<!-- ============================================================ columns within an index -->
|
||||
<xsl:template match="INDICES/INDEX/INDEXCOLUMNS/INDEXCOLUMN" mode="normal">
|
||||
<xsl:variable name="columnId"><xsl:value-of select="@idColumn"/></xsl:variable>
|
||||
<index-column>
|
||||
<xsl:attribute name="name"><xsl:value-of select="//COLUMNS/COLUMN[@ID=$columnId]/@ColName"/></xsl:attribute>
|
||||
</index-column>
|
||||
</xsl:template>
|
||||
|
||||
<xsl:template match="INDICES/INDEX/INDEXCOLUMNS/INDEXCOLUMN" mode="unique">
|
||||
<xsl:variable name="columnId"><xsl:value-of select="@idColumn"/></xsl:variable>
|
||||
<unique-column>
|
||||
<xsl:attribute name="name"><xsl:value-of select="//COLUMNS/COLUMN[@ID=$columnId]/@ColName"/></xsl:attribute>
|
||||
</unique-column>
|
||||
</xsl:template>
|
||||
|
||||
|
||||
<!-- ============================================================ show_ForeignKey -->
|
||||
<xsl:template name="show_ForeignKey">
|
||||
<xsl:param name="relation"/>
|
||||
<foreign-key>
|
||||
|
||||
<!-- foreignTable -->
|
||||
<xsl:attribute name="foreignTable">
|
||||
<xsl:value-of select="/DBMODEL/METADATA/TABLES/TABLE[@ID=$relation/@SrcTable]/@Tablename"/>
|
||||
</xsl:attribute>
|
||||
|
||||
<!-- name -->
|
||||
<xsl:attribute name="name">
|
||||
<xsl:value-of select="translate($relation/@RelationName, ' ', '_')"/>
|
||||
</xsl:attribute>
|
||||
|
||||
<!-- onDelete -->
|
||||
<xsl:attribute name="onDelete">
|
||||
|
||||
<xsl:variable name="actionId">
|
||||
<xsl:call-template name="str_replace">
|
||||
<xsl:with-param name="stringIn" select="substring-before(substring-after($relation/@RefDef,'\n'), '\n')"/>
|
||||
<xsl:with-param name="charsIn" select="'OnDelete='"/>
|
||||
<xsl:with-param name="charsOut" select="''"/>
|
||||
</xsl:call-template>
|
||||
</xsl:variable>
|
||||
|
||||
<xsl:call-template name="get_actiontype">
|
||||
<xsl:with-param name="id" select="$actionId" />
|
||||
</xsl:call-template>
|
||||
|
||||
</xsl:attribute>
|
||||
|
||||
<!-- === reference tag === -->
|
||||
<xsl:call-template name="build_fk">
|
||||
<xsl:with-param name="stringIn" select="$relation/@FKFields"/>
|
||||
</xsl:call-template>
|
||||
|
||||
</foreign-key>
|
||||
</xsl:template>
|
||||
|
||||
<!--
|
||||
============================================================
|
||||
============================================================ template "functions"
|
||||
============================================================
|
||||
-->
|
||||
|
||||
<!-- ============================================================ get_datatype -->
|
||||
<xsl:template name="get_datatype">
|
||||
<xsl:param name="id"/>
|
||||
|
||||
<xsl:variable name="type">
|
||||
<xsl:value-of select="/DBMODEL/SETTINGS/DATATYPES/DATATYPE[@ID=$id]/@TypeName"/>
|
||||
</xsl:variable>
|
||||
|
||||
<xsl:choose>
|
||||
<xsl:when test="$type = 'DATETIME'" >TIMESTAMP</xsl:when>
|
||||
<xsl:when test="$type = 'TEXT'" >LONGVARCHAR</xsl:when>
|
||||
<xsl:when test="$type = 'BOOL'" >BOOLEAN</xsl:when>
|
||||
<xsl:when test="$type = 'GEOMETRY'" >BLOB</xsl:when>
|
||||
<xsl:otherwise>
|
||||
<xsl:value-of select="$type"/>
|
||||
</xsl:otherwise>
|
||||
</xsl:choose>
|
||||
|
||||
</xsl:template>
|
||||
|
||||
|
||||
<!-- ============================================================ get_datasize -->
|
||||
<xsl:template name="get_datasize">
|
||||
<xsl:param name="dtpc"/>
|
||||
<xsl:param name="dtype"/>
|
||||
|
||||
<xsl:choose>
|
||||
<xsl:when test="contains('FLOAT,DOUBLE,DECIMAL',$dtype)" >
|
||||
<xsl:value-of select="substring-before($dtpc,',')"/>
|
||||
</xsl:when>
|
||||
<xsl:when test="$dtype = 'ENUM'">
|
||||
<xsl:value-of select="''" />
|
||||
</xsl:when>
|
||||
<xsl:otherwise>
|
||||
<xsl:value-of select="$dtpc"/>
|
||||
</xsl:otherwise>
|
||||
</xsl:choose>
|
||||
|
||||
</xsl:template>
|
||||
|
||||
|
||||
<!-- ============================================================ clean_dataparams -->
|
||||
<xsl:template name="clean_dataparams">
|
||||
<xsl:param name="dtp"/>
|
||||
|
||||
<xsl:variable name="dtp2">
|
||||
<xsl:call-template name="str_replace">
|
||||
<xsl:with-param name="stringIn" select="$dtp"/>
|
||||
<xsl:with-param name="charsIn" select="'('"/>
|
||||
<xsl:with-param name="charsOut" select="''"/>
|
||||
</xsl:call-template>
|
||||
</xsl:variable>
|
||||
|
||||
<xsl:call-template name="str_replace">
|
||||
<xsl:with-param name="stringIn" select="$dtp2"/>
|
||||
<xsl:with-param name="charsIn" select="')'"/>
|
||||
<xsl:with-param name="charsOut" select="''"/>
|
||||
</xsl:call-template>
|
||||
|
||||
</xsl:template>
|
||||
|
||||
|
||||
<!-- ============================================================ str_replace -->
|
||||
<xsl:template name="str_replace">
|
||||
<xsl:param name="stringIn"/>
|
||||
<xsl:param name="charsIn"/>
|
||||
<xsl:param name="charsOut"/>
|
||||
<xsl:choose>
|
||||
<xsl:when test="contains($stringIn,$charsIn)">
|
||||
<xsl:value-of select="concat(substring-before($stringIn,$charsIn),$charsOut)"/>
|
||||
<xsl:call-template name="str_replace">
|
||||
<xsl:with-param name="stringIn" select="substring-after($stringIn,$charsIn)"/>
|
||||
<xsl:with-param name="charsIn" select="$charsIn"/>
|
||||
<xsl:with-param name="charsOut" select="$charsOut"/>
|
||||
</xsl:call-template>
|
||||
</xsl:when>
|
||||
<xsl:otherwise>
|
||||
<xsl:value-of select="$stringIn"/>
|
||||
</xsl:otherwise>
|
||||
</xsl:choose>
|
||||
</xsl:template>
|
||||
|
||||
|
||||
<!-- ============================================================== build_fk -->
|
||||
<xsl:template name="build_fk">
|
||||
<xsl:param name="stringIn"/>
|
||||
<xsl:variable name="FKClean">
|
||||
<xsl:value-of select="substring-before($stringIn, '\n')"/>
|
||||
</xsl:variable>
|
||||
<reference>
|
||||
<xsl:attribute name="local">
|
||||
<xsl:value-of select="substring-after($FKClean, '=')"/>
|
||||
</xsl:attribute>
|
||||
<xsl:attribute name="foreign">
|
||||
<xsl:value-of select="substring-before($FKClean, '=')"/>
|
||||
</xsl:attribute>
|
||||
</reference>
|
||||
<xsl:if test="contains(substring-after($stringIn,'\n'),'=')">
|
||||
<xsl:call-template name="build_fk">
|
||||
<xsl:with-param name="stringIn" select="substring-after($stringIn,'\n')"/>
|
||||
</xsl:call-template>
|
||||
</xsl:if>
|
||||
</xsl:template>
|
||||
|
||||
<!-- ======================================================== get_actiontype -->
|
||||
|
||||
<xsl:template name="get_actiontype">
|
||||
<xsl:param name="id"/>
|
||||
|
||||
<xsl:choose>
|
||||
<xsl:when test="$id = 0">restrict</xsl:when>
|
||||
<xsl:when test="$id = 1">cascade</xsl:when>
|
||||
<xsl:when test="$id = 2">setnull</xsl:when>
|
||||
<xsl:otherwise>restrict</xsl:otherwise>
|
||||
</xsl:choose>
|
||||
</xsl:template>
|
||||
|
||||
</xsl:stylesheet>
|
|
@ -1,21 +0,0 @@
|
|||
<?php
|
||||
/*
|
||||
This PHP5 script will load the transform a DB Designer 4 database model to the
|
||||
propel database schema file format
|
||||
*/
|
||||
|
||||
// load the DB Designer 4 XML
|
||||
$xml = new DOMDocument;
|
||||
$xml->load('model.xml');
|
||||
|
||||
// load the transformation stylesheet
|
||||
$xsl = new DOMDocument;
|
||||
$xsl->load('dbd2propel.xsl');
|
||||
|
||||
$proc = new XSLTProcessor();
|
||||
// attach the xsl rules
|
||||
$proc->importStyleSheet($xsl);
|
||||
|
||||
$schema_xml = $proc->transformToXML($xml);
|
||||
|
||||
file_put_contents('schema.xml', $schema_xml);
|
File diff suppressed because it is too large
Load Diff
|
@ -1,42 +0,0 @@
|
|||
<?php
|
||||
|
||||
class patForms_Creator_Definition {
|
||||
|
||||
static function create($definition, $object = null) {
|
||||
|
||||
$form = patForms::createForm(null, array(
|
||||
'name' => $definition->name
|
||||
));
|
||||
|
||||
foreach ($definition->elements as $el) {
|
||||
$element = &$form->createElement($el['name'], $el['type'], null);
|
||||
if (!empty($el['attributes']['datasource'])) {
|
||||
$ds = $el['attributes']['datasource'];
|
||||
unset($el['attributes']['datasource']);
|
||||
$element->setDatasource(new $ds['name']($ds));
|
||||
}
|
||||
// patForms will choke when we try to set attributes that
|
||||
// don't exist for an element type. So we'll have to ask.
|
||||
foreach ($el['attributes'] as $name => $value) {
|
||||
if ($element->hasAttribute($name)) {
|
||||
$element->setAttribute($name, $value);
|
||||
}
|
||||
}
|
||||
if (isset($el['rules'])) {
|
||||
foreach ($el['rules'] as $rule) {
|
||||
$element->addRule(new $rule['type']($rule));
|
||||
}
|
||||
}
|
||||
$form->addElement($element);
|
||||
}
|
||||
if (!is_null($object)) {
|
||||
$form->setValues($object->toArray());
|
||||
}
|
||||
if ($definition->autoValidate) {
|
||||
$form->setAutoValidate($definition->autoValidate);
|
||||
}
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,132 +0,0 @@
|
|||
<?php
|
||||
/**
|
||||
* patForms Creator Propel
|
||||
*
|
||||
* @package patForms
|
||||
* @subpackage Creator
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Error: could not connect to the database
|
||||
*/
|
||||
define( 'PATFORMS_CREATOR_PROPEL_ERROR_NO_CONNECTION', 'patForms:Creator:Propel:01' );
|
||||
|
||||
/**
|
||||
* patForms Creator DB
|
||||
*
|
||||
* @access protected
|
||||
* @package patForms
|
||||
* @subpackage Creator
|
||||
* @author Bert Van den Brande <cyruzb@gmail.com>
|
||||
* @license LGPL, see license.txt for details
|
||||
* @link http://www.php-tools.net
|
||||
*/
|
||||
class patForms_Creator_Propel extends patForms_Creator
|
||||
{
|
||||
private static $creoleTypeMapping = array(
|
||||
CreoleTypes::BOOLEAN =>'Radio', // BOOLEAN = 1;
|
||||
CreoleTypes::BIGINT =>'String', // BIGINT = 2;
|
||||
CreoleTypes::SMALLINT =>'String', // SMALLINT = 3;
|
||||
CreoleTypes::TINYINT =>'String', // TINYINT = 4;
|
||||
CreoleTypes::INTEGER =>'String', // INTEGER = 5;
|
||||
CreoleTypes::CHAR =>'String', // CHAR = 6;
|
||||
CreoleTypes::VARCHAR =>'String', // VARCHAR = 7;
|
||||
CreoleTypes::FLOAT =>'String', // FLOAT = 8;
|
||||
CreoleTypes::DOUBLE =>'String', // DOUBLE = 9;
|
||||
CreoleTypes::DATE =>'Date', // DATE = 10;
|
||||
CreoleTypes::TIME =>'String', // TIME = 11;
|
||||
CreoleTypes::TIMESTAMP =>'Date', // TIMESTAMP = 12;
|
||||
CreoleTypes::VARBINARY =>'String', // VARBINARY = 13;
|
||||
CreoleTypes::NUMERIC =>'String', // NUMERIC = 14;
|
||||
CreoleTypes::BLOB =>'String', // BLOB = 15;
|
||||
CreoleTypes::CLOB =>'String', // CLOB = 16;
|
||||
CreoleTypes::TEXT =>'Text', // TEXT = 17;
|
||||
CreoleTypes::LONGVARCHAR =>'Text', // LONGVARCHAR = 17;
|
||||
CreoleTypes::DECIMAL =>'String', // DECIMAL = 18;
|
||||
CreoleTypes::REAL =>'String', // REAL = 19;
|
||||
CreoleTypes::BINARY =>'String', // BINARY = 20;
|
||||
CreoleTypes::LONGVARBINARY =>'String', // LONGVARBINARY = 21;
|
||||
CreoleTypes::YEAR =>'String', // YEAR = 22;
|
||||
CreoleTypes::ARR =>'String',
|
||||
CreoleTypes::OTHER =>'String'
|
||||
);
|
||||
|
||||
/**
|
||||
* Create a form from a propel instance
|
||||
*
|
||||
* @access public
|
||||
* @param mixed $object An instance of a Propel object
|
||||
* @param array $options Any options the creator may need
|
||||
* @return object $form The patForms object, or a patError object on failure.
|
||||
*/
|
||||
function &create( $object, $options = array() )
|
||||
{
|
||||
// Propel stuff
|
||||
$propel_peer = $object->getPeer();
|
||||
$propel_mapBuilder = $propel_peer->getMapBuilder(); // Not sure if we're gonna need this one
|
||||
$propel_tablename = constant(get_class($propel_peer) . '::TABLE_NAME');
|
||||
$propel_tableMap = $propel_mapBuilder->getDatabaseMap()->getTable($propel_tablename);
|
||||
|
||||
// The form
|
||||
$form =& patForms::createForm( null, array( 'name' => 'patForms_Creator_Form' ) );
|
||||
|
||||
$propel_cols = $propel_tableMap->getColumns();
|
||||
foreach ($propel_cols as $propel_colname => $propel_col) {
|
||||
|
||||
// phpName can be altered by editing the schema.xml,
|
||||
// thus I think, we should lowercase()/ucfirst() this
|
||||
$propel_colname = strtolower($propel_colname);
|
||||
$el_displayname = ucFirst($propel_colname);
|
||||
// this could be omitted of course, but I think, it's a
|
||||
// convenient way to get more safe request properties
|
||||
$el_name = $propel_tablename . '[' . $propel_colname . ']';
|
||||
|
||||
$el_attr = array(
|
||||
'edit' => 'yes',
|
||||
'title' => $el_displayname,
|
||||
'label' => $el_displayname,
|
||||
'name' => $el_name,
|
||||
'description' => $el_displayname
|
||||
);
|
||||
|
||||
//// Obsolete ?
|
||||
// Parse column info to element type info
|
||||
//$type_info = $this->parseTypeInfoFromColumn($propel_col);
|
||||
// Merge extra element attributes
|
||||
//$el_attr = array_merge( $el_attr, $type_info['attributes'] );
|
||||
|
||||
// Is the element required ? Can we retrieve this info from the Column object ?
|
||||
$el_attr['required'] = 'yes';
|
||||
// Value: for now we use default to set the value. Is there a better (more correct) way to do this ?
|
||||
$el_attr['default'] = $object->{'get'.$propel_col->getPhpName()}();
|
||||
|
||||
if ($propel_col->isPrimaryKey()) {
|
||||
$el_type = 'hidden';
|
||||
} else {
|
||||
$el_type = self::$creoleTypeMapping[$propel_col->getCreoleType()];
|
||||
}
|
||||
|
||||
$el = &$form->createElement($el_name, $el_type, null);
|
||||
// patForms will choke when we try to set attributes
|
||||
// that don't match the element type. So we'll ask.
|
||||
foreach ($el_attr as $name => $value) {
|
||||
if ($el->hasAttribute($name)) {
|
||||
$el->setAttribute($name, $value);
|
||||
}
|
||||
}
|
||||
$form->addElement($el);
|
||||
}
|
||||
|
||||
return $form;
|
||||
}
|
||||
|
||||
// Seems this function will become obsolete if we use the static $creoleTypeMapping
|
||||
function parseTypeInfoFromColumn ( $column ) {
|
||||
|
||||
return array(
|
||||
'type' => 'String',
|
||||
'attributes' => array()
|
||||
);
|
||||
}
|
||||
}
|
|
@ -1,201 +0,0 @@
|
|||
<?php
|
||||
/**
|
||||
* patForms_Creator_DB examples
|
||||
*
|
||||
* patForms_Creator is a subpackage of patForms that provides
|
||||
* several formbuilder classes that create a form from
|
||||
* a datasource.
|
||||
*
|
||||
* WARNING:
|
||||
* The Creator subpackage is still in devel state!
|
||||
*
|
||||
* @access public
|
||||
* @package patForms
|
||||
* @subpackage Examples
|
||||
* @author Stephan Schmidt <schst@php-tools.net
|
||||
* @author Sebastian Mordziol <argh@php-tools.net>
|
||||
* @license LGPL, see license.txt for details
|
||||
* @link http://www.php-tools.net
|
||||
*/
|
||||
|
||||
/**
|
||||
* Main examples prepend file, needed *only* for the examples framework!
|
||||
*/
|
||||
//include_once 'patExampleGen/prepend.php';
|
||||
//$exampleGen->displayHead( 'Example' );
|
||||
|
||||
include('include/common.php');
|
||||
|
||||
// EXAMPLE START ------------------------------------------------------
|
||||
|
||||
/**
|
||||
* main patForms class
|
||||
*/
|
||||
require_once ('patForms.php');
|
||||
|
||||
/**
|
||||
* patErrorManager class
|
||||
*/
|
||||
require_once ('patErrorManager.php');
|
||||
|
||||
|
||||
// create the creator :)
|
||||
$creator = &patForms::createCreator( 'Propel' );
|
||||
|
||||
// create the form object from the given propel Object class instance
|
||||
|
||||
require_once('model/general/UserProfile.php');
|
||||
$userProfile = UserProfilePeer::retrieveByPK(1);
|
||||
$form =& $creator->create( $userProfile );
|
||||
|
||||
//$wikipage = WikipagePeer::retrieveByPK('wiki');
|
||||
//$form =& $creator->create($wikipage);
|
||||
|
||||
// create the needed renderer
|
||||
$renderer =& patForms::createRenderer( "Array" );
|
||||
|
||||
// set the renderer
|
||||
$form->setRenderer( $renderer );
|
||||
|
||||
// use auto-validation
|
||||
$form->setAutoValidate( 'save' );
|
||||
|
||||
// serialize the elements
|
||||
$elements = $form->renderForm();
|
||||
|
||||
|
||||
// ERROR DISPLAY ------------------------------------------------------
|
||||
if ( $form->isSubmitted() )
|
||||
{
|
||||
displayErrors( $form ); // see patExampleGen/customFunctions.php
|
||||
}
|
||||
|
||||
// DISPLAY FORM ------------------------------------------------------
|
||||
displayForm( $form, $elements ); // see patExampleGen/customFunctions.php
|
||||
|
||||
/**
|
||||
* Takes a patForms object, asks it if there are any validation
|
||||
* errors and displays them if need be.
|
||||
*
|
||||
* NOTE: this is just a helper method for our examples collection,
|
||||
* so that you may concentrate on the relevant parts of the examples.
|
||||
* It does in no way represent the way it should be done :)
|
||||
*
|
||||
* @access public
|
||||
* @param object &$form The patForms object to use
|
||||
*/
|
||||
function displayErrors( &$form )
|
||||
{
|
||||
// get the errors from the form object - if there are none,
|
||||
// this returns false so it is easy to check if there are any.
|
||||
$errors = $form->getValidationErrors();
|
||||
|
||||
// if there are any errors, display them.
|
||||
if ( $errors )
|
||||
{
|
||||
echo '<div class="piErrors">';
|
||||
echo ' <div class="piErrorsTitle">Validation failed</div>';
|
||||
echo ' <div class="piErrorsContent">';
|
||||
|
||||
// the errors collection is an associative array with the
|
||||
// field names as keys, so we go through that.
|
||||
foreach ( $errors as $elementName => $elementErrors )
|
||||
{
|
||||
$element =& $form->getElementByName( $elementName );
|
||||
|
||||
// each element can have more than one error - this
|
||||
// is rare, but can happen so this is an indexed array
|
||||
// with one error in each row.
|
||||
foreach ( $elementErrors as $row => $error )
|
||||
{
|
||||
echo ' <div class="piError">';
|
||||
echo ' <b>'.$element->getAttribute( 'label' ).':</b> '.$error['message'].'('.$error['element'].' element error #'.$error['code'].')<br/>';
|
||||
echo ' </div>';
|
||||
}
|
||||
}
|
||||
|
||||
echo ' </div>';
|
||||
echo '</div>';
|
||||
}
|
||||
// no errors, tell the world everything is fine
|
||||
else
|
||||
{
|
||||
|
||||
echo '<div class="piHint">Validation successful.</div>';
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Displays a standard form from the examples collection when the
|
||||
* form is rendered via the array renderer. Does not work for any
|
||||
* other examples.
|
||||
*
|
||||
* NOTE: this is just a helper method for our examples collection,
|
||||
* so that you may concentrate on the relevant parts of the examples.
|
||||
* It does in no way represent the way it should be done :)
|
||||
*
|
||||
* @access public
|
||||
* @param object &$form The current form object
|
||||
* @param array $elements The rendered elements from the
|
||||
* @return
|
||||
* @see
|
||||
*/
|
||||
function displayForm( &$form, $elements )
|
||||
{
|
||||
// output the opening form tag
|
||||
echo $form->serializeStart();
|
||||
|
||||
echo "<table>\n";
|
||||
foreach ( $elements as $element ) {
|
||||
}
|
||||
echo "</table>\n";
|
||||
|
||||
// display all elements
|
||||
foreach ( $elements as $element )
|
||||
{
|
||||
if (!isset($element['description'])) {
|
||||
// would choke a warning on hidden fields
|
||||
// strange enough, we've no $element['type'] for hidden inputs
|
||||
echo $element['element'] . "\n";
|
||||
continue;
|
||||
}
|
||||
|
||||
echo '<div style="margin-bottom:8px;">';
|
||||
echo $element['label']."<br>";
|
||||
echo "<div>".$element["element"]."</div>";
|
||||
echo "<i>".$element["description"]."</i><br>";
|
||||
|
||||
echo '</div>';
|
||||
|
||||
//} else {
|
||||
//echo "<tr><td>".$element['description']."</td><td>".$element['element']."</td></tr>\n";
|
||||
//}
|
||||
}
|
||||
|
||||
// submit button, closing form tag
|
||||
echo '<input type="submit" name="save" value="Save form"/><br><br>';
|
||||
echo $form->serializeEnd();
|
||||
|
||||
|
||||
// form submitted? display all form values
|
||||
if ( $form->isSubmitted() ) {
|
||||
$els =& $form->getElements();
|
||||
$cnt = count( $els );
|
||||
|
||||
echo '<div class="piValues">';
|
||||
echo ' <div class="piValuesTitle">Submitted form values</div>';
|
||||
echo ' <div class="piValuesContent">';
|
||||
echo ' <table cellpadding="2" cellspacing="0" border="0">';
|
||||
|
||||
for ( $i = 0; $i < $cnt; $i++ ) {
|
||||
echo '<tr>';
|
||||
echo ' <td>'.$els[$i]->getAttribute('label').'</td><td> : </td><td>'.$els[$i]->getValue().'</td>';
|
||||
echo '</tr>';
|
||||
}
|
||||
|
||||
echo ' </table>';
|
||||
echo ' </div>';
|
||||
echo '</div>';
|
||||
}
|
||||
}
|
|
@ -1,70 +0,0 @@
|
|||
<?php
|
||||
|
||||
class patForms_Datasource_Propel {
|
||||
|
||||
private $peername;
|
||||
private $label;
|
||||
private $value;
|
||||
|
||||
public function __construct($conf) {
|
||||
|
||||
$this->peername = $conf['peername'];
|
||||
$this->label = $conf['label'];
|
||||
$this->value = $conf['value'];
|
||||
}
|
||||
|
||||
public function getValues() {
|
||||
|
||||
$map = call_user_func(array($this->peername, 'getPhpNameMap'));
|
||||
|
||||
$c = new Criteria();
|
||||
$c->clearSelectColumns();
|
||||
|
||||
foreach (array($this->label, $this->value) as $arr) {
|
||||
foreach ($arr['members'] as $member) {
|
||||
if (is_array($member)) {
|
||||
foreach ($member as $member) {
|
||||
$c->addSelectColumn(constant($this->peername . '::' . $map[$member]));
|
||||
}
|
||||
} else {
|
||||
$c->addSelectColumn(constant($this->peername . '::' . $map[$member]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (isset($this->label['initial']) OR isset($this->value['initial'])) {
|
||||
$label = isset($this->label['initial']) ? $this->label['initial'] : '';
|
||||
$value = isset($this->value['initial']) ? $this->value['initial'] : '';
|
||||
$result[] = array(
|
||||
'value' => $value,
|
||||
'label' => $label
|
||||
);
|
||||
}
|
||||
|
||||
$rs = AuthorPeer::doSelectStmt($c);
|
||||
$rs->setFetchmode(ResultSet::FETCHMODE_ASSOC);
|
||||
while ($rs->next()) {
|
||||
$row = $rs->getRow();
|
||||
foreach (array('label', 'value') as $key) {
|
||||
$arr = $this->$key;
|
||||
$params = array($arr['mask']);
|
||||
foreach ($arr['members'] as $member) {
|
||||
if (is_array($member)) {
|
||||
foreach ($member as $member) {
|
||||
$field_name = strtolower($map[$member]); // TODO is this always true?
|
||||
$params[] = $row[$field_name];
|
||||
}
|
||||
} else {
|
||||
$field_name = strtolower($map[$member]); // TODO is this always true?
|
||||
$params[] = $row[$field_name];
|
||||
}
|
||||
}
|
||||
$$key = call_user_func_array('sprintf', $params);
|
||||
$tmp[$key] = $$key;
|
||||
}
|
||||
$result[] = $tmp;
|
||||
}
|
||||
|
||||
return $result;
|
||||
}
|
||||
}
|
|
@ -1,122 +0,0 @@
|
|||
<?
|
||||
|
||||
class patForms_Definition {
|
||||
|
||||
private $data = array();
|
||||
|
||||
public function __construct($name, $autoValidate = '') {
|
||||
|
||||
$this->data['name'] = $name;
|
||||
$this->data['mtime'] = time();
|
||||
if ($autoValidate) {
|
||||
$this->data['autoValidate'] = $autoValidate;
|
||||
}
|
||||
}
|
||||
|
||||
static public function create($conf) {
|
||||
// TODO
|
||||
}
|
||||
|
||||
public function __get($name) {
|
||||
|
||||
if (isset($this->data[$name])) {
|
||||
return $this->data[$name];
|
||||
}
|
||||
}
|
||||
|
||||
// TODO change protocol to addElement(array $element)
|
||||
public function addElement($name, $type, $attributes = array(), $rules = array()) {
|
||||
|
||||
if (is_array($type)) {
|
||||
extract($type);
|
||||
}
|
||||
|
||||
$this->data['elements'][$name]['name'] = $name;
|
||||
$this->data['elements'][$name]['type'] = $type;
|
||||
|
||||
foreach ($attributes as $key => $value) {
|
||||
$value = $this->cast($value);
|
||||
$this->data['elements'][$name]['attributes'][$key] = $value;
|
||||
}
|
||||
foreach ($rules as $key => $rule) {
|
||||
$this->data['elements'][$name]['rules'][$key] = $rule;
|
||||
}
|
||||
}
|
||||
|
||||
public function load($filename) {
|
||||
|
||||
$data = $this->read($filename);
|
||||
|
||||
foreach ($data as $key => $value) {
|
||||
if ($key == 'elements') {
|
||||
foreach ($value as $name => $element) {
|
||||
$this->addElement($name, $element);
|
||||
}
|
||||
} else {
|
||||
$this->data[$key] = $this->cast($value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public function save($filename) {
|
||||
|
||||
$this->write($filename, $this->data);
|
||||
}
|
||||
|
||||
protected function read($filename) {
|
||||
|
||||
$xml = file_get_contents($filename);
|
||||
$unserializer = new XML_Unserializer();
|
||||
$unserializer->unserialize($xml);
|
||||
return $unserializer->getUnserializedData();
|
||||
}
|
||||
|
||||
protected function write($filename, $data) {
|
||||
|
||||
$serializer = new XML_Serializer(array (
|
||||
'addDecl' => true,
|
||||
'encoding' => 'ISO-8859-1',
|
||||
'indent' => ' ',
|
||||
'rootName' => 'form',
|
||||
'defaultTagName' => 'tag'
|
||||
));
|
||||
$serializer->serialize($data);
|
||||
$xml = $serializer->getSerializedData();
|
||||
|
||||
$fp = fopen($filename, 'w+');
|
||||
fputs($fp, $xml);
|
||||
fclose($fp);
|
||||
}
|
||||
|
||||
protected function cast($value) {
|
||||
|
||||
return $value;
|
||||
|
||||
// seems as if patForms_Element(s) are broken here
|
||||
// e.g. in patForms_Element_Text::serializeHtmlDefault()
|
||||
// at line 245 if ( $this->attributes['display'] == 'no' )
|
||||
// will result to true if the display attribute is set
|
||||
// to (php boolean) true
|
||||
// so casting the 'true'/'false' and 'yes'/'no' values
|
||||
// would break intended behaviour here
|
||||
|
||||
if (is_array($value) OR is_bool($value)) {
|
||||
return $value;
|
||||
}
|
||||
if ($value === 'true') {
|
||||
return true;
|
||||
}
|
||||
if ($value === 'false') {
|
||||
return false;
|
||||
}
|
||||
if (preg_match('/^[+-]?[0-9]+$/', $value)) {
|
||||
settype($value, 'int');
|
||||
return $value;
|
||||
}
|
||||
if (preg_match('/^[+-]?[0-9]*\.[0-9]+$/', $value)) {
|
||||
settype($value, 'double');
|
||||
return $value;
|
||||
}
|
||||
return $value;
|
||||
}
|
||||
}
|
|
@ -1,165 +0,0 @@
|
|||
<?
|
||||
|
||||
class patForms_Definition_Propel extends patForms_Definition {
|
||||
|
||||
private static $creoleTypeMap = array(
|
||||
CreoleTypes::BOOLEAN => 'Switch', // BOOLEAN = 1;
|
||||
CreoleTypes::BIGINT => 'String', // BIGINT = 2;
|
||||
CreoleTypes::SMALLINT => 'String', // SMALLINT = 3;
|
||||
CreoleTypes::TINYINT => 'String', // TINYINT = 4;
|
||||
CreoleTypes::INTEGER => 'String', // INTEGER = 5;
|
||||
CreoleTypes::CHAR => 'String', // CHAR = 6;
|
||||
CreoleTypes::VARCHAR => 'String', // VARCHAR = 7;
|
||||
CreoleTypes::FLOAT => 'String', // FLOAT = 8;
|
||||
CreoleTypes::DOUBLE => 'String', // DOUBLE = 9;
|
||||
CreoleTypes::DATE => 'String', // DATE = 10;
|
||||
CreoleTypes::TIME => 'String', // TIME = 11;
|
||||
CreoleTypes::TIMESTAMP => 'Date', // TIMESTAMP = 12;
|
||||
CreoleTypes::VARBINARY => 'String', // VARBINARY = 13;
|
||||
CreoleTypes::NUMERIC => 'String', // NUMERIC = 14;
|
||||
CreoleTypes::BLOB => 'Text', // BLOB = 15;
|
||||
CreoleTypes::CLOB => 'Text', // CLOB = 16;
|
||||
CreoleTypes::TEXT => 'Text', // TEXT = 17;
|
||||
CreoleTypes::LONGVARCHAR => 'Text', // LONGVARCHAR = 17;
|
||||
CreoleTypes::DECIMAL => 'String', // DECIMAL = 18;
|
||||
CreoleTypes::REAL => 'String', // REAL = 19;
|
||||
CreoleTypes::BINARY => 'String', // BINARY = 20;
|
||||
CreoleTypes::LONGVARBINARY => 'Text', // LONGVARBINARY = 21;
|
||||
CreoleTypes::YEAR => 'String', // YEAR = 22;
|
||||
CreoleTypes::ARR => 'String',
|
||||
CreoleTypes::OTHER => 'String'
|
||||
);
|
||||
|
||||
private static $validatorTypeMap = array(
|
||||
'unique' => null,
|
||||
'minLength' => 'patForms_Rule_MinLength',
|
||||
'maxLength' => 'patForms_Rule_MaxLength',
|
||||
'minValue' => 'patForms_Rule_MinValue',
|
||||
'maxValue' => 'patForms_Rule_MaxValue',
|
||||
'match' => 'patForms_Rule_Match',
|
||||
'notMatch' => 'patForms_Rule_NotMatch',
|
||||
'required' => null, // will be done by the elements "required" attribute
|
||||
'validValues' => 'patForms_Rule_ValidValues',
|
||||
);
|
||||
|
||||
/**
|
||||
* @param array $conf an assoc array of parameters. these are:
|
||||
* - string name => $name of the propel object class
|
||||
* - string filename => $filename of the form definition xml file
|
||||
*/
|
||||
|
||||
static public function create($conf) {
|
||||
|
||||
extract($conf);
|
||||
|
||||
$autoValidate = isset($autoValidate) ? $autoValidate : 'save';
|
||||
|
||||
$definition = new patForms_Definition_Propel($name, $autoValidate);
|
||||
|
||||
if (0 AND file_exists($filename)) {
|
||||
// load definition from xml file
|
||||
$definition->load($filename);
|
||||
} else {
|
||||
// populate definition from table map and save it to xml file
|
||||
$definition = self::populateFromTableMap($definition, $conf);
|
||||
$definition->save($filename);
|
||||
}
|
||||
|
||||
return $definition;
|
||||
}
|
||||
|
||||
private function populateFromTableMap($definition, $conf) {
|
||||
|
||||
extract($conf);
|
||||
|
||||
$mapBuilder = call_user_func(array($name . 'Peer', 'getMapBuilder'));
|
||||
$tablename = constant($name . 'Peer::TABLE_NAME');
|
||||
$tableMap = $mapBuilder->getDatabaseMap()->getTable($tablename);
|
||||
$cols = $tableMap->getColumns();
|
||||
|
||||
foreach ($cols as $col) {
|
||||
|
||||
$phpname = $col->getPhpName();
|
||||
// this would need a patched version of patForms in order
|
||||
// to retrieve request vars after having submitted the form
|
||||
// TODO - ask patForms developers to enable this
|
||||
// $elementName = $tablename . '[' . $phpname . ']';
|
||||
$elementName = $phpname;
|
||||
|
||||
$elementType = self::$creoleTypeMap[$col->getCreoleType()];
|
||||
|
||||
// TODO somehow retrieve element type specific default values?
|
||||
$elementAttributes = array(
|
||||
'name' => $elementName,
|
||||
'title' => $phpname,
|
||||
'label' => $phpname,
|
||||
'description' => $phpname,
|
||||
'edit' => 'yes',
|
||||
'display' => $col->isPrimaryKey() ? 'no' : 'yes',
|
||||
// Is the element required?
|
||||
// TODO Can we retrieve this info from the Column object?
|
||||
'required' => true,
|
||||
);
|
||||
|
||||
switch ($col->getCreoleType()) {
|
||||
case CreoleTypes::BOOLEAN: {
|
||||
$elementAttributes['value'] = 1;
|
||||
break;
|
||||
}
|
||||
case CreoleTypes::DATE: {
|
||||
// TODO doesn't seem to work for some reason
|
||||
// $elementAttributes['format'] = 'date';
|
||||
// $elementAttributes['dateformat'] = 'Ymd';
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if ($col->isForeignKey()) {
|
||||
|
||||
$relColname = $col->getRelatedColumnName();
|
||||
$relTablename = $col->getRelatedTableName();
|
||||
$relColPhpname =
|
||||
Propel::getDatabaseMap(constant($relTablename . 'Peer::DATABASE_NAME'))->
|
||||
getTable($relTablename)->getColumn($relColname)->getPhpname();
|
||||
|
||||
$elementAttributes['datasource'] = array (
|
||||
'name' => 'patForms_Datasource_Propel',
|
||||
'peername' => $relTablename . 'Peer',
|
||||
'label' => array(
|
||||
'initial' => 'Please select one ...',
|
||||
'members' => array($relColPhpname),
|
||||
'mask' => '%s',
|
||||
),
|
||||
'value' => array(
|
||||
'members' => array($relColPhpname),
|
||||
'mask' => '%s',
|
||||
),
|
||||
);
|
||||
$elementType = 'Enum';
|
||||
}
|
||||
|
||||
$rules = array();
|
||||
if ($col->hasValidators()) {
|
||||
foreach ($col->getValidators() as $validator) {
|
||||
$name = $validator->getName();
|
||||
$type = self::$validatorTypeMap[$name];
|
||||
if (!is_null($type)) {
|
||||
$rules[$name] = array (
|
||||
'table' => $col->getTablename(),
|
||||
'col' => $col->getColumnName(),
|
||||
'name' => $name,
|
||||
'type' => self::$validatorTypeMap[$name],
|
||||
'value' => $validator->getValue(),
|
||||
'class' => $validator->getClass(),
|
||||
'message' => $validator->getMessage(),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$definition->addElement($phpname, $elementType, $elementAttributes, $rules);
|
||||
}
|
||||
|
||||
return $definition;
|
||||
}
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -1,340 +0,0 @@
|
|||
<?php
|
||||
/**
|
||||
* patForms rule base class
|
||||
*
|
||||
* $Id: Rule.php 1347 2009-12-03 21:06:36Z francois $
|
||||
*
|
||||
* @access protected
|
||||
* @package patForms
|
||||
* @subpackage Rules
|
||||
*/
|
||||
|
||||
/**
|
||||
* patForms rule base class
|
||||
*
|
||||
* @access protected
|
||||
* @package patForms
|
||||
* @subpackage Rules
|
||||
* @author Stephan Schmidt <schst@php-tools.net>
|
||||
* @license LGPL, see license.txt for details
|
||||
* @link http://www.php-tools.net
|
||||
* @todo implement javascript helper methods (set a javascript property plus an
|
||||
* array of keys that will be replaced by the properties of the rule)
|
||||
*/
|
||||
class patForms_Rule
|
||||
{
|
||||
/**
|
||||
* time when the rule should be applied
|
||||
*
|
||||
* Possible values are:
|
||||
* -PATFORMS_RULE_BEFORE_VALIDATION
|
||||
* -PATFORMS_RULE_AFTER_VALIDATION
|
||||
* -PATFORMS_RULE_BOTH
|
||||
*
|
||||
* @access private
|
||||
* @var integer
|
||||
*/
|
||||
var $_time = PATFORMS_RULE_AFTER_VALIDATION;
|
||||
|
||||
/**
|
||||
* script that will be displayed only once
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $globalScript = array();
|
||||
|
||||
/**
|
||||
* script that will be displayed once per instance
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $instanceScript = array();
|
||||
|
||||
/**
|
||||
* properties that have to be replaced in the instance script.
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $scriptPlaceholders = array();
|
||||
|
||||
/**
|
||||
* store the container of the rule
|
||||
*
|
||||
* @access private
|
||||
* @var object
|
||||
*/
|
||||
var $container;
|
||||
|
||||
/**
|
||||
* define error codes an messages for each form element
|
||||
*
|
||||
* @abstract
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $validatorErrorCodes = array();
|
||||
|
||||
/**
|
||||
* error code offset for the rule
|
||||
*
|
||||
* @abstract
|
||||
* @access private
|
||||
*/
|
||||
var $errorOffset;
|
||||
|
||||
/**
|
||||
* format of the rule
|
||||
*
|
||||
* @abstract
|
||||
* @access private
|
||||
*/
|
||||
var $format = 'html';
|
||||
|
||||
/**
|
||||
* name of the rule
|
||||
*
|
||||
* @abstract
|
||||
* @access private
|
||||
*/
|
||||
var $ruleName = '';
|
||||
|
||||
/**
|
||||
* Get the time when the rule should be applied.
|
||||
*
|
||||
* This has to be defined in the _time property of the rule.
|
||||
*
|
||||
* @access public
|
||||
* @return integer
|
||||
*/
|
||||
function getTime()
|
||||
{
|
||||
return $this->_time;
|
||||
}
|
||||
|
||||
/**
|
||||
* create a new rule object
|
||||
*
|
||||
* @access public
|
||||
* @param string id
|
||||
*/
|
||||
function patForms_Rule( $id = null )
|
||||
{
|
||||
if ( $id === null )
|
||||
{
|
||||
$id = uniqid( '' );
|
||||
}
|
||||
|
||||
$this->_id = $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* set the id for the rule
|
||||
*
|
||||
* @access public
|
||||
* @param string id
|
||||
*/
|
||||
function setId( $id )
|
||||
{
|
||||
$this->_id = $id;
|
||||
}
|
||||
|
||||
/**
|
||||
* set the locale, this is needed to update the rule
|
||||
* translations, that have been passed to the container
|
||||
* element
|
||||
*
|
||||
* @access public
|
||||
* @param string new locale
|
||||
* @return boolean
|
||||
*/
|
||||
function setLocale( $locale )
|
||||
{
|
||||
// rules do not store locale information
|
||||
if (!patForms::isCustomLocale($locale)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$errorMessages = patForms::getCustomLocale($locale, 'Rule::' . $this->getRuleName());
|
||||
|
||||
if (is_array($errorMessages)) {
|
||||
$this->validatorErrorCodes[$locale] = $errorMessages;
|
||||
}
|
||||
|
||||
$this->container->addValidatorErrorCodes( $this->validatorErrorCodes, $this->errorOffset );
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* prepare the rule
|
||||
*
|
||||
* This method is used to initialize the rule.
|
||||
* By default it adds it validatorErrorCodes
|
||||
* to the container and stores a reference to the
|
||||
* container.
|
||||
*
|
||||
* You may extend it in your custom rules, but should always be calling
|
||||
* this method using:
|
||||
*
|
||||
* <code>
|
||||
* patForms_Rule::prepareRule( $container );
|
||||
* </code>
|
||||
*
|
||||
* @access public
|
||||
* @param object Either a patForms or patForms_Element object
|
||||
*/
|
||||
function prepareRule( &$container )
|
||||
{
|
||||
$this->format = $container->getFormat();
|
||||
|
||||
$this->container = &$container;
|
||||
$this->errorOffset = $container->getErrorOffset();
|
||||
|
||||
$container->addValidatorErrorCodes( $this->validatorErrorCodes, $this->errorOffset );
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* method called by patForms or any patForms_Element to validate the
|
||||
* element or the form.
|
||||
*
|
||||
* @abstract
|
||||
* @access public
|
||||
* @param object Either a patForms or patForms_Element object
|
||||
* @return boolean true, if rule has been applied succesfully, false otherwise
|
||||
*/
|
||||
function applyRule( &$container, $type = PATFORMS_RULE_BEFORE_VALIDATION )
|
||||
{
|
||||
// your code
|
||||
}
|
||||
|
||||
/**
|
||||
* addValidationError
|
||||
*
|
||||
* @access private
|
||||
* @param integer $code
|
||||
* @param array $vars fill named placeholder with values
|
||||
* @return boolean $result true on success
|
||||
*/
|
||||
function addValidationError( $code, $vars = array() )
|
||||
{
|
||||
$code= $this->errorOffset + $code;
|
||||
return $this->container->addValidationError( $code, $vars );
|
||||
}
|
||||
|
||||
/**
|
||||
* get the name of the rule
|
||||
*
|
||||
* By default just return the classname, this is sufficient.
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
function getRuleName()
|
||||
{
|
||||
if (!empty($this->ruleName)) {
|
||||
return $this->ruleName;
|
||||
}
|
||||
return get_class( $this );
|
||||
}
|
||||
|
||||
/**
|
||||
* get the global javascript of the rule
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
* @todo Rules need to know the output format
|
||||
*/
|
||||
/*
|
||||
function getGlobalJavascript()
|
||||
{
|
||||
if ( isset( $this->globalScript['html'] ) )
|
||||
{
|
||||
return $this->globalScript['html'];
|
||||
}
|
||||
return '';
|
||||
}
|
||||
*/
|
||||
|
||||
/**
|
||||
* get the instance javascript of the rule
|
||||
*
|
||||
* @access public
|
||||
* @return string
|
||||
*/
|
||||
/*
|
||||
function getInstanceJavascript()
|
||||
{
|
||||
if ( !isset( $this->instanceScript[$this->format] ) )
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// get the script for the current format
|
||||
$script = $this->instanceScript[$this->format];
|
||||
|
||||
// always replace the id
|
||||
$script = str_replace( '[RULE::ID]', $this->_id, $script );
|
||||
if ( method_exists( $this->container, 'getId' ) )
|
||||
{
|
||||
$script = str_replace( '[CONTAINER::ID]', $this->container->getId(), $script );
|
||||
}
|
||||
if ( method_exists( $this->container, 'getName' ) )
|
||||
{
|
||||
$script = str_replace( '[CONTAINER::NAME]', $this->container->getName(), $script );
|
||||
}
|
||||
|
||||
foreach ( $this->scriptPlaceholders as $placeholder => $property )
|
||||
{
|
||||
if ( isset( $this->$property ) )
|
||||
$script = str_replace( '['.$placeholder.']', $this->$property, $script );
|
||||
else
|
||||
$script = str_replace( '['.$placeholder.']', '', $script );
|
||||
}
|
||||
return $script;
|
||||
}
|
||||
*/
|
||||
|
||||
function registerJavascripts(&$form) {
|
||||
|
||||
if ($script = $this->getGlobalJavascript()) {
|
||||
$form->registerGlobalJavascript($this->getRuleName(), $script);
|
||||
}
|
||||
|
||||
if ($script = $this->getInstanceJavascript()) {
|
||||
$form->registerInstanceJavascript($script);
|
||||
}
|
||||
}
|
||||
|
||||
function getGlobalJavascript() {
|
||||
|
||||
if (isset($this->globalScript[$this->format])) {
|
||||
return $this->globalScript[$this->format];
|
||||
}
|
||||
}
|
||||
|
||||
function getInstanceJavascript(){
|
||||
|
||||
if (isset($this->instanceScript[$this->format])) {
|
||||
$script = $this->instanceScript[$this->format];
|
||||
$script = str_replace('[RULE::ID]', $this->_id, $script);
|
||||
if (method_exists($this->container, 'getId')) {
|
||||
$script = str_replace('[CONTAINER::ID]', $this->container->getId(), $script);
|
||||
}
|
||||
if (method_exists($this->container, 'getName')) {
|
||||
$script = str_replace('[CONTAINER::NAME]', $this->container->getName(), $script);
|
||||
}
|
||||
foreach ($this->scriptPlaceholders as $placeholder => $property) {
|
||||
if (isset($this->$property)) {
|
||||
$script = str_replace('['.$placeholder.']', $this->$property, $script);
|
||||
} else {
|
||||
$script = str_replace('['.$placeholder.']', '', $script);
|
||||
}
|
||||
}
|
||||
return $script;
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,163 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* patForms Rule Match
|
||||
*
|
||||
* This rule matches the field value against a regEx pattern. It successfully
|
||||
* validates the passed value if the value *does* match the pattern.
|
||||
*
|
||||
* @package patForms
|
||||
* @subpackage Rules
|
||||
* @author Sven Fuchs <svenfuchs@artweb-design.de>
|
||||
* @license LGPL, see license.txt for details
|
||||
* @link http://www.php-tools.net
|
||||
*/
|
||||
class patForms_Rule_Match extends patForms_Rule
|
||||
{
|
||||
/**
|
||||
* script that will be displayed only once
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
|
||||
var $globalScript = array(
|
||||
'html' => "/* patForms::Rule::Match */
|
||||
|
||||
function pFRC_Match(field) {
|
||||
this.field = eval('pfe_' + field);
|
||||
}
|
||||
|
||||
pFRC_Match.prototype.validate = function() {
|
||||
value = this.field.getValue();
|
||||
if (!value.match(this.pattern)) {
|
||||
alert('This is an invalid value.');
|
||||
}
|
||||
}
|
||||
|
||||
pFRC_Match.prototype.setValue = function(pattern) {
|
||||
this.pattern = pattern;
|
||||
}
|
||||
|
||||
/* END: patForms::Rule::Match */
|
||||
"
|
||||
);
|
||||
|
||||
/**
|
||||
* javascript that will be displayed once per instance
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $instanceScript = array(
|
||||
'html' => "var pfr_[RULE::ID] = new pFRC_Match('[CONTAINER::NAME]');\n"
|
||||
);
|
||||
|
||||
/**
|
||||
* properties that have to be replaced in the instance script.
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $scriptPlaceholders = array(
|
||||
'RULE::SOURCE' => '_source',
|
||||
);
|
||||
|
||||
/**
|
||||
* name of the rule
|
||||
*
|
||||
* @abstract
|
||||
* @access private
|
||||
*/
|
||||
var $ruleName = 'Match';
|
||||
|
||||
/**
|
||||
* define error codes and messages for the rule
|
||||
*
|
||||
* @access private
|
||||
* @var array $validatorErrorCodes
|
||||
* @todo translate error messages
|
||||
*/
|
||||
var $validatorErrorCodes = array(
|
||||
"C" => array(
|
||||
1 => "This is an invalid value.",
|
||||
),
|
||||
"de" => array(
|
||||
1 => "Dies ist ein ungültiger Wert.",
|
||||
),
|
||||
"fr" => array(
|
||||
1 => "This is an invalid value.",
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* the regEx pattern
|
||||
* @access private
|
||||
* @var string
|
||||
*/
|
||||
var $_pattern;
|
||||
|
||||
/**
|
||||
* field id that is used
|
||||
* @access private
|
||||
* @var string
|
||||
*/
|
||||
var $_field;
|
||||
|
||||
private $value = 10;
|
||||
|
||||
public function __construct($params) {
|
||||
|
||||
parent::__construct();
|
||||
|
||||
extract($params);
|
||||
$this->_pattern = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* prepare the rule
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms
|
||||
*/
|
||||
function prepareRule(&$container) {
|
||||
|
||||
patForms_Rule::prepareRule($container);
|
||||
|
||||
$onChange = $container->getAttribute('onchange');
|
||||
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
|
||||
$container->setAttribute('onchange', $newHandler . $onChange);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* method called by patForms or any patForms_Element to validate the
|
||||
* element or the form.
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms form object
|
||||
*/
|
||||
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
|
||||
|
||||
if (preg_match($this->_pattern, $element->getValue()) != 0){
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->addValidationError(1);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
function registerJavascripts(&$form) {
|
||||
|
||||
parent::registerJavascripts($form);
|
||||
|
||||
$script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->_pattern);
|
||||
$form->registerInstanceJavascript($script);
|
||||
}
|
||||
}
|
|
@ -1,161 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* patForms Rule MaxLength
|
||||
*
|
||||
* This is just a simple rule, that checks for a required minimum length of a field
|
||||
*
|
||||
* @package patForms
|
||||
* @subpackage Rules
|
||||
* @author Sven Fuchs <svenfuchs@artweb-design.de>
|
||||
* @license LGPL, see license.txt for details
|
||||
* @link http://www.php-tools.net
|
||||
*/
|
||||
class patForms_Rule_MaxLength extends patForms_Rule
|
||||
{
|
||||
/**
|
||||
* script that will be displayed only once
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $globalScript = array(
|
||||
'html' => "/* patForms::Rule::MaxLength */
|
||||
|
||||
function pFRC_MaxLength(field) {
|
||||
this.field = eval('pfe_' + field);
|
||||
}
|
||||
|
||||
pFRC_MaxLength.prototype.validate = function() {
|
||||
value = this.field.getValue();
|
||||
if (value.length > this.value) {
|
||||
alert('Please enter a value that is max. ' + this.value + ' characters long.');
|
||||
}
|
||||
}
|
||||
|
||||
pFRC_MaxLength.prototype.setValue = function(value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/* END: patForms::Rule::MaxLength */
|
||||
"
|
||||
);
|
||||
|
||||
/**
|
||||
* javascript that will be displayed once per instance
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $instanceScript = array(
|
||||
'html' => "var pfr_[RULE::ID] = new pFRC_MaxLength('[CONTAINER::NAME]');\n"
|
||||
);
|
||||
|
||||
/**
|
||||
* properties that have to be replaced in the instance script.
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $scriptPlaceholders = array(
|
||||
'RULE::SOURCE' => '_source',
|
||||
);
|
||||
|
||||
/**
|
||||
* name of the rule
|
||||
*
|
||||
* @abstract
|
||||
* @access private
|
||||
*/
|
||||
var $ruleName = 'MaxLength';
|
||||
|
||||
/**
|
||||
* define error codes and messages for the rule
|
||||
*
|
||||
* @access private
|
||||
* @var array $validatorErrorCodes
|
||||
* @todo translate error messages
|
||||
*/
|
||||
var $validatorErrorCodes = array(
|
||||
"C" => array(
|
||||
1 => "Please enter a value that is max. [VALUE] characters long.",
|
||||
),
|
||||
"de" => array(
|
||||
1 => "Bitte geben Sie einen max. [VALUE] Zeichen langen Wert ein.",
|
||||
),
|
||||
"fr" => array(
|
||||
1 => "Please enter a value that is max. [VALUE] characters long.",
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* possible values
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $_values;
|
||||
|
||||
/**
|
||||
* field id that is used
|
||||
* @access private
|
||||
* @var string
|
||||
*/
|
||||
var $_field;
|
||||
|
||||
private $value = 10;
|
||||
|
||||
public function __construct($params) {
|
||||
|
||||
parent::__construct();
|
||||
|
||||
extract($params);
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* prepare the rule
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms
|
||||
*/
|
||||
function prepareRule(&$container) {
|
||||
|
||||
patForms_Rule::prepareRule($container);
|
||||
|
||||
$onChange = $container->getAttribute('onchange');
|
||||
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
|
||||
$container->setAttribute('onchange', $newHandler . $onChange);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* method called by patForms or any patForms_Element to validate the
|
||||
* element or the form.
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms form object
|
||||
*/
|
||||
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
|
||||
|
||||
if (strlen($element->getValue()) <= $this->value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->addValidationError(1, array('value' => $this->value));
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
function registerJavascripts(&$form) {
|
||||
|
||||
parent::registerJavascripts($form);
|
||||
|
||||
$script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->value);
|
||||
$form->registerInstanceJavascript($script);
|
||||
}
|
||||
}
|
|
@ -1,163 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* patForms Rule MaxValue
|
||||
*
|
||||
* This rule simply checks for a required maximum value (number) of a field
|
||||
*
|
||||
* @package patForms
|
||||
* @subpackage Rules
|
||||
* @author Sven Fuchs <svenfuchs@artweb-design.de>
|
||||
* @license LGPL, see license.txt for details
|
||||
* @link http://www.php-tools.net
|
||||
*/
|
||||
class patForms_Rule_MaxValue extends patForms_Rule
|
||||
{
|
||||
/**
|
||||
* script that will be displayed only once
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
|
||||
var $globalScript = array(
|
||||
'html' => "/* patForms::Rule::MaxValue */
|
||||
|
||||
function pFRC_MaxValue(field) {
|
||||
this.field = eval('pfe_' + field);
|
||||
}
|
||||
|
||||
pFRC_MaxValue.prototype.validate = function() {
|
||||
value = this.field.getValue();
|
||||
if (parseInt(value) != value) {
|
||||
alert('Please enter a number that is less or equal to ' + this.value);
|
||||
}
|
||||
if (parseInt(value) > this.value) {
|
||||
alert('Please enter a number that is less or equal to ' + this.value);
|
||||
}
|
||||
}
|
||||
|
||||
pFRC_MaxValue.prototype.setMaxValue = function(value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/* END: patForms::Rule::MaxValue */
|
||||
"
|
||||
);
|
||||
|
||||
/**
|
||||
* javascript that will be displayed once per instance
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $instanceScript = array(
|
||||
'html' => "var pfr_[RULE::ID] = new pFRC_MaxValue('[CONTAINER::NAME]');\n"
|
||||
);
|
||||
|
||||
/**
|
||||
* properties that have to be replaced in the instance script.
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $scriptPlaceholders = array(
|
||||
'RULE::SOURCE' => '_source',
|
||||
);
|
||||
|
||||
/**
|
||||
* name of the rule
|
||||
*
|
||||
* @abstract
|
||||
* @access private
|
||||
*/
|
||||
var $ruleName = 'MaxValue';
|
||||
|
||||
/**
|
||||
* define error codes and messages for the rule
|
||||
*
|
||||
* @access private
|
||||
* @var array $validatorErrorCodes
|
||||
* @todo translate error messages
|
||||
*/
|
||||
var $validatorErrorCodes = array(
|
||||
"C" => array(
|
||||
1 => "Please enter a number that is less or equal to [VALUE].",
|
||||
),
|
||||
"de" => array(
|
||||
1 => "Bitte geben Sie eine Zahl kleiner oder gleich [VALUE] ein.",
|
||||
),
|
||||
"fr" => array(
|
||||
1 => "Please enter a number that is less or equal to [VALUE].",
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* the regEx pattern
|
||||
* @access private
|
||||
* @var string
|
||||
*/
|
||||
var $_value;
|
||||
|
||||
/**
|
||||
* field id that is used
|
||||
* @access private
|
||||
* @var string
|
||||
*/
|
||||
var $_field;
|
||||
|
||||
public function __construct($params) {
|
||||
|
||||
parent::__construct();
|
||||
|
||||
extract($params);
|
||||
$this->_value = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* prepare the rule
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms
|
||||
*/
|
||||
function prepareRule(&$container) {
|
||||
|
||||
patForms_Rule::prepareRule($container);
|
||||
|
||||
$onChange = $container->getAttribute('onchange');
|
||||
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
|
||||
$container->setAttribute('onchange', $newHandler . $onChange);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* method called by patForms or any patForms_Element to validate the
|
||||
* element or the form.
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms form object
|
||||
*/
|
||||
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
|
||||
|
||||
if (intval($element->getValue()) <= intval($this->_value)){
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->addValidationError(1, array('value' => $this->_value));
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
function registerJavascripts(&$form) {
|
||||
|
||||
parent::registerJavascripts($form);
|
||||
|
||||
$script = sprintf("pfr_%s.setMaxValue(%s);\n", $this->_id, $this->_value);
|
||||
$form->registerInstanceJavascript($script);
|
||||
}
|
||||
}
|
|
@ -1,161 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* patForms Rule MinLength
|
||||
*
|
||||
* This is just a simple rule, that checks for a required minimum length of a field
|
||||
*
|
||||
* @package patForms
|
||||
* @subpackage Rules
|
||||
* @author Sven Fuchs <svenfuchs@artweb-design.de>
|
||||
* @license LGPL, see license.txt for details
|
||||
* @link http://www.php-tools.net
|
||||
*/
|
||||
class patForms_Rule_MinLength extends patForms_Rule
|
||||
{
|
||||
/**
|
||||
* script that will be displayed only once
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $globalScript = array(
|
||||
'html' => "/* patForms::Rule::MinLength */
|
||||
|
||||
function pFRC_MinLength(field) {
|
||||
this.field = eval('pfe_' + field);
|
||||
}
|
||||
|
||||
pFRC_MinLength.prototype.validate = function() {
|
||||
value = this.field.getValue();
|
||||
if (value.length < this.value) {
|
||||
alert('Please enter a value that is at least ' + this.value + ' characters long.');
|
||||
}
|
||||
}
|
||||
|
||||
pFRC_MinLength.prototype.setValue = function(value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/* END: patForms::Rule::MinLength */
|
||||
"
|
||||
);
|
||||
|
||||
/**
|
||||
* javascript that will be displayed once per instance
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $instanceScript = array(
|
||||
'html' => "var pfr_[RULE::ID] = new pFRC_MinLength('[CONTAINER::NAME]');\n"
|
||||
);
|
||||
|
||||
/**
|
||||
* properties that have to be replaced in the instance script.
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $scriptPlaceholders = array(
|
||||
'RULE::SOURCE' => '_source',
|
||||
);
|
||||
|
||||
/**
|
||||
* name of the rule
|
||||
*
|
||||
* @abstract
|
||||
* @access private
|
||||
*/
|
||||
var $ruleName = 'MinLength';
|
||||
|
||||
/**
|
||||
* define error codes and messages for the rule
|
||||
*
|
||||
* @access private
|
||||
* @var array $validatorErrorCodes
|
||||
* @todo translate error messages
|
||||
*/
|
||||
var $validatorErrorCodes = array(
|
||||
"C" => array(
|
||||
1 => "Please enter a value that is at least [VALUE] characters long.",
|
||||
),
|
||||
"de" => array(
|
||||
1 => "Bitte geben Sie einen mindestens [VALUE] Zeichen langen Wert ein.",
|
||||
),
|
||||
"fr" => array(
|
||||
1 => "Please enter a value that is at least [VALUE] characters long.",
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* possible values
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $_values;
|
||||
|
||||
/**
|
||||
* field id that is used
|
||||
* @access private
|
||||
* @var string
|
||||
*/
|
||||
var $_field;
|
||||
|
||||
private $value = 10;
|
||||
|
||||
public function __construct($params) {
|
||||
|
||||
parent::__construct();
|
||||
|
||||
extract($params);
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* prepare the rule
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms
|
||||
*/
|
||||
function prepareRule(&$container) {
|
||||
|
||||
patForms_Rule::prepareRule($container);
|
||||
|
||||
$onChange = $container->getAttribute('onchange');
|
||||
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
|
||||
$container->setAttribute('onchange', $newHandler . $onChange);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* method called by patForms or any patForms_Element to validate the
|
||||
* element or the form.
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms form object
|
||||
*/
|
||||
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
|
||||
|
||||
if (strlen($element->getValue()) >= $this->value) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->addValidationError(1, array('value' => $this->value));
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
function registerJavascripts(&$form) {
|
||||
|
||||
parent::registerJavascripts($form);
|
||||
|
||||
$script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->value);
|
||||
$form->registerInstanceJavascript($script);
|
||||
}
|
||||
}
|
|
@ -1,165 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* patForms Rule MinValue
|
||||
*
|
||||
* This rule simply checks for a required minimum value (number) of a field
|
||||
*
|
||||
* @package patForms
|
||||
* @subpackage Rules
|
||||
* @author Sven Fuchs <svenfuchs@artweb-design.de>
|
||||
* @license LGPL, see license.txt for details
|
||||
* @link http://www.php-tools.net
|
||||
*/
|
||||
class patForms_Rule_MinValue extends patForms_Rule
|
||||
{
|
||||
/**
|
||||
* script that will be displayed only once
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
|
||||
var $globalScript = array(
|
||||
'html' => "/* patForms::Rule::MinValue */
|
||||
|
||||
function pFRC_MinValue(field) {
|
||||
this.field = eval('pfe_' + field);
|
||||
}
|
||||
|
||||
pFRC_MinValue.prototype.validate = function() {
|
||||
value = this.field.getValue();
|
||||
if (parseInt(value) != value) {
|
||||
alert('Please enter a number that is greater or equal to ' + this.value);
|
||||
}
|
||||
if (parseInt(value) < this.value) {
|
||||
alert('Please enter a number that is greater or equal to ' + this.value);
|
||||
}
|
||||
}
|
||||
|
||||
pFRC_MinValue.prototype.setMinValue = function(value) {
|
||||
this.value = value;
|
||||
}
|
||||
|
||||
/* END: patForms::Rule::MinValue */
|
||||
"
|
||||
);
|
||||
|
||||
/**
|
||||
* javascript that will be displayed once per instance
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $instanceScript = array(
|
||||
'html' => "var pfr_[RULE::ID] = new pFRC_MinValue('[CONTAINER::NAME]');\n"
|
||||
);
|
||||
|
||||
/**
|
||||
* properties that have to be replaced in the instance script.
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $scriptPlaceholders = array(
|
||||
'RULE::SOURCE' => '_source',
|
||||
);
|
||||
|
||||
/**
|
||||
* name of the rule
|
||||
*
|
||||
* @abstract
|
||||
* @access private
|
||||
*/
|
||||
var $ruleName = 'MinValue';
|
||||
|
||||
/**
|
||||
* define error codes and messages for the rule
|
||||
*
|
||||
* @access private
|
||||
* @var array $validatorErrorCodes
|
||||
* @todo translate error messages
|
||||
*/
|
||||
var $validatorErrorCodes = array(
|
||||
"C" => array(
|
||||
1 => "Please enter a number that is greater or equal to [VALUE].",
|
||||
),
|
||||
"de" => array(
|
||||
1 => "Bitte geben Sie eine Zahl größer oder gleich [VALUE] ein.",
|
||||
),
|
||||
"fr" => array(
|
||||
1 => "Please enter a number that is greater or equal to [VALUE].",
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* the regEx pattern
|
||||
* @access private
|
||||
* @var string
|
||||
*/
|
||||
var $_value;
|
||||
|
||||
/**
|
||||
* field id that is used
|
||||
* @access private
|
||||
* @var string
|
||||
*/
|
||||
var $_field;
|
||||
|
||||
private $value = 10;
|
||||
|
||||
public function __construct($params) {
|
||||
|
||||
parent::__construct();
|
||||
|
||||
extract($params);
|
||||
$this->_value = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* prepare the rule
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms
|
||||
*/
|
||||
function prepareRule(&$container) {
|
||||
|
||||
patForms_Rule::prepareRule($container);
|
||||
|
||||
$onChange = $container->getAttribute('onchange');
|
||||
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
|
||||
$container->setAttribute('onchange', $newHandler . $onChange);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* method called by patForms or any patForms_Element to validate the
|
||||
* element or the form.
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms form object
|
||||
*/
|
||||
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
|
||||
|
||||
if (intval($element->getValue()) >= intval($this->_value)){
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->addValidationError(1, array('value' => $this->_value));
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
function registerJavascripts(&$form) {
|
||||
|
||||
parent::registerJavascripts($form);
|
||||
|
||||
$script = sprintf("pfr_%s.setMinValue(%s);\n", $this->_id, $this->_value);
|
||||
$form->registerInstanceJavascript($script);
|
||||
}
|
||||
}
|
|
@ -1,163 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* patForms Rule NotMatch
|
||||
*
|
||||
* This rule matches the field value against a regEx pattern. It successfully
|
||||
* validates the passed value if the value does *not* match the pattern.
|
||||
*
|
||||
* @package patForms
|
||||
* @subpackage Rules
|
||||
* @author Sven Fuchs <svenfuchs@artweb-design.de>
|
||||
* @license LGPL, see license.txt for details
|
||||
* @link http://www.php-tools.net
|
||||
*/
|
||||
class patForms_Rule_NotMatch extends patForms_Rule
|
||||
{
|
||||
/**
|
||||
* script that will be displayed only once
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
|
||||
var $globalScript = array(
|
||||
'html' => "/* patForms::Rule::NotMatch */
|
||||
|
||||
function pFRC_NotMatch(field) {
|
||||
this.field = eval('pfe_' + field);
|
||||
}
|
||||
|
||||
pFRC_NotMatch.prototype.validate = function() {
|
||||
value = this.field.getValue();
|
||||
if (value.match(this.pattern)) {
|
||||
alert('This is an invalid value.');
|
||||
}
|
||||
}
|
||||
|
||||
pFRC_NotMatch.prototype.setValue = function(pattern) {
|
||||
this.pattern = pattern;
|
||||
}
|
||||
|
||||
/* END: patForms::Rule::NotMatch */
|
||||
"
|
||||
);
|
||||
|
||||
/**
|
||||
* javascript that will be displayed once per instance
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $instanceScript = array(
|
||||
'html' => "var pfr_[RULE::ID] = new pFRC_NotMatch('[CONTAINER::NAME]');\n"
|
||||
);
|
||||
|
||||
/**
|
||||
* properties that have to be replaced in the instance script.
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $scriptPlaceholders = array(
|
||||
'RULE::SOURCE' => '_source',
|
||||
);
|
||||
|
||||
/**
|
||||
* name of the rule
|
||||
*
|
||||
* @abstract
|
||||
* @access private
|
||||
*/
|
||||
var $ruleName = 'NotMatch';
|
||||
|
||||
/**
|
||||
* define error codes and messages for the rule
|
||||
*
|
||||
* @access private
|
||||
* @var array $validatorErrorCodes
|
||||
* @todo translate error messages
|
||||
*/
|
||||
var $validatorErrorCodes = array(
|
||||
"C" => array(
|
||||
1 => "This is an invalid value.",
|
||||
),
|
||||
"de" => array(
|
||||
1 => "Dies ist ein ungültiger Wert.",
|
||||
),
|
||||
"fr" => array(
|
||||
1 => "This is an invalid value.",
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* the regEx pattern
|
||||
* @access private
|
||||
* @var string
|
||||
*/
|
||||
var $_pattern;
|
||||
|
||||
/**
|
||||
* field id that is used
|
||||
* @access private
|
||||
* @var string
|
||||
*/
|
||||
var $_field;
|
||||
|
||||
private $value = 10;
|
||||
|
||||
public function __construct($params) {
|
||||
|
||||
parent::__construct();
|
||||
|
||||
extract($params);
|
||||
$this->_pattern = $value;
|
||||
}
|
||||
|
||||
/**
|
||||
* prepare the rule
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms
|
||||
*/
|
||||
function prepareRule(&$container) {
|
||||
|
||||
patForms_Rule::prepareRule($container);
|
||||
|
||||
$onChange = $container->getAttribute('onchange');
|
||||
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
|
||||
$container->setAttribute('onchange', $newHandler . $onChange);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* method called by patForms or any patForms_Element to validate the
|
||||
* element or the form.
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms form object
|
||||
*/
|
||||
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
|
||||
|
||||
if (preg_match($this->_pattern, $element->getValue()) == 0){
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->addValidationError(1);
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
function registerJavascripts(&$form) {
|
||||
|
||||
parent::registerJavascripts($form);
|
||||
|
||||
$script = sprintf("pfr_%s.setValue(%s);\n", $this->_id, $this->_pattern);
|
||||
$form->registerInstanceJavascript($script);
|
||||
}
|
||||
}
|
|
@ -1,182 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* patForms Rule ValidValues
|
||||
*
|
||||
* This is just a simple rule, that checks for a required minimum length of a field
|
||||
*
|
||||
* @package patForms
|
||||
* @subpackage Rules
|
||||
* @author Sven Fuchs <svenfuchs@artweb-design.de>
|
||||
* @license LGPL, see license.txt for details
|
||||
* @link http://www.php-tools.net
|
||||
*/
|
||||
class patForms_Rule_ValidValues extends patForms_Rule
|
||||
{
|
||||
/**
|
||||
* script that will be displayed only once
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $globalScript = array(
|
||||
'html' => "/* patForms::Rule::ValidValues */
|
||||
|
||||
Array.prototype.inArray = function(value) {
|
||||
var i;
|
||||
for (i=0; i < this.length; i++) {
|
||||
if (this[i] === value) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
};
|
||||
|
||||
function pFRC_ValidValue(field) {
|
||||
this.field = eval('pfe_' + field);
|
||||
}
|
||||
|
||||
pFRC_ValidValue.prototype.validate = function() {
|
||||
value = this.field.getValue();
|
||||
for (var i = 0; i < this.values.length; i++) {
|
||||
if (this.values[i] === value) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
var msg = 'Please enter one of the following values: ';
|
||||
for (var i = 0; i < this.values.length; i++) {
|
||||
msg = msg + this.values[i];
|
||||
if (i < this.values.length - 1) {
|
||||
msg = msg + ', ';
|
||||
}
|
||||
}
|
||||
alert(msg);
|
||||
}
|
||||
|
||||
pFRC_ValidValue.prototype.setValues = function(values) {
|
||||
this.values = values;
|
||||
}
|
||||
|
||||
/* END: patForms::Rule::ValidValue */
|
||||
"
|
||||
);
|
||||
|
||||
/**
|
||||
* javascript that will be displayed once per instance
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $instanceScript = array(
|
||||
'html' => "var pfr_[RULE::ID] = new pFRC_ValidValue('[CONTAINER::NAME]');\n"
|
||||
);
|
||||
|
||||
/**
|
||||
* properties that have to be replaced in the instance script.
|
||||
*
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $scriptPlaceholders = array(
|
||||
'RULE::SOURCE' => '_source',
|
||||
);
|
||||
|
||||
/**
|
||||
* name of the rule
|
||||
*
|
||||
* @abstract
|
||||
* @access private
|
||||
*/
|
||||
var $ruleName = 'ValidValue';
|
||||
|
||||
/**
|
||||
* define error codes and messages for the rule
|
||||
*
|
||||
* @access private
|
||||
* @var array $validatorErrorCodes
|
||||
* @todo translate error messages
|
||||
*/
|
||||
var $validatorErrorCodes = array(
|
||||
"C" => array(
|
||||
1 => "Please enter one of the following values: [VALUES].",
|
||||
),
|
||||
"de" => array(
|
||||
1 => "Bitte geben Sie einen der folgenden Werte ein: [VALUES].",
|
||||
),
|
||||
"fr" => array(
|
||||
1 => "Please enter one of the following values: [VALUES].",
|
||||
)
|
||||
);
|
||||
|
||||
/**
|
||||
* possible values
|
||||
* @access private
|
||||
* @var array
|
||||
*/
|
||||
var $_values;
|
||||
|
||||
/**
|
||||
* field id that is used
|
||||
* @access private
|
||||
* @var string
|
||||
*/
|
||||
var $_field;
|
||||
|
||||
public function __construct($params) {
|
||||
|
||||
parent::__construct();
|
||||
|
||||
extract($params);
|
||||
$this->_values = explode('|', $value);
|
||||
}
|
||||
|
||||
/**
|
||||
* prepare the rule
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms
|
||||
*/
|
||||
function prepareRule(&$container) {
|
||||
|
||||
patForms_Rule::prepareRule($container);
|
||||
|
||||
$onChange = $container->getAttribute('onchange');
|
||||
$newHandler = sprintf('pfr_%s.validate();', $this->_id);
|
||||
$container->setAttribute('onchange', $newHandler . $onChange);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* method called by patForms or any patForms_Element to validate the
|
||||
* element or the form.
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms form object
|
||||
*/
|
||||
function applyRule(&$element, $type = PATFORMS_RULE_AFTER_VALIDATION) {
|
||||
|
||||
if (in_array($element->getValue(), $this->_values)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
$this->addValidationError(1, array('values' => implode(', ', $this->_values)));
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @access public
|
||||
*/
|
||||
function registerJavascripts(&$form) {
|
||||
|
||||
parent::registerJavascripts($form);
|
||||
|
||||
foreach ($this->_values as $value) {
|
||||
$values[] = "'$value'";
|
||||
}
|
||||
$script = sprintf("pfr_%s.setValues(new Array(%s));\n", $this->_id, implode(', ', $values));
|
||||
$form->registerInstanceJavascript($script);
|
||||
}
|
||||
}
|
|
@ -1,146 +0,0 @@
|
|||
<?php
|
||||
|
||||
class patForms_Storage_Propel extends patForms_Storage
|
||||
{
|
||||
private $peer;
|
||||
private $peername;
|
||||
|
||||
public function setStorageLocation($peername) {
|
||||
|
||||
$this->peer = new $peername();
|
||||
$this->peername = $peername;
|
||||
|
||||
$parts = explode('.', explode('.', $this->peer->getOMClass()));
|
||||
$this->classname = array_pop($parts);
|
||||
|
||||
$this->setPrimaryField('Id');
|
||||
}
|
||||
|
||||
private function getCriteria($values) {
|
||||
|
||||
$object = new $this->classname();
|
||||
//$object->populateFromArray($values); //TODO use a workaround until we'll get phpNamed keys in populateFromArray()
|
||||
$object = $this->populateObjectFromArray($object, $values);
|
||||
return $object->buildPkeyCriteria();
|
||||
}
|
||||
|
||||
/**
|
||||
* get an entry
|
||||
*
|
||||
* This tries to find an entry in the storage container
|
||||
* that matches the current data that has been set in the
|
||||
* form and populates the form with the data of this
|
||||
* entry
|
||||
*
|
||||
* @access public
|
||||
* @param object patForms patForms object that should be stored
|
||||
* @return boolean true on success
|
||||
*/
|
||||
public function loadEntry(&$form) {
|
||||
|
||||
if (!$object = $this->_entryExists($form->getValues())) {
|
||||
// entry does not exists (why return an array here??)
|
||||
return array();
|
||||
}
|
||||
|
||||
$form->setValues($object->toArray());
|
||||
return true;
|
||||
}
|
||||
|
||||
public function validateEntry(&$form) {
|
||||
|
||||
if (!$object = $this->_entryExists($form->getValues())) {
|
||||
$object = new $this->classname();
|
||||
}
|
||||
//$object->populateFromArray($form->getValues()); //TODO use a workaround until we'll get phpNamed keys in populateFromArray()
|
||||
$object = $this->populateObjectFromArray($object, $form->getValues());
|
||||
$result = $object->validate();
|
||||
|
||||
if ($result !== true) {
|
||||
$mapBuilder = $this->peer->getMapBuilder();
|
||||
$dbMap = $mapBuilder->getDatabaseMap();
|
||||
foreach ($result as $colname => $error) {
|
||||
list($tablename, $colname) = explode('.', $colname);
|
||||
$column = $dbMap->getTable($tablename)->getColumn($colname);
|
||||
$element = $form->getElement($column->getPhpName());
|
||||
$element->addValidatorErrorCodes(array(
|
||||
'C' => array(
|
||||
1 => $error->getMessage() . ' (occured in Storage)',
|
||||
),
|
||||
), 1000);
|
||||
$element->addValidationError(1001);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* adds an entry to the storage
|
||||
*
|
||||
* @param object patForms patForms object that should be stored
|
||||
* @return boolean true on success
|
||||
*/
|
||||
public function _addEntry(&$form) {
|
||||
|
||||
$object = new $this->classname();
|
||||
//$object->populateFromArray($form->getValues()); //TODO use a workaround until we'll get phpNamed keys in populateFromArray()
|
||||
$object = $this->populateObjectFromArray($object, $form->getValues());
|
||||
$object->save();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* updates an entry in the storage
|
||||
*
|
||||
* @param object patForms patForms object that should be stored
|
||||
* @return boolean true on success
|
||||
*/
|
||||
public function _updateEntry(&$form, $primary) {
|
||||
|
||||
$object = $this->_entryExists($form->getValues());
|
||||
//$object->populateFromArray($form->getValues()); //TODO use a workaround until we'll get phpNamed keys in populateFromArray()
|
||||
$object = $this->populateObjectFromArray($object, $form->getValues());
|
||||
$object->save();
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* check, whether an entry exists
|
||||
*
|
||||
* @access private
|
||||
* @param array
|
||||
*/
|
||||
public function _entryExists($values) {
|
||||
|
||||
// This method gets called multiple times, e.g. when an existing
|
||||
// object gets updated. We'll therefor cache results locally using
|
||||
// a criteria string representation as hash.
|
||||
|
||||
static $objects;
|
||||
$criteria = $this->getCriteria($values);
|
||||
$hash = $criteria->toString();
|
||||
|
||||
if (isset($objects[$hash])) {
|
||||
return $objects[$hash];
|
||||
}
|
||||
|
||||
$objects[$hash] = $this->peer->doSelectOne($criteria);
|
||||
|
||||
if (empty($objects[$hash])) {
|
||||
return false;
|
||||
}
|
||||
return $objects[$hash];
|
||||
}
|
||||
|
||||
// this method is just a workaround
|
||||
|
||||
private function populateObjectFromArray($object, $values) {
|
||||
|
||||
foreach (array_keys($object->toArray()) as $key) {
|
||||
if (array_key_exists($key, $values)) {
|
||||
$object->{'set' . $key}($values[$key]);
|
||||
}
|
||||
}
|
||||
return $object;
|
||||
}
|
||||
}
|
|
@ -1,94 +0,0 @@
|
|||
<patTemplate:tmpl name="page">
|
||||
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
|
||||
|
||||
<html>
|
||||
<head>
|
||||
<title>{TITLE}</title>
|
||||
<style>
|
||||
body {
|
||||
font: normal 13px arial;
|
||||
}
|
||||
form div.row {
|
||||
clear: left;
|
||||
float: left;
|
||||
margin-bottom: 5px;
|
||||
}
|
||||
form label {
|
||||
float: left !important;
|
||||
display: block;
|
||||
width: 100px;
|
||||
}
|
||||
form div div {
|
||||
float: left !important;
|
||||
margin: 0px 10px 0px 0px;
|
||||
}
|
||||
form div.descr {
|
||||
font-style: italic;
|
||||
}
|
||||
form div.buttons {
|
||||
clear: left;
|
||||
padding: 5px 0px 0px 100px;
|
||||
}
|
||||
form div.errors {
|
||||
border: solid 1px #666666;
|
||||
margin-bottom: 25px;
|
||||
padding-bottom: 10px;
|
||||
background: #f6f6f6;
|
||||
}
|
||||
form div.errors h3 {
|
||||
background: #666666;
|
||||
color: #ffffff;
|
||||
font-size: 14px;
|
||||
padding: 2px 5px 2px 10px;
|
||||
margin: 0px;
|
||||
}
|
||||
form div.errors p {
|
||||
padding: 10px 10px 10px 10px;
|
||||
margin: 0px;
|
||||
}
|
||||
form div.errors ul {
|
||||
margin: 0px;
|
||||
padding-left: 24px;
|
||||
}
|
||||
input, select {
|
||||
font: normal 12px arial;
|
||||
}
|
||||
</style>
|
||||
</head>
|
||||
|
||||
<body>
|
||||
|
||||
<patTemplate:tmpl name="form">
|
||||
{START}
|
||||
<pattemplate:tmpl name="errors" visibility="hidden">
|
||||
<div class="errors">
|
||||
<h3>Validation failed</h3>
|
||||
<p>Sorry, your input could not be saved for the following reasons:</p>
|
||||
<ul>
|
||||
<pattemplate:tmpl name="error">
|
||||
<li><b>{FIELD}:</b> {MESSAGE}</li>
|
||||
</pattemplate:tmpl>
|
||||
</ul>
|
||||
</div>
|
||||
</pattemplate:tmpl>
|
||||
<patTemplate:tmpl name="elements" type="condition" conditionvar="display">
|
||||
<patTemplate:sub condition="no">
|
||||
{ELEMENT}
|
||||
</patTemplate:sub>
|
||||
<patTemplate:sub condition="__default">
|
||||
<div class="row">
|
||||
<label for="{ID}" title="{TITLE}">{LABEL}:</label>
|
||||
<div>{ELEMENT}</div>
|
||||
<div class="descr">{DESCRIPTION}</div>
|
||||
</div>
|
||||
</patTemplate:sub>
|
||||
</patTemplate:tmpl>
|
||||
<div class="buttons">
|
||||
<input type="submit" name="save" value="Save form"/>
|
||||
</div>
|
||||
{END}
|
||||
</patTemplate:tmpl>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
</patTemplate:tmpl>
|
|
@ -1,10 +0,0 @@
|
|||
|
||||
# This first example is tested with a Bookstore project on MySql
|
||||
# (default setting Sqlite has not been tested)
|
||||
#
|
||||
# Additionally, you'll need some data in your tables. In case you
|
||||
# don't have - here's a mini-dump to get the example running.
|
||||
|
||||
INSERT INTO `author` VALUES (1, 'Martin', 'Heidegger');
|
||||
INSERT INTO `book` VALUES (1, 'Sein und Zeit', '3484701226', NULL, NULL);
|
||||
INSERT INTO `publisher` VALUES (1, 'Max Niemeyer Verlag');
|
|
@ -1,97 +0,0 @@
|
|||
<?
|
||||
|
||||
function __autoload($classname) {
|
||||
$filename = str_replace ('_', '/', $classname) . '.php';
|
||||
require_once $filename;
|
||||
}
|
||||
|
||||
/**
|
||||
* Required packages:
|
||||
*
|
||||
* - Propel Bookstore project (tested only with mysql, not sqlite)
|
||||
* - patForms (http://www.php-tools.net/site.php?file=patForms)
|
||||
* - patTemplate (http://www.php-tools.net/site.php?file=patTemplate)
|
||||
* - Xml_Serializer (http://pear.php.net/package/XML_Serializer)
|
||||
*
|
||||
* Installation:
|
||||
*
|
||||
* In theorie, it should work to
|
||||
*
|
||||
* - download the files from svn/propel/contrib/pat
|
||||
* - save them anywhere in your servers docroot
|
||||
* - tweak the following settings and
|
||||
* - run this file
|
||||
*/
|
||||
|
||||
// change these according to your setup
|
||||
|
||||
$pathToBookstore = 'f:/test/propel'; // omit bookstore/ here
|
||||
$pathToPear = 'f:/pear';
|
||||
$pathToPat = 'f:/pear/pat';
|
||||
|
||||
$path = PATH_SEPARATOR . $pathToBookstore . PATH_SEPARATOR . $pathToPat;
|
||||
set_include_path(get_include_path() . $path);
|
||||
|
||||
// change these according to your propel settings
|
||||
$classname = 'book';
|
||||
$path = './patForms/res';
|
||||
$propelConfFilename = 'conf/bookstore-conf.php';
|
||||
|
||||
// uncomment this to edit an existing record
|
||||
$pk = array('Id' => 2);
|
||||
|
||||
|
||||
/**
|
||||
* the rest should work out of the box if you don't have any unusal
|
||||
* types in your database schema.xml (strings, int etc. should work)
|
||||
*/
|
||||
|
||||
require_once 'bookstore/' . $classname . '.php';
|
||||
Propel::init($propelConfFilename);
|
||||
|
||||
// create a form definition
|
||||
|
||||
$definition = patForms_Definition_Propel::create(array(
|
||||
'name' => $classname,
|
||||
'filename' => $path . '/form.' . $classname . '.xml',
|
||||
));
|
||||
|
||||
// create a storage
|
||||
|
||||
$storage = patForms::createStorage('Propel');
|
||||
$storage->setStorageLocation($classname . 'peer');
|
||||
|
||||
// create a form
|
||||
|
||||
$form = &patForms::createCreator('Definition')->create($definition);
|
||||
$form->setRenderer(patForms::createRenderer('Array'));
|
||||
$form->setStorage($storage);
|
||||
if (isset($pk)) {
|
||||
$form->setValues($pk);
|
||||
}
|
||||
|
||||
// render it to a patTemplate (could be done by other template engines)
|
||||
|
||||
$tpl = new patTemplate();
|
||||
$tpl->setRoot($path);
|
||||
$tpl->readTemplatesFromInput('form.dynamic.tpl');
|
||||
|
||||
$tpl->addVar('page', 'title', 'Bookstore party');
|
||||
$tpl->addVar('form', 'start', $form->serializeStart());
|
||||
$tpl->addVar('form', 'end', $form->serializeEnd());
|
||||
$tpl->addRows('elements', $form->renderForm());
|
||||
|
||||
// this should be possible to be done in a more elegant way
|
||||
if ($errors = $form->getValidationErrors()) {
|
||||
foreach ($errors as $field => $error) {
|
||||
$tpl->addVar('error', 'field', $field);
|
||||
foreach ($error as $line) {
|
||||
$tpl->addVar('error', 'message', $line['message']);
|
||||
$tpl->addVar('error', 'code', $line['code']);
|
||||
$tpl->parseTemplate('error', 'a');
|
||||
}
|
||||
}
|
||||
$tpl->setAttribute('errors', 'visibility', 'visible');
|
||||
}
|
||||
|
||||
$tpl->displayParsedTemplate();
|
File diff suppressed because it is too large
Load Diff
|
@ -1,909 +0,0 @@
|
|||
<?php
|
||||
/*
|
||||
* $Id: Propel.php 1347 2009-12-03 21:06:36Z francois $
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the LGPL. For more information please see
|
||||
* <http://propel.phpdb.org>.
|
||||
*/
|
||||
|
||||
require_once 'HTML/QuickForm.php';
|
||||
|
||||
define('HTML_QUICKFORM_PROPEL_NO_COLUMNS', 2);
|
||||
define('HTML_QUICKFORM_PROPEL_ALL_COLUMNS', 3);
|
||||
define('HTML_QUICKFORM_PROPEL_COLUMN_MADE_VISIBLE', 4);
|
||||
define('HTML_QUICKFORM_PROPEL_COLUMN_MADE_HIDDEN', 5);
|
||||
|
||||
/* On large foreign table resultsets propel choked */
|
||||
# ini_set('memory_limit', '50M');
|
||||
|
||||
/**
|
||||
*
|
||||
* NOTE: HTML_QuickForm_Propel extends HTML_QuickForm, so all QuickForm functionality is available.
|
||||
*
|
||||
* A fictive example:
|
||||
*
|
||||
* $className = 'book';
|
||||
* $id = '7'; // existing item
|
||||
* $id = null; // when no id is passed, it's assumed we are creating a new item
|
||||
*
|
||||
* $quickForm = new HTML_QuickForm_Propel($className, $id); // optionally pass it to the constructor
|
||||
* $quickForm->setAction('/Bookstore/Form');
|
||||
* $quickForm->addElement('header', '', 'HTML_QuickForm_Propel');
|
||||
* $quickForm->setId($id);
|
||||
* $quickForm->setClassName($className);
|
||||
* $quickForm->setTarget('_self');
|
||||
* $quickForm->setMethod('post');
|
||||
*
|
||||
* // use this to override the default behaviour for
|
||||
* // foreign table select boxes, UserPeer::UNAME will be shown in the select list.
|
||||
* // It defaults to the first string column in the foreign table.
|
||||
*
|
||||
* $quickForm->joinColumn(bookPeer::PUBLISHER_ID,UserPeer::UNAME);
|
||||
*
|
||||
* // default to all columns shown
|
||||
* $quickForm->setColumnMode(HTML_QUICKFORM_PROPEL_ALL_COLUMNS);
|
||||
* $quickForm->hideColumn('PASS');
|
||||
*
|
||||
* // or default to no columns shown
|
||||
* $quickForm->setColumnMode(HTML_QUICKFORM_PROPEL_NO_COLUMNS);
|
||||
* $quickForm->showColumn('NAME'); // column name without table prefix.
|
||||
* $quickForm->showColumn('UNAME');
|
||||
* $quickForm->showColumn('USER_INFO');
|
||||
* $quickForm->showColumn('EMAIL');
|
||||
* $quickForm->showColumn('FEMAIL');
|
||||
* $quickForm->showColumn('URL');
|
||||
* $quickForm->showColumn('PASS');
|
||||
*
|
||||
* // generate the form
|
||||
* $quickForm->build();
|
||||
*
|
||||
* // after the form is build, it's possible to modify the generated elements
|
||||
* $quickForm->getElement('NAME')->setSize(10); // manually tune this element
|
||||
*
|
||||
* if ($quickForm->validate()) {
|
||||
* $quickForm->freeze();
|
||||
*
|
||||
* // save the object we have editted
|
||||
* $quickForm->save();
|
||||
* } else {
|
||||
* $quickForm->toHtml(); // or any other QuickForm render option
|
||||
* }
|
||||
*
|
||||
* TODO: map all creoleTypes to usefull formelements
|
||||
*
|
||||
* @author Rob Halff <info@rhalff.com>
|
||||
* some improvements by Zoltan Nagy (sunshine@freemail.hu)
|
||||
* @version $Rev: 1347 $
|
||||
* @copyright Copyright (c) 2005 Rob Halff: LGPL - See LICENCE
|
||||
* @package propel.contrib
|
||||
*/
|
||||
|
||||
class HTML_QuickForm_Propel extends HTML_QuickForm {
|
||||
|
||||
/**
|
||||
* ID of the Propel Object.
|
||||
* @var integer
|
||||
* @access private
|
||||
*/
|
||||
private $id;
|
||||
|
||||
/**
|
||||
* Contains column visibility information.
|
||||
* @var array
|
||||
* @access private
|
||||
*/
|
||||
private $columnVisibility = array();
|
||||
|
||||
/**
|
||||
* Contains titles of columns.
|
||||
* @var array
|
||||
* @access private
|
||||
*/
|
||||
private $columnTitle = array();
|
||||
|
||||
/**
|
||||
* The Column visibility mode either.
|
||||
* Possible values:
|
||||
*
|
||||
* HTML_QUICKFORM_PROPEL_ALL_COLUMNS
|
||||
* HTML_QUICKFORM_PROPEL_NO_COLUMNS
|
||||
*
|
||||
* @var integer
|
||||
* @access private
|
||||
*/
|
||||
private $columnMode;
|
||||
|
||||
/**
|
||||
* String containing the peerName.
|
||||
* @var string
|
||||
* @access private
|
||||
*/
|
||||
private $peerName;
|
||||
|
||||
/**
|
||||
* String containing the className of the propel Object.
|
||||
* @var string
|
||||
* @access private
|
||||
*/
|
||||
private $className;
|
||||
|
||||
/**
|
||||
* The Column objects.
|
||||
*
|
||||
* @var array
|
||||
* @access private
|
||||
*/
|
||||
private $cols;
|
||||
|
||||
/**
|
||||
* The Object being operated on.
|
||||
* @var object
|
||||
* @access private
|
||||
*/
|
||||
private $obj;
|
||||
|
||||
/**
|
||||
* Seperator value.
|
||||
*
|
||||
* In case the option list will be build by multiple values
|
||||
* This is the value these fields will be seperated with
|
||||
*
|
||||
* @var string
|
||||
* @access private
|
||||
*/
|
||||
private $seperator = ' ';
|
||||
|
||||
/**
|
||||
*
|
||||
* Not used yet.
|
||||
*
|
||||
* @var array
|
||||
* @access private
|
||||
*/
|
||||
private $joinMap = array();
|
||||
|
||||
/**
|
||||
* The default QuickForm rule type to use.
|
||||
* Either server or client
|
||||
*
|
||||
* @var string
|
||||
* @access private
|
||||
*/
|
||||
private $defaultRuleType = 'server';
|
||||
|
||||
|
||||
/**
|
||||
* This is used in the QuickForm DateElement
|
||||
* @var string
|
||||
* @access private
|
||||
*/
|
||||
private $lang = 'en';
|
||||
|
||||
/**
|
||||
* Rulemapping should cover all available propel rules
|
||||
*
|
||||
* @var array
|
||||
* @access private
|
||||
*/
|
||||
private $ruleMapping = array(
|
||||
'mask'=>'regex',
|
||||
'maxLength'=>'maxlength',
|
||||
'minLength'=>'minlength',
|
||||
'maxValue'=>'maxvalue',
|
||||
'minValue'=>'minvalue',
|
||||
'required'=>'required',
|
||||
'validValues'=>'validvalues',
|
||||
'unique'=>'unique'
|
||||
);
|
||||
|
||||
/**
|
||||
*
|
||||
* CreoleType to QuickForm element mapping
|
||||
*
|
||||
* @var array
|
||||
* @access private
|
||||
*/
|
||||
private $typeMapping = array(
|
||||
CreoleTypes::BOOLEAN =>'radio',
|
||||
CreoleTypes::BIGINT =>'text',
|
||||
CreoleTypes::SMALLINT =>'text',
|
||||
CreoleTypes::TINYINT =>'text',
|
||||
CreoleTypes::INTEGER =>'text',
|
||||
CreoleTypes::NUMERIC =>'text',
|
||||
CreoleTypes::DECIMAL =>'text',
|
||||
CreoleTypes::REAL =>'text',
|
||||
CreoleTypes::FLOAT =>'text',
|
||||
CreoleTypes::DOUBLE =>'text',
|
||||
CreoleTypes::CHAR =>'text',
|
||||
CreoleTypes::VARCHAR =>'text',
|
||||
CreoleTypes::LONGVARCHAR=>'textarea',
|
||||
CreoleTypes::TEXT =>'textarea',
|
||||
CreoleTypes::TIME =>'text',
|
||||
CreoleTypes::TIMESTAMP =>'date',
|
||||
CreoleTypes::DATE =>'date',
|
||||
CreoleTypes::YEAR =>'text',
|
||||
CreoleTypes::VARBINARY =>'text',
|
||||
CreoleTypes::BLOB =>'text',
|
||||
CreoleTypes::CLOB =>'text',
|
||||
CreoleTypes::BINARY =>'text',
|
||||
CreoleTypes::LONGVARBINARY=>'text',
|
||||
CreoleTypes::ARR =>'text',
|
||||
CreoleTypes::OTHER =>'text'
|
||||
);
|
||||
|
||||
/**
|
||||
*
|
||||
* The Constructor
|
||||
*
|
||||
* Classname and id are specific to HTML_QuickForm_Propel
|
||||
*
|
||||
* The other parameters are needed to construct the parent QuickForm Class.
|
||||
*
|
||||
* @param string className
|
||||
* @param string id
|
||||
* @param string formName
|
||||
* @param string method
|
||||
* @param string action
|
||||
* @param string target
|
||||
* @param array attributes
|
||||
* @param boolean trackSubmit
|
||||
*
|
||||
*/
|
||||
public function __construct($className = null, $id = null, $formName='HTML_QuickForm_Propel', $method='post', $action='', $target='_self', $attributes=null, $trackSubmit = false)
|
||||
{
|
||||
$this->setClassName($className);
|
||||
$this->setPeerName($className.'Peer'); // Is this always true ?
|
||||
$this->setId($id);
|
||||
parent::HTML_QuickForm($formName, $method, $action, $target, $attributes, $trackSubmit);
|
||||
|
||||
// set the default column policy
|
||||
$this->setColumnMode(HTML_QUICKFORM_PROPEL_ALL_COLUMNS);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* NOT IMPLEMENTED
|
||||
*
|
||||
* Allows for creating complex forms.
|
||||
* Note that limit 1 will always be added to the criteria.
|
||||
* Because we can only edit one record/row at a time.
|
||||
*
|
||||
* However we will be able to join tables in complex ways.
|
||||
*
|
||||
* @param Criteria
|
||||
*
|
||||
*/
|
||||
public function setCriteria(Criteria $c)
|
||||
{
|
||||
$c->setLimit(1);
|
||||
$this->criteria = $c;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Set the action of this form
|
||||
*
|
||||
* @param string action
|
||||
*
|
||||
*/
|
||||
public function setAction($action)
|
||||
{
|
||||
$attributes = array('action'=>$action);
|
||||
$this->updateAttributes($attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Set method of this form, e.g. post or get
|
||||
*
|
||||
* @param string method
|
||||
*
|
||||
*/
|
||||
public function setMethod($method)
|
||||
{
|
||||
$attributes = array('method'=>$method);
|
||||
$this->updateAttributes($attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Set the target of this form
|
||||
*
|
||||
* @param string target
|
||||
*
|
||||
*/
|
||||
public function setTarget($target)
|
||||
{
|
||||
$attributes = array('target'=>$target);
|
||||
$this->updateAttributes($attributes);
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Set the id of the object we need to get
|
||||
*
|
||||
* @param string id
|
||||
*
|
||||
*/
|
||||
public function setId($id)
|
||||
{
|
||||
$this->id = $id;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Set the class
|
||||
*
|
||||
* @param string className
|
||||
*
|
||||
*/
|
||||
public function setClassName($className)
|
||||
{
|
||||
$this->className = $className;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Get the class name
|
||||
*
|
||||
* @return string className
|
||||
*
|
||||
*/
|
||||
public function getClassName()
|
||||
{
|
||||
return $this->className;
|
||||
}
|
||||
|
||||
private function setPeerName($peerName)
|
||||
{
|
||||
$this->peerName = $peerName;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Get the peer name
|
||||
*
|
||||
* @return string peerName
|
||||
*
|
||||
*/
|
||||
public function getPeerName()
|
||||
{
|
||||
return $this->peerName;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the form
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
*/
|
||||
public function build()
|
||||
{
|
||||
|
||||
if (!class_exists($this->peerName)) {
|
||||
// some autoloading, dunno if it should belong here.
|
||||
// or in the users autoload function
|
||||
//$dbMap = call_user_func(array($this->peerName, 'getMapBuilder'));
|
||||
// TODO: implement this.
|
||||
}
|
||||
|
||||
if (empty($this->id)) {
|
||||
// create empty instance of this class
|
||||
$this->obj = new $this->className();
|
||||
} else {
|
||||
// find the object.
|
||||
if (!$this->obj = call_user_func(array($this->peerName, 'retrieveByPK'), $this->id)) {
|
||||
// for help me god.. what to do ?
|
||||
throw new PropelException("HTML_QuickForm_Propel::build(): $this->peerName::retrieveByPK($this->id) failed.");
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// note: getTableMap is protected by default.
|
||||
// so do this handstand to get the tableMap
|
||||
$mapBuilder = call_user_func(array($this->peerName, 'getMapBuilder'));
|
||||
|
||||
// Note: $dbMap is re-used below to determine foreign table
|
||||
$dbMap = $mapBuilder->getDatabaseMap();
|
||||
|
||||
// Get the column names for this table.
|
||||
$this->cols = $dbMap->getTable(constant("$this->peerName::TABLE_NAME"))->getColumns();
|
||||
|
||||
// Do it the HTML_QuickForm way and use defaultValues
|
||||
// instead of setValue() on every element.
|
||||
// we have to first loop through the columns
|
||||
foreach ($this->cols as $colName=>$col) {
|
||||
|
||||
|
||||
$elementType = $this->typeMapping[$col->getCreoleType()];
|
||||
|
||||
if ($elementType == 'date') {
|
||||
// null returns timestamp
|
||||
$value = $this->obj->{'get'.$col->getPhpName()}(null);
|
||||
} else {
|
||||
|
||||
$value = $this->obj->{'get'.$col->getPhpName()}();
|
||||
|
||||
}
|
||||
|
||||
$defaultValues[$colName] = $value;
|
||||
}
|
||||
|
||||
$this->setDefaults($defaultValues);
|
||||
|
||||
foreach ($this->cols as $colName=>$col) {
|
||||
|
||||
if ($this->isColumnHidden($colName)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if ($col->isPrimaryKey()) {
|
||||
// create a hidden field with primary key
|
||||
if (!$this->checkColumn($colName, HTML_QUICKFORM_PROPEL_COLUMN_MADE_VISIBLE)) {
|
||||
$this->addElement('hidden', $col->getColumnName(), $col->getColumnName());
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// element's title
|
||||
$colTitle = $this->getColumnTitle($colName);
|
||||
|
||||
if ($col->isForeignKey()) {
|
||||
|
||||
// TODO: check if user created an optional method for populating the select form
|
||||
// this populating of the select box is just some way to show joined items in a form.
|
||||
// it could also be checkboxes, radio buttons or whatever kind of widget.
|
||||
|
||||
$relatedTable = $dbMap->getTable($col->getRelatedTableName());
|
||||
$relatedCols = $relatedTable->getColumns();
|
||||
$relatedPeer = $relatedTable->getPhpName().'Peer';
|
||||
|
||||
if (is_callable($relatedPeer, 'doSelect')) {
|
||||
|
||||
|
||||
// TODO: allow set this criteria.
|
||||
$c = new Criteria;
|
||||
|
||||
$relatedList = call_user_func(array($relatedPeer,'doSelect'), $c);
|
||||
|
||||
$colConstant = constant($this->peerName.'::'.$colName);
|
||||
//$relatedColConstant = constant($relatedPeer.'::'.$relatedCol->getColumnName());
|
||||
$relatedGetter = 'getPrimaryKey';
|
||||
|
||||
|
||||
// TODO: this needs to be array based, to support multiple foreign columns
|
||||
if (isset($this->joinMap[$colConstant])) {
|
||||
// translate to getter
|
||||
$relatedColConstant = $this->joinMap[$colConstant];
|
||||
if (!$relatedTable->containsColumn($relatedColConstant)) {
|
||||
// throw exception, there is no such column
|
||||
throw new PropelException('HTML_QuickForm_Propel::build(): there is no column named '.$relatedTable->normalizeColName($relatedConstant).'in '.$relatedTable->getTableName().' while trying to build the select list');
|
||||
}
|
||||
$nameColumn = $relatedTable->getColumn($relatedColConstant);
|
||||
$relatedGetter = 'get'.$nameColumn->getPhpName();
|
||||
} else {
|
||||
//auto detection
|
||||
// determine the first string column
|
||||
foreach ($relatedCols as $relatedCol) {
|
||||
if ($relatedCol->getType() == 'string') {
|
||||
$relatedGetter = 'get'.$relatedCol->getPhpName();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
$selectList = array();
|
||||
|
||||
// TODO: not hardcoded here.
|
||||
$selectList[null] = _('Please selection an option');
|
||||
|
||||
foreach ($relatedList as $relObj) {
|
||||
$key = $relObj->getPrimaryKey();
|
||||
|
||||
if (false OR $yesWannaUseEntireObjectsToUseItInTemplate) {
|
||||
// TODO: IMPLEMENT THIS.
|
||||
$selectList[$key] = $relObj;
|
||||
} elseif (false OR $forceSomeKindOfColumnToBeDisplayed) {
|
||||
// TODO: IMPLEMENT THIS.
|
||||
} else {
|
||||
$selectList[$key] = $relObj->{$relatedGetter}();
|
||||
}
|
||||
}
|
||||
|
||||
if (count($selectList) > 1) { // value of 1 depends on select message being set.
|
||||
$select =& $this->addElement('select', $colName, $colTitle, $selectList);
|
||||
} else {
|
||||
// what to do if no records exists in the foreign table ?
|
||||
$this->addElement('static', $colName, $colTitle, _('No Records'));
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// do some recursion ?
|
||||
|
||||
} else {
|
||||
|
||||
//TODO: the mapping is not so generic anymore (to many exceptions)
|
||||
$elementType = $this->typeMapping[$col->getCreoleType()];
|
||||
|
||||
if ($col->getCreoleType() == CreoleTypes::BOOLEAN) {
|
||||
// TODO: describe how to override these options.
|
||||
$radio = array();
|
||||
$radio[] = HTML_QuickForm::createElement('radio', null, null, 'Yes', true);
|
||||
$radio[] = HTML_QuickForm::createElement('radio', null, null, 'No', false);
|
||||
$el = $this->addGroup($radio, $colName, $colName);
|
||||
|
||||
|
||||
} else {
|
||||
|
||||
$el = $this->addElement(
|
||||
$elementType,
|
||||
$colName,
|
||||
$colTitle);
|
||||
|
||||
if ($elementType == 'text') {
|
||||
$el->setMaxLength($col->getSize());
|
||||
}
|
||||
|
||||
if ($col->getCreoleType() == CreoleTypes::TIMESTAMP) {
|
||||
|
||||
/* Option Info:
|
||||
var $_options = array(
|
||||
'language' => 'en',
|
||||
'format' => 'dMY',
|
||||
'minYear' => 2001,
|
||||
'maxYear' => 2010,
|
||||
'addEmptyOption' => false,
|
||||
'emptyOptionValue' => '',
|
||||
'emptyOptionText' => ' ',
|
||||
'optionIncrement' => array('i' => 1, 's' => 1)
|
||||
);
|
||||
*/
|
||||
|
||||
// hmm, don't like it but there seems to be no public method
|
||||
// to set an option afterwards
|
||||
$el->_options['language'] = $this->lang;
|
||||
// TODO: is the format always the same in propel ?
|
||||
$el->_options['format'] = 'Y-F-d H:i:s';
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
// add an html id to the element
|
||||
$this->addElementId($el, $colName);
|
||||
|
||||
//$el->setValue($value);
|
||||
|
||||
// required rule for NOT NULL columns
|
||||
if ($col->isNotNull()) {
|
||||
// TODO: What error message should we use?
|
||||
$this->addRule($colName,
|
||||
$this->getColumnTitle($colName) . ' is required',
|
||||
'required');
|
||||
}
|
||||
|
||||
if ($col->hasValidators()) {
|
||||
|
||||
foreach ($col->getValidators() as $validatorMap) {
|
||||
|
||||
$this->addRule($colName,
|
||||
$validatorMap->getMessage(),
|
||||
$this->ruleMapping[$validatorMap->getName()],
|
||||
$validatorMap->getValue(),
|
||||
$this->defaultRuleType
|
||||
);
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// should HTML_QuickForm_Propel add this ?
|
||||
$this->addElement('submit', 'submit', 'Submit');
|
||||
|
||||
// do this for the developer, can't think of any case where this is unwanted.
|
||||
$this->applyFilter('__ALL__', 'trim');
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Use it to change the locale used for the Date element
|
||||
*
|
||||
* @param string locale
|
||||
* @return void
|
||||
*
|
||||
*/
|
||||
public function setLang($lang)
|
||||
{
|
||||
$this->lang = $lang;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Save the form.
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
*/
|
||||
public function save()
|
||||
{
|
||||
$this->copyToObj();
|
||||
$this->obj->save();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Copy form values to Obj.
|
||||
*
|
||||
* @return void
|
||||
*
|
||||
*/
|
||||
public function copyToObj()
|
||||
{
|
||||
// TODO: check what process does, if we leave out anything important.
|
||||
|
||||
if (!isset($this->cols)) {
|
||||
// throw some error, form cannot be saved before it is build.
|
||||
throw new PropelException('HTML_QuickForm_Propel::save(): form cannot be saved before it is build.');
|
||||
}
|
||||
|
||||
foreach ($this->cols as $colName=>$col) {
|
||||
|
||||
// Has the form got this element?
|
||||
if ($this->isColumnHidden($colName))
|
||||
{
|
||||
continue;
|
||||
}
|
||||
|
||||
$value = $this->getElementValue($colName);
|
||||
if ($value instanceof HTML_QuickForm_Error)
|
||||
{
|
||||
// TODO: What should we do if an error has occured?
|
||||
continue;
|
||||
}
|
||||
$elementType = $this->typeMapping[$col->getCreoleType()];
|
||||
|
||||
// quickform doesn't seem to give back a timestamp, so calculate the date manually.
|
||||
if ($elementType == 'date') {
|
||||
|
||||
$date = array(
|
||||
'D' => null,
|
||||
'l' => null,
|
||||
'd' => null,
|
||||
'M' => null,
|
||||
'm' => null,
|
||||
'F' => null,
|
||||
'Y' => null,
|
||||
'y' => null,
|
||||
'h' => null,
|
||||
'H' => null,
|
||||
'i' => null,
|
||||
's' => null,
|
||||
'a' => null,
|
||||
'A' => null
|
||||
);
|
||||
|
||||
foreach ($value as $key=>$val) {
|
||||
$date[$key] = $val[0];
|
||||
|
||||
}
|
||||
|
||||
$value = mktime($date['h'], $date['m'], $date['s'], $date['M'], $date['d'], $date['Y']);
|
||||
}
|
||||
|
||||
$this->obj->{'set'.$col->getPhpName()}($value);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Get the object we are operating on.
|
||||
*
|
||||
* @return object a propel object
|
||||
*
|
||||
*/
|
||||
public function getObj()
|
||||
{
|
||||
return $this->obj;
|
||||
}
|
||||
|
||||
/**
|
||||
* What to do if a delete button is added
|
||||
* and the user clicks on it, after the object has been delete in save()
|
||||
*/
|
||||
public function onDelete()
|
||||
{
|
||||
|
||||
|
||||
}
|
||||
|
||||
public function createDeleteButton()
|
||||
{
|
||||
return $this->addElement('submit', 'delete', 'Delete');
|
||||
}
|
||||
|
||||
public function isColumnHidden($column)
|
||||
{
|
||||
if ($this->checkColumn($column, HTML_QUICKFORM_PROPEL_COLUMN_MADE_HIDDEN) && $this->columnMode == HTML_QUICKFORM_PROPEL_ALL_COLUMNS) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!$this->checkColumn($column, HTML_QUICKFORM_PROPEL_COLUMN_MADE_VISIBLE) && $this->columnMode == HTML_QUICKFORM_PROPEL_NO_COLUMNS) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private function checkColumn($column, $state)
|
||||
{
|
||||
if (isset($this->columnVisibility[$column])) {
|
||||
return ($this->columnVisibility[$column] == $state);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Sets the default visibility mode
|
||||
*
|
||||
* This must be either:
|
||||
* HTML_QUICKFORM_PROPEL_NO_COLUMNS or
|
||||
* HTML_QUICKFORM_PROPEL_ALL_COLUMNS
|
||||
*
|
||||
* @param string $column column name
|
||||
* @return void
|
||||
*
|
||||
*/
|
||||
public function setColumnMode($mode)
|
||||
{
|
||||
|
||||
if ($mode != HTML_QUICKFORM_PROPEL_NO_COLUMNS && $mode != HTML_QUICKFORM_PROPEL_ALL_COLUMNS) {
|
||||
|
||||
throw new PropelException('HTML_QuickForm_Propel::setColumnMode(): invalid mode passed.');
|
||||
|
||||
}
|
||||
|
||||
$this->columnMode = $mode;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Tell HTML_QuickForm_Propel it should hide this column
|
||||
* It is now passed like ID instead of somePeer::ID
|
||||
* The latter is better, but the array_keys of the columns are in ID format and not somePeer::ID
|
||||
*
|
||||
* @param string $column column name
|
||||
* @return void
|
||||
*
|
||||
*/
|
||||
|
||||
public function hideColumn($column)
|
||||
{
|
||||
$this->columnVisibility[$column] = HTML_QUICKFORM_PROPEL_COLUMN_MADE_HIDDEN;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Tell HTML_QuickForm_Propel it should show this column
|
||||
*
|
||||
* It is now passed like ID instead of somePeer::ID
|
||||
* The latter is better, but the array_keys of the columns are in ID format and not somePeer::ID
|
||||
*
|
||||
* @param string $column column name
|
||||
* @param string $title Title for the column, not required
|
||||
* @return void
|
||||
*/
|
||||
public function showColumn($column, $title = NULL)
|
||||
{
|
||||
$this->columnVisibility[$column] = HTML_QUICKFORM_PROPEL_COLUMN_MADE_VISIBLE;
|
||||
if ($title !== NULL)
|
||||
{
|
||||
$this->setColumnTitle($column, $title);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* assign a title to the column
|
||||
*
|
||||
* @param string $column
|
||||
* @param string $title
|
||||
* @return void
|
||||
*/
|
||||
public function setColumnTitle($column, $title)
|
||||
{
|
||||
$this->columnTitles[$column] = $title;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* returns column's title
|
||||
*
|
||||
* @param string $column
|
||||
* @return void
|
||||
*/
|
||||
public function getColumnTitle($column)
|
||||
{
|
||||
// TODO: check if $column exists
|
||||
return (array_key_exists($column, $this->columnTitles))
|
||||
? $this->columnTitles[$column]
|
||||
: $column;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Try to automatically join all relatedTables.
|
||||
* NOT IMPLEMENTED
|
||||
*
|
||||
* @param boolean $bool
|
||||
* @return void
|
||||
*/
|
||||
public function autoJoin($bool)
|
||||
{
|
||||
$this->autoJoin = $bool;
|
||||
}
|
||||
|
||||
/**
|
||||
* Override this if you don't like the (strtolower) default
|
||||
*
|
||||
* @param HTML_QuickForm_Element $el
|
||||
* @param string $colName
|
||||
* @return void
|
||||
*/
|
||||
protected function addElementId($el, $colName)
|
||||
{
|
||||
$el->updateAttributes(array('id'=>strtolower($colName)));
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Set the default rule typef
|
||||
* @param string $type
|
||||
* @return void
|
||||
*
|
||||
*/
|
||||
public function setDefaultRuleType($type)
|
||||
{
|
||||
$this->defaultRuleType = $type;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* UNFINISHED
|
||||
*
|
||||
* Probably it would be nice to be able to add this to the schema xml
|
||||
*
|
||||
* TODO: further implement multiple columns for the select list
|
||||
*
|
||||
* @var colName constant
|
||||
* @var foreignColName mixed (constant/array of columnName constants)
|
||||
* @var $seperator string Only used if foreignColName is an array
|
||||
*/
|
||||
|
||||
public function joinColumn($colName, $foreignColName, $seperator = null)
|
||||
{
|
||||
if (isset($seperator)) {
|
||||
$this->seperator = $seperator;
|
||||
}
|
||||
$this->joinMap[$colName] = $foreignColName;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,352 +0,0 @@
|
|||
<?
|
||||
/*
|
||||
* $Id: Propel.php 1347 2009-12-03 21:06:36Z francois $
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
|
||||
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
|
||||
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
|
||||
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
|
||||
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
||||
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
|
||||
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
|
||||
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
|
||||
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
|
||||
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*
|
||||
* This software consists of voluntary contributions made by many individuals
|
||||
* and is licensed under the LGPL. For more information please see
|
||||
* <http://propel.phpdb.org>.
|
||||
*/
|
||||
|
||||
require_once 'Structures/DataGrid.php';
|
||||
|
||||
define('STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS', 2);
|
||||
define('STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS', 3);
|
||||
define('STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_VISIBLE', 4);
|
||||
define('STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_HIDDEN', 5);
|
||||
|
||||
/**
|
||||
*
|
||||
* NOTE: Structures_DataGrid_Propel extends Structures_DataGrid, so all Datagrid functionality is available.
|
||||
*
|
||||
* A fictive example:
|
||||
* // Propel and Propel project classes must be in the include_path
|
||||
*
|
||||
* // Propel Class name : Report
|
||||
* $dg =& new Structures_DataGrid_Propel('Report');
|
||||
*
|
||||
* // limit to 10 rows
|
||||
* $c = new Criteria();
|
||||
* $c->setLimit(10);
|
||||
* $dg->setCriteria($c);
|
||||
*
|
||||
* // choose what columns must be displayed
|
||||
* $dg->setColumnMode(STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS);
|
||||
* $dg->showColumn('ACTIVE');
|
||||
* $dg->showColumn('TITLE');
|
||||
* $dg->showColumn('ID');
|
||||
*
|
||||
* // generate the datagrid
|
||||
* $dg->build();
|
||||
*
|
||||
* // add two columns to edit the row and checkbox for further operations
|
||||
* $dg->addColumn(new Structures_DataGrid_Column('', null, null, array('width' => '4%'), null, 'printEditLink()'));
|
||||
* $dg->addColumn(new Structures_DataGrid_Column('', null, null, array('width' => '1%'), null, 'printCheckbox()'));
|
||||
*
|
||||
* // Display the datagrid
|
||||
* $dg->render();
|
||||
*
|
||||
* @author Marc <therebel@free.fr>
|
||||
* @version $Rev: 1347 $
|
||||
* @copyright Copyright (c) 2005 Marc: LGPL - See LICENCE
|
||||
* @package propel.contrib
|
||||
*/
|
||||
|
||||
class Structures_DataGrid_Propel extends Structures_DataGrid {
|
||||
|
||||
/**
|
||||
* Contains column visibility information.
|
||||
* @var array
|
||||
* @access private
|
||||
*/
|
||||
private $columnVisibility = array();
|
||||
|
||||
/**
|
||||
* The Column visibility mode.
|
||||
* Possible values:
|
||||
*
|
||||
* STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS
|
||||
* STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS
|
||||
*
|
||||
* @var integer
|
||||
* @access private
|
||||
*/
|
||||
private $columnMode;
|
||||
|
||||
/**
|
||||
* String containing the peerName.
|
||||
* @var string
|
||||
* @access private
|
||||
*/
|
||||
private $peerName;
|
||||
|
||||
/**
|
||||
* String containing the className of the propel Object.
|
||||
* @var string
|
||||
* @access private
|
||||
*/
|
||||
private $className;
|
||||
|
||||
/**
|
||||
* Criteria of the Select query.
|
||||
* @var criteria
|
||||
* @access private
|
||||
*/
|
||||
private $criteria;
|
||||
|
||||
/**
|
||||
* List of primary keys
|
||||
* @var array
|
||||
* @access public
|
||||
*/
|
||||
public $primaryKeys;
|
||||
|
||||
/**
|
||||
*
|
||||
* The Constructor
|
||||
*
|
||||
* Classname is specific to Structures_Datagrid_Propel
|
||||
*
|
||||
* The other parameters are needed to construct the parent Structures_DataGrid Class.
|
||||
*
|
||||
* @param string className
|
||||
* @param string limit
|
||||
* @param string render
|
||||
*
|
||||
*/
|
||||
public function __construct($className = null, $limit = null, $render = DATAGRID_RENDER_HTML_TABLE)
|
||||
{
|
||||
|
||||
include_once $className.'.php';
|
||||
include_once $className.'Peer'.'.php';
|
||||
|
||||
$this->setClassName($className);
|
||||
$this->setPeerName($className.'Peer'); // Is this always true ?
|
||||
parent::Structures_DataGrid($limit,null,$render);
|
||||
|
||||
// set the default column policy
|
||||
$this->setColumnMode(STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS);
|
||||
$this->criteria = new Criteria();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Set the criteria for select query
|
||||
*
|
||||
* @param Criteria c
|
||||
*
|
||||
*/
|
||||
public function setCriteria(Criteria $c)
|
||||
{
|
||||
$this->criteria = $c;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Set the class
|
||||
*
|
||||
* @param string className
|
||||
*
|
||||
*/
|
||||
public function setClassName($className)
|
||||
{
|
||||
$this->className = $className;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Get the class name
|
||||
*
|
||||
* @return string className
|
||||
*
|
||||
*/
|
||||
public function getClassName()
|
||||
{
|
||||
return $this->className;
|
||||
}
|
||||
|
||||
private function setPeerName($peerName)
|
||||
{
|
||||
$this->peerName = $peerName;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Get the peer name
|
||||
*
|
||||
* @return string peerName
|
||||
*
|
||||
*/
|
||||
public function getPeerName()
|
||||
{
|
||||
return $this->peerName;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Get the visibility of a column
|
||||
*
|
||||
* @return boolean true if column is set to hidden
|
||||
*
|
||||
*/
|
||||
public function isColumnHidden($column)
|
||||
{
|
||||
if ($this->checkColumn($column, STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_HIDDEN) && $this->columnMode == STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (!$this->checkColumn($column, STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_VISIBLE) && $this->columnMode == STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Check the state of a column
|
||||
*
|
||||
* @return boolean true if column is set to state
|
||||
*
|
||||
*/
|
||||
private function checkColumn($column, $state)
|
||||
{
|
||||
if (isset($this->columnVisibility[$column])) {
|
||||
return ($this->columnVisibility[$column] == $state);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Sets the default visibility mode
|
||||
*
|
||||
* This must be either:
|
||||
* STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS or
|
||||
* STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS
|
||||
*
|
||||
* @param string $column column name
|
||||
* @return void
|
||||
*
|
||||
*/
|
||||
public function setColumnMode($mode)
|
||||
{
|
||||
|
||||
if ($mode != STRUCTURES_DATAGRID_PROPEL_NO_COLUMNS && $mode != STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS) {
|
||||
throw new PropelException('STRUCTURES_DATAGRID_PROPEL::setColumnMode(): invalid mode passed.');
|
||||
}
|
||||
|
||||
$this->columnMode = $mode;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Tell Structures_Datagrid_Propel it should hide this column
|
||||
* It is now passed like ID instead of somePeer::ID
|
||||
* The latter is better, but the array_keys of the columns are
|
||||
* in ID format and not somePeer::ID
|
||||
*
|
||||
* @param string $column column name
|
||||
* @return void
|
||||
*
|
||||
*/
|
||||
public function hideColumn($column)
|
||||
{
|
||||
$this->columnVisibility[$column] = STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_HIDDEN;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Tell Structures_Datagrid_Propel it should show this column
|
||||
*
|
||||
* It is now passed like ID instead of somePeer::ID
|
||||
* The latter is better, but the array_keys of the columns are in ID format and not somePeer::ID
|
||||
*
|
||||
* @param string $column column name
|
||||
* @return void
|
||||
*/
|
||||
public function showColumn($column)
|
||||
{
|
||||
$this->columnVisibility[$column] = STRUCTURES_DATAGRID_PROPEL_COLUMN_MADE_VISIBLE;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* Build the datagrid
|
||||
*
|
||||
* @return void
|
||||
*/
|
||||
public function build()
|
||||
{
|
||||
$mapBuilder = call_user_func(array($this->getPeerName(), 'getMapBuilder'));
|
||||
$dbMap = $mapBuilder->getDatabaseMap();
|
||||
$cols = $dbMap->getTable(constant($this->getPeerName()."::TABLE_NAME"))->getColumns();
|
||||
$stmt = call_user_func(array( $this->getPeerName(), 'doSelectStmt'), $this->criteria);
|
||||
|
||||
$dataset = array();
|
||||
$columns = array();
|
||||
$this->primaryKeys = array();
|
||||
$class = $this->getClassName();
|
||||
while ($row = $stmt->fetch(PDO::FETCH_NUM)) { // use Creole ResultSet methods to iterate over resultset
|
||||
$obj = new $class();
|
||||
$obj->hydrate($row);
|
||||
|
||||
$row = array();
|
||||
foreach ($cols as $tmp_id => $col)
|
||||
{
|
||||
// save the PK in an array
|
||||
if ($col->isPrimaryKey()) {
|
||||
$this->primaryKeys[$col->getColumnName()] = $col->getColumnName();
|
||||
}
|
||||
|
||||
$value = $obj->{'get'.$col->getPhpName()}(null);
|
||||
// save the row value
|
||||
|
||||
$row[$col->getColumnName()] = $value;
|
||||
// save the list of propel header column name
|
||||
$columns[$col->getColumnName()] = $col->getColumnName();
|
||||
|
||||
}
|
||||
// add the row to dataset
|
||||
$dataset[] = $row;
|
||||
}
|
||||
|
||||
$this->bind($dataset);
|
||||
|
||||
if ($this->columnMode == STRUCTURES_DATAGRID_PROPEL_ALL_COLUMNS) {
|
||||
foreach ($columns as $tmp_id => $column) {
|
||||
|
||||
if (!$this->isColumnHidden($column)) {
|
||||
|
||||
$this->addColumn(new Structures_DataGrid_Column($column, $column, $column, null));
|
||||
}
|
||||
}
|
||||
} else {
|
||||
|
||||
foreach ($this->columnVisibility as $column => $visibility) {
|
||||
|
||||
if (!$this->isColumnHidden($column)) {
|
||||
$this->addColumn(new Structures_DataGrid_Column($column, $column, $column, null));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->renderer->setTableHeaderAttributes(array('class' => 'title'));
|
||||
$this->renderer->setTableAttribute('class', 'list');
|
||||
$this->renderer->sortIconASC = '?';
|
||||
$this->renderer->sortIconDESC = '?';
|
||||
}
|
||||
|
||||
}
|
|
@ -1,130 +0,0 @@
|
|||
= Aggregate Column Behavior =
|
||||
|
||||
The `aggregate_column` behavior keeps a column updated using an aggregate function executed on a related table.
|
||||
|
||||
== Basic Usage ==
|
||||
|
||||
In the `schema.xml`, use the `<behavior>` tag to add the `aggregate_column` behavior to a table. You must provide parameters for the aggregate column `name`, the foreign table name, and the aggegate `expression`. For instance, to add an aggregate column keeping the comment count in a `post` table:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="post">
|
||||
<column name="id" type="INTEGER" required="true" primaryKey="true" autoIncrement="true" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="aggregate_column">
|
||||
<parameter name="name" value="nb_comments" />
|
||||
<parameter name="foreign_table" value="comment" />
|
||||
<parameter name="expression" value="COUNT(id)" />
|
||||
</behavior>
|
||||
</table>
|
||||
<table name="comment">
|
||||
<column name="id" type="INTEGER" required="true" primaryKey="true" autoIncrement="true" />
|
||||
<column name="post_id" type="INTEGER" />
|
||||
<foreign-key foreignTable="post" onDelete="cascade">
|
||||
<reference local="post_id" foreign="id" />
|
||||
</foreign-key>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Rebuild your model, and insert the table creation sql again. The model now has an additional `nb_comments` column, of type `integer` by default. And each time an record from the foreign table is added, modified, or removed, the aggregate column is updated:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$post = new Post();
|
||||
$post->setTitle('How Is Life On Earth?');
|
||||
$post->save();
|
||||
echo $post->getNbComments(); // 0
|
||||
$comment1 = new Comment();
|
||||
$comment1->setPost($post);
|
||||
$comment1->save();
|
||||
echo $post->getNbComments(); // 1
|
||||
$comment2 = new Comment();
|
||||
$comment2->setPost($post);
|
||||
$comment2->save();
|
||||
echo $post->getNbComments(); // 2
|
||||
$comment2->delete();
|
||||
echo $post->getNbComments(); // 1
|
||||
}}}
|
||||
|
||||
The aggregate column is also kept up to date when related records get modified through a Query object:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
CommentQuery::create()
|
||||
->filterByPost($post)
|
||||
->delete():
|
||||
echo $post->getNbComments(); // 0
|
||||
}}}
|
||||
|
||||
== Customizing The Aggregate Calculation ==
|
||||
|
||||
Any aggregate function can be used on any of the foreign columns. For instance, you can use the `aggregate_column` behavior to keep the latest update date of the related comments, or the total votes on the comments. You can even keep several aggregate columns in a single table:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="post">
|
||||
<column name="id" type="INTEGER" required="true" primaryKey="true" autoIncrement="true" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="aggregate_column">
|
||||
<parameter name="name" value="nb_comments" />
|
||||
<parameter name="foreign_table" value="comment" />
|
||||
<parameter name="expression" value="COUNT(id)" />
|
||||
</behavior>
|
||||
<behavior name="aggregate_column">
|
||||
<parameter name="name" value="last_comment" />
|
||||
<parameter name="foreign_table" value="comment" />
|
||||
<parameter name="expression" value="MAX(created_at)" />
|
||||
</behavior>
|
||||
<behavior name="aggregate_column">
|
||||
<parameter name="name" value="total_votes" />
|
||||
<parameter name="foreign_table" value="comment" />
|
||||
<parameter name="expression" value="SUM(vote)" />
|
||||
</behavior>
|
||||
</table>
|
||||
<table name="comment">
|
||||
<column name="id" type="INTEGER" required="true" primaryKey="true" autoIncrement="true" />
|
||||
<column name="post_id" type="INTEGER" />
|
||||
<foreign-key foreignTable="post" onDelete="cascade">
|
||||
<reference local="post_id" foreign="id" />
|
||||
</foreign-key>
|
||||
<column name="created_at" type="TIMESTAMP" />
|
||||
<column name="vote" type="INTEGER" />
|
||||
</table>
|
||||
}}}
|
||||
|
||||
The behavior adds a `computeXXX()` method to the `Post` class to compute the value of the aggregate function. This method, called each time records are modified in the related `comment` table, is the translation of the behavior settings into a SQL query:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// in om/BasePost.php
|
||||
public function computeNbComments(PropelPDO $con)
|
||||
{
|
||||
$stmt = $con->prepare('SELECT COUNT(id) FROM `comment` WHERE comment.POST_ID = :p1');
|
||||
$stmt->bindValue(':p1', $this->getId());
|
||||
$stmt->execute();
|
||||
return $stmt->fetchColumn();
|
||||
}
|
||||
}}}
|
||||
|
||||
You can override this method in the model class to customize the aggregate column calculation.
|
||||
|
||||
== Customizing The Aggregate Column ==
|
||||
|
||||
By default, the behavior adds one columns to the model. If this column is already described in the schema, the behavior detects it and doesn't add it a second time. This can be useful if you need to use a custom `type` or `phpName` for the aggregate column:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="post">
|
||||
<column name="id" type="INTEGER" required="true" primaryKey="true" autoIncrement="true" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<column name="nb_comments" phpName="CommentCount" type="INTEGER" />
|
||||
<behavior name="aggregate_column">
|
||||
<parameter name="name" value="nb_comments" />
|
||||
<parameter name="foreign_table" value="comment" />
|
||||
<parameter name="expression" value="COUNT(id)" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
|
@ -1,89 +0,0 @@
|
|||
= Alternative Coding Standards Behavior =
|
||||
|
||||
The `alternative_coding_standards` behavior changes the coding standards of the model classes generated by Propel to match your own coding style.
|
||||
|
||||
== Basic Usage ==
|
||||
|
||||
In the `schema.xml`, use the `<behavior>` tag to add the `alternative_coding_standards` behavior to a table:
|
||||
{{{
|
||||
#!xml
|
||||
<table name="book">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="alternative_coding_standards" />
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Rebuild your model, and you're ready to go. The code of the model classes now uses an alternative set of coding standards:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// in om/BaseBook.php
|
||||
/**
|
||||
* Set the value of [title] column.
|
||||
*
|
||||
* @param string $v new value
|
||||
* @return Table4 The current object (for fluent API support)
|
||||
*/
|
||||
public function setTitle($v)
|
||||
{
|
||||
if ($v !== null)
|
||||
{
|
||||
$v = (string) $v;
|
||||
}
|
||||
|
||||
if ($this->title !== $v)
|
||||
{
|
||||
$this->title = $v;
|
||||
$this->modifiedColumns[] = BookPeer::TITLE;
|
||||
}
|
||||
|
||||
return $this;
|
||||
}
|
||||
|
||||
// instead of
|
||||
|
||||
/**
|
||||
* Set the value of [title] column.
|
||||
*
|
||||
* @param string $v new value
|
||||
* @return Table4 The current object (for fluent API support)
|
||||
*/
|
||||
public function setTitle($v)
|
||||
{
|
||||
if ($v !== null) {
|
||||
$v = (string) $v;
|
||||
}
|
||||
|
||||
if ($this->title !== $v) {
|
||||
$this->title = $v;
|
||||
$this->modifiedColumns[] = BookPeer::TITLE;
|
||||
}
|
||||
|
||||
return $this;
|
||||
} // setTitle()
|
||||
}}}
|
||||
|
||||
The behavior replaces tabulations by whitespace (2 spaces by default), places opening brackets on newlines, removes closing brackets comments, and can even strip every comments in the generated classes if you wish.
|
||||
|
||||
== Parameters ==
|
||||
|
||||
Each of the new coding style rules has corresponding parameter in the behavior description. Here is the default configuration:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="book">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="alternative_coding_standards">
|
||||
<parameter name="brackets_newline" value="true" />
|
||||
<parameter name="remove_closing_comments" value="true" />
|
||||
<parameter name="use_whitespace" value="true" />
|
||||
<parameter name="tab_size" value="2" />
|
||||
<parameter name="strip_comments" value="false" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
You can change these settings to better match your own coding styles.
|
|
@ -1,73 +0,0 @@
|
|||
= AutoAddPk Behavior =
|
||||
|
||||
The `auto_add_pk` behavior adds a primary key columns to the tables that don't have one. Using this behavior allows you to omit the declaration of primary keys in your tables.
|
||||
|
||||
== Basic Usage ==
|
||||
|
||||
In the `schema.xml`, use the `<behavior>` tag to add the `auto_add_pk` behavior to a table:
|
||||
{{{
|
||||
#!xml
|
||||
<table name="book">
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="auto_add_pk" />
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Rebuild your model, and insert the table creation sql. You will notice that the `book` table has two columns and not just one. The behavior added an `id` column, of type integer and autoincremented. This column can be used as any other column:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$b = new Book();
|
||||
$b->setTitle('War And Peace');
|
||||
$b->save();
|
||||
echo $b->getId(); // 1
|
||||
}}}
|
||||
|
||||
This behavior is more powerful if you add it to the database instead of a table. That way, it will alter all tables not defining a primary key column - and leave the others unchanged.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<database name="bookstore" defaultIdMethod="native">
|
||||
<behavior name="auto_add_pk" />
|
||||
<table name="book">
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
</table>
|
||||
</database>
|
||||
}}}
|
||||
|
||||
You can even enable it for all your database by adding it to the default behaviors in your `build.properties` file:
|
||||
|
||||
{{{
|
||||
#!ini
|
||||
propel.behavior.default = auto_add_pk
|
||||
}}}
|
||||
|
||||
== Parameters ==
|
||||
|
||||
By default, the behavior adds a column named `id` to the table if the table has no primary key. You can customize all the attributes of the added column by setting corresponding parameters in the behavior definition:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<database name="bookstore" defaultIdMethod="native">
|
||||
<behavior name="auto_add_pk">
|
||||
<parameter name="name" value="identifier" />
|
||||
<parameter name="autoIncrement" value="false" />
|
||||
</behavior>
|
||||
<table name="book">
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
</table>
|
||||
</database>
|
||||
}}}
|
||||
|
||||
Once you regenerate your model, the column is now named differently:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$b = new Book();
|
||||
$b->setTitle('War And Peace');
|
||||
$b->setIdentifier(1);
|
||||
$b->save();
|
||||
echo $b->getIdentifier(); // 1
|
||||
}}}
|
|
@ -1,370 +0,0 @@
|
|||
= NestedSet Behavior =
|
||||
|
||||
The `nested_set` behavior allows a model to become a tree structure, and provides numerous methods to traverse the tree in an efficient way.
|
||||
|
||||
Many applications need to store hierarchical data in the model. For instance, a forum stores a tree of messages for each discussion. A CMS sees sections and subsections as a navigation tree. In a business organization chart, each person is a leaf of the organization tree. [http://en.wikipedia.org/wiki/Nested_set_model Nested sets] are the best way to store such hierachical data in a relational database and manipulate it. The name "nested sets" describes the algorithm used to store the position of a model in the tree ; it is also known as "modified preorder tree traversal".
|
||||
|
||||
== Basic Usage ==
|
||||
|
||||
In the `schema.xml`, use the `<behavior>` tag to add the `nested_set` behavior to a table:
|
||||
{{{
|
||||
#!xml
|
||||
<table name="section">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="nested_set" />
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Rebuild your model, insert the table creation sql again, and you're ready to go. The model now has the ability to be inserted into a tree structure, as follows:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$s1 = new Section();
|
||||
$s1->setTitle('Home');
|
||||
$s1->makeRoot(); // make this node the root of the tree
|
||||
$s1->save();
|
||||
$s2 = new Section();
|
||||
$s2->setTitle('World');
|
||||
$s2->insertAsFirstChildOf($s1); // insert the node in the tree
|
||||
$s2->save();
|
||||
$s3 = new Section();
|
||||
$s3->setTitle('Europe');
|
||||
$s3->insertAsFirstChildOf($s2); // insert the node in the tree
|
||||
$s3->save()
|
||||
$s4 = new Section();
|
||||
$s4->setTitle('Business');
|
||||
$s4->insertAsNextSiblingOf($s2); // insert the node in the tree
|
||||
$s4->save();
|
||||
/* The sections are now stored in the database as a tree:
|
||||
$s1:Home
|
||||
| \
|
||||
$s2:World $s4:Business
|
||||
|
|
||||
$s3:Europe
|
||||
*/
|
||||
}}}
|
||||
|
||||
You can continue to insert new nodes as children or siblings of existing nodes, using any of the `insertAsFirstChildOf()`, `insertAsLastChildOf()`, `insertAsPrevSiblingOf()`, and `insertAsNextSiblingOf()` methods.
|
||||
|
||||
Once you have built a tree, you can traverse it using any of the numerous methods the `nested_set` behavior adds to the query and model objects. For instance:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$rootNode = SectionQuery::create()->findRoot(); // $s1
|
||||
$worldNode = $rootNode->getFirstChild(); // $s2
|
||||
$businessNode = $worldNode->getNextSibling(); // $s4
|
||||
$firstLevelSections = $rootNode->getChildren(); // array($s2, $s4)
|
||||
$allSections = $rootNode->getDescendants(); // array($s2, $s3, $s4)
|
||||
// you can also chain the methods
|
||||
$europeNode = $rootNode->getLastChild()->getPrevSibling()->getFirstChild(); // $s3
|
||||
$path = $europeNode->getAncestors(); // array($s1, $s2)
|
||||
}}}
|
||||
|
||||
The nodes returned by these methods are regular Propel model objects, with access to the properties and related models. The `nested_set` behavior also adds inspection methods to nodes:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
echo $s2->isRoot(); // false
|
||||
echo $s2->isLeaf(); // false
|
||||
echo $s2->getLevel(); // 1
|
||||
echo $s2->hasChildren(); // true
|
||||
echo $s2->countChildren(); // 1
|
||||
echo $s2->hasSiblings(); // true
|
||||
}}}
|
||||
|
||||
Each of the traversal and inspection methods result in a single database query, whatever the position of the node in the tree. This is because the information about the node position in the tree is stored in three columns of the model, named `tree_left`, `tree_left`, and `tree_level`. The value given to these columns is determined by the nested set algorithm, and it makes read queries much more effective than trees using a simple `parent_id` foreign key.
|
||||
|
||||
== Manipulating Nodes ==
|
||||
|
||||
You can move a node - and its subtree - across the tree using any of the `moveToFirstChildOf()`, `moveToLastChildOf()`, `moveToPrevSiblingOf()`, and `moveToLastSiblingOf()` methods. These operations are immediate and don't require that you save the model afterwards:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// move the entire "World" section under "Business"
|
||||
$s2->moveToFirstChildOf($s4);
|
||||
/* The tree is modified as follows:
|
||||
$s1:Home
|
||||
|
|
||||
$s4:Business
|
||||
|
|
||||
$s2:World
|
||||
|
|
||||
$s3:Europe
|
||||
*/
|
||||
// now move the "Europe" section directly under root, after "Business"
|
||||
$s2->moveToFirstChildOf($s4);
|
||||
/* The tree is modified as follows:
|
||||
$s1:Home
|
||||
| \
|
||||
$s4:Business $s3:Europe
|
||||
|
|
||||
$s2:World
|
||||
*/
|
||||
}}}
|
||||
|
||||
You can delete the descendants of a node using `deleteDescendants()`:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// move the entire "World" section under "Business"
|
||||
$s4->deleteDescendants($s4);
|
||||
/* The tree is modified as follows:
|
||||
$s1:Home
|
||||
| \
|
||||
$s4:Business $s3:Europe
|
||||
*/
|
||||
}}}
|
||||
|
||||
If you `delete()` a node, all its descendants are deleted in cascade. To avoid accidental deletion of an entire tree, calling `delete()` on a root node throws an exception. Use the `delete()` Query method instead to delete an entire tree.
|
||||
|
||||
== Filtering Results ==
|
||||
|
||||
The `nested_set` behavior adds numerous methods to the generated Query object. You can use these methods to build more complex queries. For instance, to get all the children of the root node ordered by title, build a Query as follows:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$children = SectionQuery::create()
|
||||
->childrenOf($rootNode)
|
||||
->orderByTitle()
|
||||
->find();
|
||||
}}}
|
||||
|
||||
Alternatively, if you already have an existing query method, you can pass it to the model object's methods to filter the results:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$orderQuery = SectionQuery::create()->orderByTitle();
|
||||
$children = $rootNode->getChildren($orderQuery);
|
||||
}}}
|
||||
|
||||
== Multiple Trees ==
|
||||
|
||||
When you need to store several trees for a single model - for instance, several threads of posts in a forum - use a ''scope'' for each tree. This requires that you enable scope tree support in the behavior definition by setting the `use_scope` parameter to `true`:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="post">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="body" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="nested_set">
|
||||
<parameter name="use_scope" value="true" />
|
||||
<parameter name="scope_column" value="thread_id" />
|
||||
</behavior>
|
||||
<foreign-key foreignTable="thread" onDelete="cascade">
|
||||
<reference local="thread_id" foreign="id" />
|
||||
</foreign-key>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Now, after rebuilding your model, you can have as many trees as required:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$thread = ThreadQuery::create()->findPk(123);
|
||||
$firstPost = PostQuery::create()->findRoot($thread->getId()); // first message of the discussion
|
||||
$discussion = PostQuery::create()->findTree(thread->getId()); // all messages of the discussion
|
||||
PostQuery::create()->inTree($thread->getId())->delete(); // delete an entire discussion
|
||||
$firstPostOfEveryDiscussion = PostQuery::create()->findRoots();
|
||||
}}}
|
||||
|
||||
== Using a RecursiveIterator ==
|
||||
|
||||
An alternative way to browse a tree structure extensively is to use a [http://php.net/RecursiveIterator RecursiveIterator]. The `nested_set` behavior provides an easy way to retrieve such an iterator from a node, and to parse the entire branch in a single iteration.
|
||||
|
||||
For instance, to display an entire tree structure, you can use the following code:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$root = SectionQuery::create()->findRoot();
|
||||
foreach ($root->getIterator() as $node) {
|
||||
echo str_repeat(' ', $node->getLevel()) . $node->getTitle() . "\n";
|
||||
}
|
||||
}}}
|
||||
|
||||
The iterator parses the tree in a recursive way by retrieving the children of every node. This can be quite effective on very large trees, since the iterator hydrates only a few objects at a time.
|
||||
|
||||
Beware, though, that the iterator executes many queries to parse a tree. On smaller trees, prefer the `getBranch()` method to execute only one query, and hydrate all records at once:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$root = SectionQuery::create()->findRoot();
|
||||
foreach ($root->getBranch() as $node) {
|
||||
echo str_repeat(' ', $node->getLevel()) . $node->getTitle() . "\n";
|
||||
}
|
||||
}}}
|
||||
|
||||
== Parameters ==
|
||||
|
||||
By default, the behavior adds three columns to the model - four if you use the scope feature. You can use custom names for the nested sets columns. The following schema illustrates a complete customization of the behavior:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="post">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="lft" type="INTEGER" />
|
||||
<column name="rgt" type="INTEGER" />
|
||||
<column name="lvl" type="INTEGER" />
|
||||
<column name="thread_id" type="INTEGER" />
|
||||
<column name="body" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="nested_set">
|
||||
<parameter name="left_column" value="lft" />
|
||||
<parameter name="right_column" value="rgt" />
|
||||
<parameter name="level_column" value="lvl" />
|
||||
<parameter name="use_scope" value="true" />
|
||||
<parameter name="scope_column" value="thread_id" />
|
||||
</behavior>
|
||||
<foreign-key foreignTable="thread" onDelete="cascade">
|
||||
<reference local="thread_id" foreign="id" />
|
||||
</foreign-key>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Whatever name you give to your columns, the `nested_sets` behavior always adds the following proxy methods, which are mapped to the correct column:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$post->getLeftValue(); // returns $post->lft
|
||||
$post->setLeftValue($left);
|
||||
$post->getRightValue(); // returns $post->rgt
|
||||
$post->setRightValue($right);
|
||||
$post->getLevel(); // returns $post->lvl
|
||||
$post->setLevel($level);
|
||||
$post->getScopeValue(); // returns $post->thread_id
|
||||
$post->setScopeValue($scope);
|
||||
}}}
|
||||
|
||||
If your application used the old nested sets builder from Propel 1.4, you can enable the `method_proxies` parameter so that the behavior generates method proxies for the methods that used a different name (e.g. `createRoot()` for `makeRoot()`, `retrieveFirstChild()` for `getFirstChild()`, etc.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="section">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="nested_set">
|
||||
<parameter name="method_proxies" value="true" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
== Complete API ==
|
||||
|
||||
Here is a list of the methods added by the behavior to the model objects:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// storage columns accessors
|
||||
int getLeftValue()
|
||||
$node setLeftValue(int $left)
|
||||
int getRightValue()
|
||||
$node setRightValue(int $right)
|
||||
int getLevel()
|
||||
$node setLevel(int $level)
|
||||
// only for behavior with use_scope
|
||||
int getScopeValue()
|
||||
$node setScopeValue(int $scope)
|
||||
|
||||
// root maker (requires calling save() afterwards)
|
||||
$node makeRoot()
|
||||
|
||||
// inspection methods
|
||||
bool isInTree()
|
||||
bool isRoot()
|
||||
bool isLeaf()
|
||||
bool isDescendantOf()
|
||||
bool isAncestorOf()
|
||||
bool hasParent()
|
||||
bool hasPrevSibling()
|
||||
bool hasNextSibling()
|
||||
bool hasChildren()
|
||||
int countChildren()
|
||||
int countDescendants()
|
||||
|
||||
// tree traversal methods
|
||||
$node getParent()
|
||||
$node getPrevSibling()
|
||||
$node getNextSibling()
|
||||
array getChildren()
|
||||
$node getFirstChild()
|
||||
$node getLastChild()
|
||||
array getSiblings($includeCurrent = false, Criteria $c = null)
|
||||
array getDescendants(Criteria $c = null)
|
||||
array getBranch(Criteria $c = null)
|
||||
array getAncestors(Criteria $c = null)
|
||||
|
||||
// node insertion methods (require calling save() afterwards)
|
||||
$node addChild($node)
|
||||
$node insertAsFirstChildOf($node)
|
||||
$node insertAsLastChildOf($node)
|
||||
$node insertAsPrevSiblingOf($node)
|
||||
$node insertAsNextSiblingOf($node)
|
||||
|
||||
// node move methods (immediate, no need to save() afterwards)
|
||||
$node moveToFirstChildOf($node)
|
||||
$node moveToLastChildOf($node)
|
||||
$node moveToPrevSiblingOf($node)
|
||||
$node moveToNextSiblingOf($node)
|
||||
|
||||
// deletion methods
|
||||
$node deleteDescendants()
|
||||
|
||||
// only for behavior with method_proxies
|
||||
$node createRoot()
|
||||
$node retrieveParent()
|
||||
$node retrievePrevSibling()
|
||||
$node retrieveNextSibling()
|
||||
$node retrieveFirstChild()
|
||||
$node retrieveLastChild()
|
||||
array getPath()
|
||||
}}}
|
||||
|
||||
The behavior also adds some methods to the Query classes:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// tree filter methods
|
||||
query descendantsOf($node)
|
||||
query branchOf($node)
|
||||
query childrenOf($node)
|
||||
query siblingsOf($node)
|
||||
query ancestorsOf($node)
|
||||
query rootsOf($node)
|
||||
// only for behavior with use_scope
|
||||
query treeRoots()
|
||||
query inTree($scope = null)
|
||||
// order methods
|
||||
query orderByBranch($reverse = false)
|
||||
query orderByLevel($reverse = false)
|
||||
// termination methods
|
||||
$node findRoot($scope = null)
|
||||
coll findTree($scope = null)
|
||||
}}}
|
||||
|
||||
Lastly, the behavior adds a few methods to the Peer classes:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$node retrieveRoot($scope = null)
|
||||
array retrieveTree($scope = null)
|
||||
int deleteTree($scope = null)
|
||||
// only for behavior with use_scope
|
||||
array retrieveRoots(Criteria $c = null)
|
||||
}}}
|
||||
|
||||
== TODO ==
|
||||
|
||||
* InsertAsParentOf
|
|
@ -1,103 +0,0 @@
|
|||
= Query Cache Behavior =
|
||||
|
||||
The `query_cache` behavior gives a speed boost to Propel queries by caching the transformation of a PHP Query object into reusable SQL code.
|
||||
|
||||
== Basic Usage ==
|
||||
|
||||
In the `schema.xml`, use the `<behavior>` tag to add the `query_cache` behavior to a table:
|
||||
{{{
|
||||
#!xml
|
||||
<table name="book">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="query_cache" />
|
||||
</table>
|
||||
}}}
|
||||
|
||||
After you rebuild your model, all the queries on this object can now be cached. To trigger the query cache on a particular query, just give it a query key using the `setQueryKey()` method. The key is a unique identifier that you can choose, later used for cache lookups:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$title = 'War And Peace';
|
||||
$books = BookQuery::create()
|
||||
->setQueryKey('search book by title')
|
||||
->filterByTitle($title)
|
||||
->findOne();
|
||||
}}}
|
||||
|
||||
The first time Propel executes the termination method, it computes the SQL translation of the Query object and stores it into a cache backend (APC by default). Next time you run the same query, it executes faster, even with different parameters:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$title = 'Anna Karenina';
|
||||
$books = BookQuery::create()
|
||||
->setQueryKey('search book by title')
|
||||
->filterByTitle($title)
|
||||
->findOne();
|
||||
}}}
|
||||
|
||||
'''Tip''': The more complex the query, the greater the boost you get from the query cache behavior.
|
||||
|
||||
== Parameters ==
|
||||
|
||||
You can change the cache backend and the cache lifetime (in seconds) by setting the `backend` and `lifetime` parameters:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="book">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="query_cache">
|
||||
<parameter name="backend" value="custom" />
|
||||
<parameter name="lifetime" value="600" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
To implement a custom cache backend, just override the generated `cacheContains()`, `cacheFetch()` and `cacheStore()` methods in the Query object. For instance, to implement query cache using Zend_Cache and memcached, try the following:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
class BookQuery extends BaseBookQuery
|
||||
{
|
||||
public function cacheContains($key)
|
||||
{
|
||||
return $this->getCacheBackend()->test($key);
|
||||
}
|
||||
|
||||
public function cacheFetch($key)
|
||||
{
|
||||
return $this->getCacheBackend()->load($key);
|
||||
}
|
||||
|
||||
public function cacheStore($key, $value)
|
||||
{
|
||||
return $this->getCacheBackend()->save($key, $value);
|
||||
}
|
||||
|
||||
protected function getCacheBackend()
|
||||
{
|
||||
if (self::$cacheBackend === null) {
|
||||
$frontendOptions = array(
|
||||
'lifetime' => 7200,
|
||||
'automatic_serialization' => true
|
||||
);
|
||||
$backendOptions = array(
|
||||
'servers' => array(
|
||||
array(
|
||||
'host' => 'localhost',
|
||||
'port' => 11211,
|
||||
'persistent' => true
|
||||
)
|
||||
)
|
||||
);
|
||||
self::$cacheBackend = Zend_Cache::factory('Core', 'Memcached', $frontendOptions, $backendOptions);
|
||||
}
|
||||
|
||||
return self::$cacheBackend;
|
||||
}
|
||||
}
|
||||
}}}
|
|
@ -1,135 +0,0 @@
|
|||
= Sluggable Behavior =
|
||||
|
||||
The `sluggable` behavior allows a model to offer a human readable identifier that can be used for search engine friendly URLs.
|
||||
|
||||
== Basic Usage ==
|
||||
|
||||
In the `schema.xml`, use the `<behavior>` tag to add the `sluggable` behavior to a table:
|
||||
{{{
|
||||
#!xml
|
||||
<table name="post">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="sluggable" />
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Rebuild your model, insert the table creation sql again, and you're ready to go. The model now has an additional getter for its slug, which is automatically set before the object is saved:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$p1 = new Post();
|
||||
$p1->setTitle('Hello, World!');
|
||||
$p1->save();
|
||||
echo $p1->getSlug(); // 'hello-world'
|
||||
}}}
|
||||
|
||||
By default, the behavior uses the string representation of the object to build the slug. In the example above, the `title` column is defined as `primaryString`, so the slug uses this column as a base string. The string is then cleaned up in order to allow it to appear in a URL. In the process, blanks and special characters are replaced by a dash, and the string is lowercased.
|
||||
|
||||
'''Tip''': The slug is unique by design. That means that if you create a new object and that the behavior calculates a slug that already exists, the string is modified to be unique:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$p2 = new Post();
|
||||
$p2->setTitle('Hello, World!');
|
||||
$p2->save();
|
||||
echo $p2->getSlug(); // 'hello-world-1'
|
||||
}}}
|
||||
|
||||
The generated model query offers a `findOneBySlug()` method to easily retrieve a model object based on its slug:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$p = PostQuery::create()->findOneBySlug('hello-world');
|
||||
}}}
|
||||
|
||||
== Parameters ==
|
||||
|
||||
By default, the behavior adds one columns to the model. If this column is already described in the schema, the behavior detects it and doesn't add it a second time. The behavior parameters allow you to use custom patterns for the slug composition. The following schema illustrates a complete customization of the behavior:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="post">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<column name="url" type="VARCHAR" size="100" />
|
||||
<behavior name="sluggable" />
|
||||
<parameter name="slug_column" value="url" />
|
||||
<parameter name="slug_pattern" value="/posts/{Title}" />
|
||||
<parameter name="replace_pattern" value="/[^\w\/]+/u" />
|
||||
<parameter name="replacement" value="-" />
|
||||
<parameter name="separator" value="/" />
|
||||
<parameter name="permanent" value="true" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Whatever `slug_column` name you choose, the `sluggable` behavior always adds the following proxy methods, which are mapped to the correct column:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$post->getSlug(); // returns $post->url
|
||||
$post->setSlug($slug); // $post->url = $slug
|
||||
}}}
|
||||
|
||||
The `slug_pattern` parameter is the rule used to build the raw slug based on the object properties. Any substring enclosed between brackets '{}' is turned into a getter, so the `Post` class generates slugs as follows:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
protected function createRawSlug()
|
||||
{
|
||||
return '/posts/' . $this->getTitle();
|
||||
}
|
||||
}}}
|
||||
|
||||
Incidentally, that means that you can use names that don't match a real column phpName, as long as your model provides a getter for it.
|
||||
|
||||
The `replace_pattern` parameter is a regular expression that shows all the characters that will end up replaced by the `replacement` parameter. In the above example, special characters like '!' or ':' are replaced by '-', but not letters, digits, nor '/'.
|
||||
|
||||
The `separator` parameter is the character that separates the slug from the incremental index added in case of non-unicity. Set as '/', it makes `Post` objects sharing the same title have the following slugs:
|
||||
|
||||
{{{
|
||||
'posts/hello-world'
|
||||
'posts/hello-world/1'
|
||||
'posts/hello-world/2'
|
||||
...
|
||||
}}}
|
||||
|
||||
A `permanent` slug is not automatically updated when the fields that constitute it change. This is useful when the slug serves as a permalink, that should work even when the model object properties change. Note that you can still manually change the slug in a model using the `permanent` setting by calling `setSlug()`;
|
||||
|
||||
== Further Customization ==
|
||||
|
||||
The slug is generated by the object when it is saved, via the `createSlug()` method. This method does several operations on a simple string:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
protected function createSlug()
|
||||
{
|
||||
// create the slug based on the `slug_pattern` and the object properties
|
||||
$slug = $this->createRawSlug();
|
||||
// truncate the slug to accomodate the size of the slug column
|
||||
$slug = $this->limitSlugSize($slug);
|
||||
// add an incremental index to make sure the slug is unique
|
||||
$slug = $this->makeSlugUnique($slug);
|
||||
|
||||
return $slug;
|
||||
}
|
||||
|
||||
protected function createRawSlug()
|
||||
{
|
||||
// here comes the string composition code, generated according to `slug_pattern`
|
||||
$slug = 'posts/' . $this->cleanupSlugPart($this->getTitle());
|
||||
// cleanupSlugPart() cleans up the slug part
|
||||
// based on the `replace_pattern` and `replacement` parameters
|
||||
|
||||
return $slug;
|
||||
}
|
||||
}}}
|
||||
|
||||
You can override any of these methods in your model class, in order to implement a custom slug logic.
|
|
@ -1,116 +0,0 @@
|
|||
= SoftDelete Behavior =
|
||||
|
||||
The `soft_delete` behavior overrides the deletion methods of a model object to make them 'hide' the deleted rows but keep them in the database. Deleted objects still don't show up on select queries, but they can be retrieved or undeleted when necessary.
|
||||
|
||||
== Basic Usage ==
|
||||
|
||||
In the `schema.xml`, use the `<behavior>` tag to add the `soft_delete` behavior to a table:
|
||||
{{{
|
||||
#!xml
|
||||
<table name="book">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="soft_delete" />
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Rebuild your model, insert the table creation sql again, and you're ready to go. The model now has one new column, `deleted_at`, that stores the deletion date. Select queries don't return the deleted objects:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$b = new Book();
|
||||
$b->setTitle('War And Peace');
|
||||
$b->save();
|
||||
$b->delete();
|
||||
echo $b->isDeleted(); // false
|
||||
echo $b->getDeletedAt(); // 2009-10-02 18:14:23
|
||||
$books = BookQuery::create()->find(); // empty collection
|
||||
}}}
|
||||
|
||||
Behind the curtain, the behavior adds a condition to every SELECT query to return only records where the `deleted_at` column is null. That's why the deleted objects don't appear anymore upon selection.
|
||||
|
||||
You can turn off the query alteration globally by calling the static method `disableSoftDelete()` on the related Query object:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
BookQuery::disableSoftDelete();
|
||||
$books = BookQuery::create()->find();
|
||||
$book = $books[0];
|
||||
echo $book->getTitle(); // 'War And Peace'
|
||||
}}}
|
||||
|
||||
Note that `find()` and other selection methods automatically re-enable the `soft_delete` filter. You can also enable it manually by calling the `enableSoftDelete()` method on Peer objects.
|
||||
|
||||
If you want to recover a deleted object, use the `unDelete()` method:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$book->unDelete();
|
||||
$books = BookQuery::create()->find();
|
||||
$book = $books[0];
|
||||
echo $book->getTitle(); // 'War And Peace'
|
||||
}}}
|
||||
|
||||
If you want to force the real deletion of an object, call the `forceDelete()` method:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$book->forceDelete();
|
||||
echo $book->isDeleted(); // true
|
||||
$books = BookQuery::create()->find(); // empty collection
|
||||
}}}
|
||||
|
||||
The query methods `delete()` and `deleteAll()` also perform a soft deletion, unless you disable the behavior on the peer class:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$b = new Book();
|
||||
$b->setTitle('War And Peace');
|
||||
$b->save();
|
||||
|
||||
BookQuery::create()->delete($b);
|
||||
$books = BookQuery::create()->find(); // empty collection
|
||||
// the rows look deleted, but they are still there
|
||||
BookQuery::disableSoftDelete();
|
||||
$books = BookQuery::create()->find();
|
||||
$book = $books[0];
|
||||
echo $book->getTitle(); // 'War And Peace'
|
||||
|
||||
// To perform a true deletion, disable the softDelete feature
|
||||
BookQuery::disableSoftDelete();
|
||||
BookQuery::create()->delete();
|
||||
// Alternatively, use forceDelete()
|
||||
BookQuery::create()->forceDelete();
|
||||
}}}
|
||||
|
||||
== Parameters ==
|
||||
|
||||
You can change the name of the column added by the behavior by setting the `deleted_column` parameter:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="book">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<column name="my_deletion_date" type="TIMESTAMP" />
|
||||
<behavior name="soft_delete">
|
||||
<parameter name="deleted_column" value="my_deletion_date" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$b = new Book();
|
||||
$b->setTitle('War And Peace');
|
||||
$b->save();
|
||||
$b->delete();
|
||||
echo $b->getMyDeletionDate(); // 2009-10-02 18:14:23
|
||||
$books = BookQuery::create()->find(); // empty collection
|
||||
}}}
|
|
@ -1,285 +0,0 @@
|
|||
= Sortable Behavior =
|
||||
|
||||
The `sortable` behavior allows a model to become an ordered list, and provides numerous methods to traverse this list in an efficient way.
|
||||
|
||||
== Basic Usage ==
|
||||
|
||||
In the `schema.xml`, use the `<behavior>` tag to add the `sortable` behavior to a table:
|
||||
{{{
|
||||
#!xml
|
||||
<table name="task">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="sortable" />
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Rebuild your model, insert the table creation sql again, and you're ready to go. The model now has the ability to be inserted into an ordered list, as follows:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$t1 = new Task();
|
||||
$t1->setTitle('Wash the dishes');
|
||||
$t1->save();
|
||||
echo $t1->getRank(); // 1, the first rank to be given (not 0)
|
||||
$t2 = new Task();
|
||||
$t2->setTitle('Do the laundry');
|
||||
$t2->save();
|
||||
echo $t2->getRank(); // 2
|
||||
$t3 = new Task();
|
||||
$t3->setTitle('Rest a little');
|
||||
$t3->save()
|
||||
echo $t3->getRank(); // 3
|
||||
}}}
|
||||
|
||||
As long as you save new objects, Propel gives them the first available rank in the list.
|
||||
|
||||
Once you have built an ordered list, you can traverse it using any of the methods added by the `sortable` behavior. For instance:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$firstTask = TaskQuery::create()->findOneByRank(1); // $t1
|
||||
$secondTask = $firstTask->getNext(); // $t2
|
||||
$lastTask = $secondTask->getNext(); // $t3
|
||||
$secondTask = $lastTask->getPrevious(); // $t2
|
||||
|
||||
$allTasks = TaskQuery::create()->findList();
|
||||
// => collection($t1, $t2, $t3)
|
||||
$allTasksInReverseOrder = TaskQuery::create()->orderByRank('desc')->find();
|
||||
// => collection($t3, $t2, $t2)
|
||||
}}}
|
||||
|
||||
The results returned by these methods are regular Propel model objects, with access to the properties and related models. The `sortable` behavior also adds inspection methods to objects:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
echo $t2->isFirst(); // false
|
||||
echo $t2->isLast(); // false
|
||||
echo $t2->getRank(); // 2
|
||||
}}}
|
||||
|
||||
== Manipulating Objects In A List ==
|
||||
|
||||
You can move an object in the list using any of the `moveUp()`, `moveDown()`, `moveToTop()`, `moveToBottom()`, `moveToRank()`, and `swapWith()` methods. These operations are immediate and don't require that you save the model afterwards:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// The list is 1 - Wash the dishes, 2 - Do the laundry, 3 - Rest a little
|
||||
$t2->moveToTop();
|
||||
// The list is now 1 - Do the laundry, 2 - Wash the dishes, 3 - Rest a little
|
||||
$t2->moveToBottom();
|
||||
// The list is now 1 - Wash the dishes, 2 - Rest a little, 3 - Do the laundry
|
||||
$t2->moveUp();
|
||||
// The list is 1 - Wash the dishes, 2 - Do the laundry, 3 - Rest a little
|
||||
$t2->swapWith($t1);
|
||||
// The list is now 1 - Do the laundry, 2 - Wash the dishes, 3 - Rest a little
|
||||
$t2->moveToRank(3);
|
||||
// The list is now 1 - Wash the dishes, 2 - Rest a little, 3 - Do the laundry
|
||||
$t2->moveToRank(2);
|
||||
}}}
|
||||
|
||||
By default, new objects are added at the bottom of the list. But you can also insert them at a specific position, using any of the `insertAtTop(), `insertAtBottom()`, and `insertAtRank()` methods. Note that the `insertAtXXX` methods don't save the object:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// The list is 1 - Wash the dishes, 2 - Do the laundry, 3 - Rest a little
|
||||
$t4 = new Task();
|
||||
$t4->setTitle('Clean windows');
|
||||
$t4->insertAtRank(2);
|
||||
$t4->save();
|
||||
// The list is now 1 - Wash the dishes, 2 - Clean Windows, 3 - Do the laundry, 4 - Rest a little
|
||||
}}}
|
||||
|
||||
Whenever you `delete()` an object, the ranks are rearranged to fill the gap:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$t4->delete();
|
||||
// The list is now 1 - Wash the dishes, 2 - Do the laundry, 3 - Rest a little
|
||||
}}}
|
||||
|
||||
'''Tip''': You can remove an object from the list without necessarily deleting it by calling `removeFromList()`. Don't forget to `save()` it afterwards so that the other objects in the lists are rearranged to fill the gap.
|
||||
|
||||
== Multiple Lists ==
|
||||
|
||||
When you need to store several lists for a single model - for instance, one task list for each user - use a ''scope'' for each list. This requires that you enable scope support in the behavior definition by setting the `use_scope` parameter to `true`:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="task">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<column name="user_id" required="true" type="INTEGER" />
|
||||
<foreign-key foreignTable="user" onDelete="cascade">
|
||||
<reference local="user_id" foreign="id" />
|
||||
</foreign-key>
|
||||
<behavior name="sortable">
|
||||
<parameter name="use_scope" value="true" />
|
||||
<parameter name="scope_column" value="user_id" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Now, after rebuilding your model, you can have as many lists as required:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// test users
|
||||
$paul = new User();
|
||||
$john = new User();
|
||||
// now onto the tasks
|
||||
$t1 = new Task();
|
||||
$t1->setTitle('Wash the dishes');
|
||||
$t1->setUser($paul);
|
||||
$t1->save();
|
||||
echo $t1->getRank(); // 1
|
||||
$t2 = new Task();
|
||||
$t2->setTitle('Do the laundry');
|
||||
$t2->setUser($paul);
|
||||
$t2->save();
|
||||
echo $t2->getRank(); // 2
|
||||
$t3 = new Task();
|
||||
$t3->setTitle('Rest a little');
|
||||
$t3->setUser($john);
|
||||
$t3->save()
|
||||
echo $t3->getRank(); // 1, because John has his own task list
|
||||
}}}
|
||||
|
||||
The generated methods now accept a `$scope` parameter to restrict the query to a given scope:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$firstPaulTask = TaskQuery::create()->findOneByRank($rank = 1, $scope = $paul->getId()); // $t1
|
||||
$lastPaulTask = $firstTask->getNext(); // $t2
|
||||
$firstJohnTask = TaskPeer::create()->findOneByRank($rank = 1, $scope = $john->getId()); // $t1
|
||||
}}}
|
||||
|
||||
Models using the sortable behavior with scope benefit from one additional Query methods named `inList()`:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$allPaulsTasks = TaskPeer::create()->inList($scope = $paul->getId())->find();
|
||||
}}}
|
||||
|
||||
== Parameters ==
|
||||
|
||||
By default, the behavior adds one columns to the model - two if you use the scope feature. If these columns are already described in the schema, the behavior detects it and doesn't add them a second time. The behavior parameters allow you to use custom names for the sortable columns. The following schema illustrates a complete customization of the behavior:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="task">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<column name="my_rank_column" required="true" type="INTEGER" />
|
||||
<column name="user_id" required="true" type="INTEGER" />
|
||||
<foreign-key foreignTable="user" onDelete="cascade">
|
||||
<reference local="user_id" foreign="id" />
|
||||
</foreign-key>
|
||||
<behavior name="sortable">
|
||||
<parameter name="rank_column" value="my_rank_column" />
|
||||
<parameter name="use_scope" value="true" />
|
||||
<parameter name="scope_column" value="user_id" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Whatever name you give to your columns, the `sortable` behavior always adds the following proxy methods, which are mapped to the correct column:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$task->getRank(); // returns $task->my_rank_column
|
||||
$task->setRank($rank);
|
||||
$task->getScopeValue(); // returns $task->user_id
|
||||
$task->setScopeValue($scope);
|
||||
}}}
|
||||
|
||||
The same happens for the generated Query object:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$query = TaskQuery::create()->filterByRank(); // proxies to filterByMyRankColumn()
|
||||
$query = TaskQuery::create()->orderByRank(); // proxies to orderByMyRankColumn()
|
||||
$tasks = TaskQuery::create()->findOneByRank(); // proxies to findOneByMyRankColumn()
|
||||
}}}
|
||||
|
||||
'''Tip''': The behavior adds columns but no index. Depending on your table structure, you might want to add a column index by hand to speed up queries on sorted lists.
|
||||
|
||||
== Complete API ==
|
||||
|
||||
Here is a list of the methods added by the behavior to the model objects:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// storage columns accessors
|
||||
int getRank()
|
||||
$object setRank(int $rank)
|
||||
// only for behavior with use_scope
|
||||
int getScopeValue()
|
||||
$object setScopeValue(int $scope)
|
||||
|
||||
// inspection methods
|
||||
bool isFirst()
|
||||
bool isLast()
|
||||
|
||||
// list traversal methods
|
||||
$object getNext()
|
||||
$object getPrevious()
|
||||
|
||||
// methods to insert an object in the list (require calling save() afterwards)
|
||||
$object insertAtRank($rank)
|
||||
$object insertAtBottom()
|
||||
$object insertAtTop()
|
||||
|
||||
// methods to move an object in the list (immediate, no need to save() afterwards)
|
||||
$object moveToRank($rank)
|
||||
$object moveUp()
|
||||
$object moveDown()
|
||||
$object moveToTop()
|
||||
$object moveToBottom()
|
||||
$object swapWith($object)
|
||||
|
||||
// method to remove an object from the list (requires calling save() afterwards)
|
||||
$object removeFromList()
|
||||
}}}
|
||||
|
||||
Here is a list of the methods added by the behavior to the query objects:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
query filterByRank($order, $scope = null)
|
||||
query orderByRank($order, $scope = null)
|
||||
$object findOneByRank($rank, $scope = null)
|
||||
coll findList($scope = null)
|
||||
int getMaxRank($scope = null)
|
||||
bool reorder($newOrder) // $newOrder is a $id => $rank associative array
|
||||
// only for behavior with use_scope
|
||||
array inList($scope)
|
||||
}}}
|
||||
|
||||
The behavior also adds a few methods to the Peer classes:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
int getMaxRank($scope = null)
|
||||
$object retrieveByRank($rank, $scope = null)
|
||||
array doSelectOrderByRank($order, $scope = null)
|
||||
bool reorder($newOrder) // $newOrder is a $id => $rank associative array
|
||||
// only for behavior with use_scope
|
||||
array retrieveList($scope)
|
||||
int countList($scope)
|
||||
int deleteList($scope)
|
||||
}}}
|
|
@ -1,92 +0,0 @@
|
|||
= Timestampable Behavior =
|
||||
|
||||
The `timestampable` behavior allows you to keep track of the date of creation and last update of your model objects.
|
||||
|
||||
== Basic Usage ==
|
||||
|
||||
In the `schema.xml`, use the `<behavior>` tag to add the `timestampable` behavior to a table:
|
||||
{{{
|
||||
#!xml
|
||||
<table name="book">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<behavior name="timestampable" />
|
||||
</table>
|
||||
}}}
|
||||
|
||||
Rebuild your model, insert the table creation sql again, and you're ready to go. The model now has two new columns, `created_at` and `updated_at`, that store a timestamp automatically updated on save:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$b = new Book();
|
||||
$b->setTitle('War And Peace');
|
||||
$b->save();
|
||||
echo $b->getCreatedAt(); // 2009-10-02 18:14:23
|
||||
echo $b->getUpdatedAt(); // 2009-10-02 18:14:23
|
||||
$b->setTitle('Anna Karenina');
|
||||
$b->save();
|
||||
echo $b->getCreatedAt(); // 2009-10-02 18:14:23
|
||||
echo $b->getUpdatedAt(); // 2009-10-02 18:14:25
|
||||
}}}
|
||||
|
||||
The object query also has specific methods to retrieve recent objects and order them according to their update date:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$books = BookQuery::create()
|
||||
->recentlyUpdated() // adds a minimum value for the update date
|
||||
->lastUpdatedFirst() // orders the results by descending update date
|
||||
->find();
|
||||
}}}
|
||||
|
||||
You can use any of the following methods in the object query:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// limits the query to recent objects
|
||||
ModelCriteria recentlyCreated($nbDays = 7)
|
||||
ModelCriteria recentlyUpdated($nbDays = 7)
|
||||
// orders the results
|
||||
ModelCriteria lastCreatedFirst() // order by creation date desc
|
||||
ModelCriteria firstCreatedFirst() // order by creation date asc
|
||||
ModelCriteria lastUpdatedFirst() // order by update date desc
|
||||
ModelCriteria firstUpdatedFirst() // order by update date asc
|
||||
}}}
|
||||
|
||||
'''Tip''': You may need to keep the update date unchanged after an update on the object, for instance when you only update a calculated row. In this case, call the `keepUpdateDateUnchanged()` method on the object before saving it.
|
||||
|
||||
|
||||
== Parameters ==
|
||||
|
||||
You can change the name of the columns added by the behavior by setting the `create_column` and `update_column` parameters:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="book">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<column name="my_create_date" type="TIMESTAMP" />
|
||||
<column name="my_update_date" type="TIMESTAMP" />
|
||||
<behavior name="timestampable">
|
||||
<parameter name="create_column" value="my_create_date" />
|
||||
<parameter name="update_column" value="my_update_date" />
|
||||
</behavior>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$b = new Book();
|
||||
$b->setTitle('War And Peace');
|
||||
$b->save();
|
||||
echo $b->getMyCreateDate(); // 2009-10-02 18:14:23
|
||||
echo $b->getMyUpdateDate(); // 2009-10-02 18:14:23
|
||||
$b->setTitle('Anna Karenina');
|
||||
$b->save();
|
||||
echo $b->getMyCreateDate(); // 2009-10-02 18:14:23
|
||||
echo $b->getMyUpdateDate(); // 2009-10-02 18:14:25
|
||||
}}}
|
|
@ -1,34 +0,0 @@
|
|||
<project name="propel-docs" default="phpdoc">
|
||||
|
||||
<property name="runtime.dir" value="../runtime" />
|
||||
<property name="generator.dir" value="../generator" />
|
||||
|
||||
<target name="phpdoc">
|
||||
<phingcall target="phpdoc-runtime"/>
|
||||
<phingcall target="phpdoc-generator"/>
|
||||
</target>
|
||||
|
||||
<target name="phpdoc-runtime" description="build runtime docs">
|
||||
<phpdoc title="Propel Runtime" destdir="api/runtime" sourcecode="yes" output="HTML:Smarty:PHP">
|
||||
<fileset dir="${runtime.dir}/lib">
|
||||
<include name="**/*.php" />
|
||||
</fileset>
|
||||
</phpdoc>
|
||||
</target>
|
||||
|
||||
<target name="phpdoc-generator" description="build generator docs">
|
||||
<phpdoc title="Propel Generator" destdir="api/generator" sourcecode="yes" output="HTML:Smarty:PHP">
|
||||
<fileset dir="${generator.dir}/lib">
|
||||
<include name="**/*.php" />
|
||||
</fileset>
|
||||
<!--
|
||||
<projdocfileset dir="${generator.dir}">
|
||||
<include name="README" />
|
||||
<include name="INSTALL" />
|
||||
<include name="CHANGELOG" />
|
||||
</projdocfileset>
|
||||
-->
|
||||
</phpdoc>
|
||||
</target>
|
||||
|
||||
</project>
|
|
@ -1,34 +0,0 @@
|
|||
= Adding Additional SQL Files =
|
||||
|
||||
In many cases you may wish to have the ''insert-sql'' task perform additional SQL operations (e.g. add views, stored procedures, triggers, sample data, etc.). Rather than have to run additional SQL statements yourself every time you re-build your object model, you can have the Propel generator do this for you.
|
||||
|
||||
== 1. Create the SQL DDL files ==
|
||||
|
||||
Create any additional SQL files that you want executed against the database (after the base ''schema.sql'' file is applied).
|
||||
|
||||
For example, if we wanted to add a default value to a column that was unsupported in the schema (e.g. where value is a SQL function):
|
||||
|
||||
{{{
|
||||
#!sql
|
||||
-- (for postgres)
|
||||
ALTER TABLE my_table ALTER COLUMN my_column SET DEFAULT CURRENT_TIMESTAMP;
|
||||
}}}
|
||||
|
||||
Now we save that as '''my_column-default.sql''' in the same directory as the generated '''schema.sql''' file (usually in projectdir/build/sql/).
|
||||
|
||||
== 2. Tell Propel Generator about the new file ==
|
||||
|
||||
In that same directory (where your '''schema.sql''' is located), there is a '''sqldb.map''' file which contains a mapping of SQL DDL files to the database that they should be executed against. After running the propel generator, you will probably have a single entry in that file that looks like:
|
||||
|
||||
{{{
|
||||
schema.sql=your-db-name
|
||||
}}}
|
||||
|
||||
We want to simply add the new file we created to this file (future builds will preserve anything you add to this file). When we're done, the file will look like this:
|
||||
|
||||
{{{
|
||||
schema.sql=your-db-name
|
||||
my_column-default.sql=your-db-name
|
||||
}}}
|
||||
|
||||
Now when you execute the ''insert-sql'' Propel generator target, the '''my_column-default.sql''' file will be executed against the ''your-db-name'' database.
|
|
@ -1,47 +0,0 @@
|
|||
= Copying Persisted Objects =
|
||||
|
||||
Propel provides the {{{copy()}}} method to perform copies of mapped row in the database. Note that Propel does '''not''' override the {{{__clone()}}} method; this allows you to create local duplicates of objects that map to the same persisted database row (should you need to do this).
|
||||
|
||||
The {{{copy()}}} method by default performs shallow copies, meaning that any foreign key references will remain the same.
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
|
||||
$a = new Author();
|
||||
$a->setFirstName("Aldous");
|
||||
$a->setLastName("Huxley");
|
||||
|
||||
$p = new Publisher();
|
||||
$p->setName("Harper");
|
||||
|
||||
$b = new Book();
|
||||
$b->setTitle("Brave New World");
|
||||
$b->setPublisher($p);
|
||||
$b->setAuthor($a);
|
||||
|
||||
$b->save(); // so that auto-increment IDs are created
|
||||
|
||||
$bcopy = $b->copy();
|
||||
var_export($bcopy->getId() == $b->getId()); // FALSE
|
||||
var_export($bcopy->getAuthorId() == $b->getAuthorId()); // TRUE
|
||||
var_export($bcopy->getAuthor() === $b->getAuthor()); // TRUE
|
||||
?>
|
||||
}}}
|
||||
|
||||
== Deep Copies ==
|
||||
|
||||
By calling {{{copy()}}} with a {{{TRUE}}} parameter, Propel will create a deep copy of the object; this means that any related objects will also be copied.
|
||||
|
||||
To continue with example from above:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
|
||||
$bdeep = $b->copy(true);
|
||||
var_export($bcopy->getId() == $b->getId()); // FALSE
|
||||
var_export($bcopy->getAuthorId() == $b->getAuthorId()); // FALSE
|
||||
var_export($bcopy->getAuthor() === $b->getAuthor()); // FALSE
|
||||
?>
|
||||
}}}
|
|
@ -1,153 +0,0 @@
|
|||
= Customizing Build =
|
||||
It is possible to customize the Propel build process by overriding values in your propel __build.properties__ file. For maximum flexibility, you can even create your own Phing __build.xml__ file.
|
||||
|
||||
== Customizing the build.properties ==
|
||||
The easiest way to customize your Propel build is to simply specify build properties in your project's __build.properties__ file.
|
||||
|
||||
=== Understanding Phing build properties ===
|
||||
''Properties'' are essentially variables. These variables can be specified on the commandline or in ''properties files''.
|
||||
|
||||
For example, here's how a property might be specified on the commandline:
|
||||
{{{
|
||||
$> phing -Dpropertyname=value
|
||||
}}}
|
||||
|
||||
More typically, properties are stored in files and loaded by Phing. For those not familiar with Java properties files, these files look like PHP INI files; the main difference is that values in properties files can be references to other properties (a feature that will probably exist in in INI files in PHP 5.1).
|
||||
|
||||
'''Importantly:''' properties, once loaded, are not overridden by properties with the same name unless explicitly told to do so. In the Propel build process, the order of precedence for property values is as follows:
|
||||
1. Commandline properties
|
||||
1. Project __build.properties__
|
||||
1. Top-level __build.properties__
|
||||
1. Top-level __default.properties__
|
||||
|
||||
This means, for example, that values specified in the project's __build.properties__ files will override those in the top-level __build.properties__ and __default.properties__ files.
|
||||
|
||||
=== Changing values ===
|
||||
To get an idea of what you can modify in Propel, simply look through the __build.properties__ and __default.properties__ files.
|
||||
|
||||
''Note, however, that some of the current values exist for legacy reasons and will be cleaned up in Propel 1.1.''
|
||||
|
||||
==== New build output directories ====
|
||||
This can easily be customized on a project-by-project basis. For example, here is a __build.properties__ file for the ''bookstore ''project that puts the generated classes in __/var/www/bookstore/classes__ and puts the generated SQL in __/var/www/bookstore/db/sql__:
|
||||
{{{
|
||||
propel.project = bookstore
|
||||
propel.database = sqlite
|
||||
propel.database.url = sqlite://localhost/./test/bookstore.db
|
||||
propel.targetPackage = bookstore
|
||||
|
||||
# directories
|
||||
prope.output.dir = /var/www/bookstore
|
||||
propel.php.dir = ${propel.output.dir}/classes
|
||||
propel.phpconf.dir = ${propel.output.dir}/conf
|
||||
propel.sql.dir = ${propel.output.dir}/db/sql
|
||||
}}}
|
||||
|
||||
The ''targetPackage'' property is also used in determining the path of the generated classes. In the example above, the __Book.php__ class will be located at __/var/www/bookstore/classes/bookstore/Book.php__. You can change this __bookstore__ subdir by altering the ''targetPackage'' property:
|
||||
{{{
|
||||
propel.targetPackage = propelom
|
||||
}}}
|
||||
|
||||
Now the class will be located at __/var/www/bookstore/classes/propelom/Book.php__
|
||||
|
||||
''Note that you can override the targetPackage property by specifying a package="" attribute in the <database> tag or even the <table> tag of the schema.xml.''
|
||||
|
||||
== Creating a custom build.xml file ==
|
||||
|
||||
If you want to make more major changes to the way the build script works, you can setup your own Phing build script. This actually is not a very scary task, and once you've managed to create a Phing build script, you'll probably want to create build targets for other aspects of your project (e.g. running batch unit tests is now supported in Phing 2.1-CVS).
|
||||
|
||||
To start with, I suggest taking a look at the __build-propel.xml__ script (the build.xml script is just a wrapper script). Note, however, that the __build-propel.xml__ script does a lot & has a lot of complexity that is designed to make it easy to configure using properties (so, don't be scared).
|
||||
|
||||
Without going into too much detail about how Phing works, the important thing is that Phing build scripts XML and they are grouped into ''targets'' which are kinda like functions. The actual work of the scripts is performed by ''tasks'', which are PHP5 classes that extend the base Phing ''Task'' class and implement its abstract methods. Propel provides some Phing tasks that work with templates to create the object model.
|
||||
|
||||
=== Step 1: register the needed tasks ===
|
||||
|
||||
The Propel tasks must be registered so that Phing can find them. This is done using the ''<taskdef>'' tag. You can see this near the top of the __build-propel.xml__ file.
|
||||
|
||||
For example, here is how we register the ''propel-om'' task, which is the task that creates the PHP classes for your object model:
|
||||
{{{
|
||||
<taskdef
|
||||
name="propel-om"
|
||||
classname="propel.phing.PropelOMTask"/>
|
||||
}}}
|
||||
|
||||
Simple enough. Phing will now associate the ''<propel-data-model>'' tag with the ''PropelOMTask'' class, which it expects to find at __propel/phing/PropelOMTask.php__ (on your ''include_path''). If Propel generator classes are not on your ''include_path'', you can specify that path in your ''<taskdef>'' tag:
|
||||
{{{
|
||||
<taskdef
|
||||
name="propel-om"
|
||||
classname="propel.phing.PropelOMTask"
|
||||
classpath="/path/to/propel-generator/classes"/>
|
||||
}}}
|
||||
|
||||
Or, for maximum re-usability, you can create a ''<path>'' object, and then reference it (this is the way __build-propel.xml__ does it):
|
||||
{{{
|
||||
<path id="propelclasses">
|
||||
<pathelement dir="/path/to/propel-generator/classes"/>
|
||||
</path>
|
||||
|
||||
<taskdef
|
||||
name="propel-om"
|
||||
classname="propel.phing.PropelOMTask"
|
||||
classpathRef="propelclasses"/>
|
||||
}}}
|
||||
|
||||
=== Step 2: invoking the new task ===
|
||||
|
||||
Now that the ''<propel-om>'' task has been registered with Phing, it can be invoked in your build file.
|
||||
{{{
|
||||
<propel-om
|
||||
outputDirectory="/var/www/bookstore/classes"
|
||||
targetDatabase="mysql"
|
||||
targetPackage="bookstore"
|
||||
templatePath="/path/to/propel-generator/templates"
|
||||
targetPlatform="php5">
|
||||
<schemafileset dir="/var/www/bookstore/db/model" includes="*schema.xml"/>
|
||||
</propel-om>
|
||||
}}}
|
||||
|
||||
In the example above, it's worth pointing out that the ''<propel-om>'' task can actually transform multiple __schema.xml__ files, which is why there is a ''<schemafileset>'' sub-element. Phing ''filesets'' are beyond the scope of this HOWTO, but hopefully the above example is obvious enough.
|
||||
|
||||
=== Step 3: putting it together into a build.xml file ===
|
||||
|
||||
Now that we've seen the essential elements of our custom build file, it's time to look at how to assemble them into a working whole:
|
||||
{{{
|
||||
<?xml version="1.0">
|
||||
<project name="propel" default="om">
|
||||
|
||||
<!-- set properties we use later -->
|
||||
<property name="propelgen.home" value="/path/to/propel-generator"/>
|
||||
<property name="out.dir" value="/var/www/bookstore"/>
|
||||
|
||||
<!-- register task -->
|
||||
<path id="propelclasses">
|
||||
<pathelement dir="${propelgen.home}/classes"/>
|
||||
</path>
|
||||
|
||||
<taskdef
|
||||
name="propel-om"
|
||||
classname="propel.phing.PropelOMTask"
|
||||
classpathRef="propelclasses"/>
|
||||
|
||||
|
||||
<!-- this [default] target performs the work -->
|
||||
<target name="om" description="build propel om">
|
||||
<propel-om
|
||||
outputDirectory="${out.dir}/classes"
|
||||
targetDatabase="mysql"
|
||||
targetPackage="bookstore"
|
||||
templatePath="${propelgen.home}/templates"
|
||||
targetPlatform="php5">
|
||||
<schemafileset dir="${out.dir}/db/model" includes="*schema.xml"/>
|
||||
</propel-om>
|
||||
</target>
|
||||
|
||||
</project>
|
||||
}}}
|
||||
|
||||
If that build script was named __build.xml__ then it could be executed by simply running ''phing'' in the directory where it is located:
|
||||
{{{
|
||||
$> phing om
|
||||
}}}
|
||||
|
||||
Actually, specifying the ''om'' target is not necessary since it is the default.
|
||||
|
||||
Refer to the __build-propel.xml__ file for examples of how to use the other Propel Phing tasks -- e.g. ''<propel-sql>'' for generating the DDL SQL, ''<propel-sql-exec>'' for inserting the SQL, etc.
|
|
@ -1,95 +0,0 @@
|
|||
= Working With Existing Databases =
|
||||
|
||||
The following topics are targeted for developers who already have a working database solution in place, but would like to use Propel to work with the data. For this case, Propel provides a number of command-line utilities helping with migrations of data and data structures.
|
||||
|
||||
== Working with Database Structures ==
|
||||
|
||||
Propel uses an abstract XML schema file to represent databases (the [wiki:Documentation/1.5/Schema schema]). Propel builds the SQL specific to a database based on this schema. Propel also provides a way to reverse-engineer the generic schema file based on database metadata.
|
||||
|
||||
=== Creating an XML Schema from a DB Structure ===
|
||||
|
||||
To generate a schema file, create a new directory for your project & specify the connection information in your `build.properties` file for that project. For example, to create a new project, `legacyapp`, follow these steps:
|
||||
|
||||
1. Create the `legacyapp` project directory anywhere on your filesystem:
|
||||
{{{
|
||||
> mkdir legacyapp
|
||||
> cd legacyapp
|
||||
}}}
|
||||
1. Create a `build.properties` file in `legacyapp/` directory with the DB connection parameters for your existing database, e.g.:
|
||||
{{{
|
||||
propel.project = legacyapp
|
||||
|
||||
# The Propel driver to use for generating SQL, etc.
|
||||
propel.database = mysql
|
||||
|
||||
# This must be a PDO DSN
|
||||
propel.database.url = mysql:dbname=legacyapp
|
||||
propel.database.user = root
|
||||
# propel.database.password =
|
||||
}}}
|
||||
1. Run the `reverse` task to generate the `schema.xml`:
|
||||
{{{
|
||||
> propel-gen reverse
|
||||
}}}
|
||||
1. Pay attention to any errors/warnings issued by Phing during the task execution and then examine the generated `schema.xml` file to make any corrections needed.
|
||||
1. '''You're done! ''' Now you have a `schema.xml` file in the `legacyapp/` project directory. You can now run the default Propel build to generate all the classes.
|
||||
|
||||
The generated `schema.xml` file should be used as a guide, not a final answer. There are some datatypes that Propel may not be familiar with; also some datatypes are simply not supported by Propel (e.g. arrays in PostgreSQL). Unfamiliar datatypes will be reported as warnings and substituted with a default VARCHAR datatype.
|
||||
|
||||
Tip: The reverse engineering classes may not be able to provide the same level of detail for all databases. In particular, metadata information for SQLite is often very basic since SQLite is a typeless database.
|
||||
|
||||
=== Migrating Structure to a New RDBMS ===
|
||||
|
||||
Because Propel has both the ability to create XML schema files based on existing database structures and to create RDBMS-specific DDL SQL from the XML schema file, you can use Propel to convert one database into another.
|
||||
|
||||
To do this you would simply:
|
||||
1. Follow the steps above to create the `schema.xml` file from existing db.
|
||||
1. Then you would change the target database type and specify connection URL for new database in the project's `build.properties` file:
|
||||
{{{
|
||||
propel.database = pgsql
|
||||
propel.database.url = pgsql://unix+localhost/newlegacyapp
|
||||
}}}
|
||||
1. And then run the `sql` task to generate the new DDL:
|
||||
{{{
|
||||
> propel-gen sql
|
||||
}}}
|
||||
1. And (optionally) the `insert-sql` task to create the new database:
|
||||
{{{
|
||||
> propel-gen insert-sql
|
||||
}}}
|
||||
|
||||
== Working with Database Data ==
|
||||
|
||||
Propel also provides several tasks to facilitate data import/export. The most important of these are `datadump` and `datasql`. The first dumps data to XML and the second converts the XML data dump to a ready-to-insert SQL file.
|
||||
|
||||
Tip: Both of these tasks require that you already have generated the `schema.xml` for your database.
|
||||
|
||||
=== Dumping Data to XML ===
|
||||
|
||||
Once you have created (or reverse-engineered) your `schema.xml` file, you can run the `datadump` task to dump data from the database into a `data.xml` file.
|
||||
|
||||
{{{
|
||||
> propel-gen datadump
|
||||
}}}
|
||||
|
||||
The task transfers database records to XML using a simple format, where each row is an element, and each column is an attribute. So for instance, the XML representation of a row in a `publisher` table:
|
||||
|
||||
||'''publisher_id'''||'''name'''||
|
||||
||1||William Morrow||
|
||||
|
||||
... is rendered in the `data.xml` as follows:
|
||||
{{{
|
||||
<dataset name="all">
|
||||
...
|
||||
<Publisher PublisherId="1" Name="William Morrow"/>
|
||||
...
|
||||
</dataset>
|
||||
}}}
|
||||
|
||||
=== Creating SQL from XML ===
|
||||
|
||||
To create the SQL files from the XML, run the `datasql` task:
|
||||
{{{
|
||||
> propel-gen datasql
|
||||
}}}
|
||||
The generated SQL is placed in the `build/sql/` directory and will be inserted when you run the `insert-sql` task.
|
|
@ -1,73 +0,0 @@
|
|||
= Working with LOB Columns =
|
||||
|
||||
Propel uses PHP streams internally for storing ''Binary'' Locator Objects (BLOBs). This choice was made because PDO itself uses streams as a convention when returning LOB columns in a resultset and when binding values to prepared statements. Unfortunately, not all PDO drivers support this (see, for example, http://bugs.php.net/bug.php?id=40913); in those cases, Propel creates a {{{php://temp}}} stream to hold the LOB contents and thus provide a consistent API.
|
||||
|
||||
Note that CLOB (''Character'' Locator Objects) are treated as strings in Propel, as there is no convention for them to be treated as streams by PDO.
|
||||
|
||||
== Getting BLOB Values ==
|
||||
|
||||
BLOB values will be returned as PHP stream resources from the accessor methods. Alternatively, if the value is NULL in the database, then the accessors will return the PHP value NULL.
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$media = MediaPeer::retrieveByPK(1);
|
||||
$fp = $media->getCoverImage();
|
||||
if ($fp !== null) {
|
||||
echo stream_get_contents($fp);
|
||||
}
|
||||
}}}
|
||||
|
||||
== Setting BLOB Values ==
|
||||
|
||||
When setting a BLOB column, you can either pass in a stream or the blob contents.
|
||||
|
||||
=== Setting using a stream ===
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
|
||||
$fp = fopen("/path/to/file.ext", "rb");
|
||||
|
||||
$media = new Media();
|
||||
$media->setCoverImage($fp);
|
||||
}}}
|
||||
|
||||
=== Setting using file contents ===
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
|
||||
$media = new Media();
|
||||
$media->setCoverImage(file_get_contents("/path/to/file.ext"));
|
||||
}}}
|
||||
|
||||
Regardless of which setting method you choose, the BLOB will always be represented internally as a stream resource -- ''and subsequent calls to the accessor methods will return a stream.''
|
||||
|
||||
For example:
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
|
||||
$media = new Media();
|
||||
$media->setCoverImage(file_get_contents("/path/to/file.ext"));
|
||||
|
||||
$fp = $media->getCoverImage();
|
||||
print gettype($fp); // "resource"
|
||||
}}}
|
||||
|
||||
=== Setting BLOB columns and isModified() ===
|
||||
|
||||
Note that because a stream contents may be externally modified, ''mutator methods for BLOB columns will always set the '''isModified()''' to report true'' -- even if the stream has the same identity as the stream that was returned.
|
||||
|
||||
For example:
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
|
||||
$media = MediaPeer::retrieveByPK(1);
|
||||
$fp = $media->getCoverImage();
|
||||
$media->setCoverImage($fp);
|
||||
|
||||
var_export($media->isModified()); // TRUE
|
||||
}}}
|
|
@ -1,94 +0,0 @@
|
|||
= Replication =
|
||||
|
||||
Propel can be used in a master-slave replication environment. These environments are set up to improve the performance of web applications by dispatching the database-load to multiple database-servers. While a single master database is responsible for all write-queries, multiple slave-databases handle the read-queries. The slaves are synchronised with the master by a fast binary log (depending on the database).
|
||||
|
||||
== Configuring Propel for Replication ==
|
||||
|
||||
* Set up a replication environment (see the Databases section below)
|
||||
* Use the latest Propel-Version from SVN
|
||||
* add a slaves-section to your {{{runtime-conf.xml}}} file
|
||||
* verify the correct setup by checking the masters log file (should not contain "select ..." statements)
|
||||
|
||||
You can configure Propel to support replication by adding a <slaves> element with nested <connection> element(s) to your {{{runtime-conf.xml}}}.
|
||||
|
||||
The <slaves> section is at the same level as the master <connection> and contains multiple nested <connection> elements with the same information as the top-level (master) <connection>. It is recommended that they are numbered. The follwing example shows a slaves section with a several slave connections configured where "localhost" is the master and "slave-server1" and "slave-server2" are the slave-database connections.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<?xml version="1.0"?>
|
||||
<config>
|
||||
<log>
|
||||
<ident>propel-bookstore</ident>
|
||||
<name>console</name>
|
||||
<level>7</level>
|
||||
</log>
|
||||
<propel>
|
||||
<datasources default="bookstore">
|
||||
<datasource id="bookstore">
|
||||
<adapter>sqlite</adapter>
|
||||
<connection>
|
||||
<dsn>mysql:host=localhost;dbname=bookstore</dsn>
|
||||
<user>testuser</user>
|
||||
<password>password</password>
|
||||
</connection>
|
||||
<slaves>
|
||||
<connection>
|
||||
<dsn>mysql:host=slave-server1; dbname=bookstore</dsn>
|
||||
<user>testuser</user>
|
||||
<password>password</password>
|
||||
</connection>
|
||||
<connection>
|
||||
<dsn>mysql:host=slave-server2; dbname=bookstore</dsn>
|
||||
<user>testuser</user>
|
||||
<password>password</password>
|
||||
</connection>
|
||||
</slaves>
|
||||
</datasource>
|
||||
</datasources>
|
||||
</propel>
|
||||
</config>
|
||||
}}}
|
||||
|
||||
== Implementation ==
|
||||
|
||||
The replication functionality is implemented in the Propel connection configuration and initialization code and in the generated Peer and Object classes.
|
||||
|
||||
=== Propel::getConnection() ===
|
||||
|
||||
When requesting a connection from Propel ('''Propel::getConnection()'''), you can either specify that you want a READ connection (slave) or WRITE connection (master). Methods that are designed to perform READ operations, like the '''doSelect*()''' methods of your generated Peer classes, will always request a READ connection like so:
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
|
||||
$con = Propel::getConnection(MyPeer::DATABASE_NAME, Propel::CONNECTION_READ);
|
||||
}}}
|
||||
Other methods that are designed to perform write operations will explicitly request a Propel::CONNECTION_WRITE connection. The WRITE connections are also the default, however, so applications that make a call to '''Propel::getConnection()''' without specifying a connection mode will always get a master connection.
|
||||
|
||||
If you do have configured slave connections, Propel will choose a single random slave to use per request for any connections where the mode is Propel::CONNECTION_READ.
|
||||
|
||||
Both READ (slave) and WRITE (master) connections are only configured on demand. If all of your SQL statements are SELECT queries, Propel will never create a connection to the master database (unless, of course, you have configured Propel to always use the master connection -- see below).
|
||||
|
||||
'''Important:''' if you are using Propel to execute custom SQL queries in your application (and you want to make sure that Propel respects your replication setup), you will need to explicitly get the correct connection. For example:
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
|
||||
$con = Propel::getConnection(MyPeer::DATABASE_NAME, Propel::CONNECTION_READ);
|
||||
$stmt = $con->query('SELECT * FROM my');
|
||||
/* ... */
|
||||
}}}
|
||||
|
||||
=== Propel::setForceMasterConnection() ===
|
||||
|
||||
You can force Propel to always return a WRITE (master) connection from '''Propel::getConnection()''' by calling '''Propel::setForceMasterConnection(true);'''. This can be useful if you must be sure that you are getting the most up-to-date data (i.e. if there is some latency possible between master and slaves).
|
||||
|
||||
== Databases ==
|
||||
|
||||
=== MySql ===
|
||||
|
||||
http://dev.mysql.com/doc/refman/5.0/en/replication-howto.html
|
||||
|
||||
== References ==
|
||||
|
||||
* Henderson Carl (2006): Building Scalable Web Sites. The Flickr Way. O'Reilly. ISBN-596-10235-6.
|
||||
|
|
@ -1,297 +0,0 @@
|
|||
= Multi-Component Data Model =
|
||||
|
||||
Propel comes along with packaging capabilities that allow you to more easily integrate Propel into a packaged or modularized application.
|
||||
|
||||
== Muliple Schemas ==
|
||||
|
||||
You can use as many `schema.xml` files as you want. Schema files have to be named `(*.)schema.xml`, so names like `schema.xml`, `package1.schema.xml`, `core.package1.schema.xml` are all acceptable. These files ''have'' to be located in your project directory.
|
||||
|
||||
Each schema file has to contain a `<database>` element with a `name` attribute. This name references the connection settings to be used for this database (and configured in the `runtime-conf.xml`), so separated schemas can share a common database name.
|
||||
|
||||
Whenever you call a propel build taks, Propel will consider all these schema files and build the classes (or the SQL) for all the tables.
|
||||
|
||||
== Understanding Packages ==
|
||||
|
||||
In Propel, a ''package'' represents a group of models. This is a convenient way to organize your code in a modularized way, since classes and SQL files of a given package are be grouped together and separated from the other packages. By carefully choosing the package of each model, applications end up in smaller, independent modules that are easier to manage.
|
||||
|
||||
=== Package Cascade ===
|
||||
|
||||
The package is defined in a configuration cascade. You can set it up for the whole project, for all the tables of a schema, or for a single table.
|
||||
|
||||
For the whole project, the main package is set in the `build.properties`:
|
||||
|
||||
{{{
|
||||
#!ini
|
||||
propel.targetPackage = my_project
|
||||
}}}
|
||||
|
||||
By default, all the tables of all the schemas in the project use this package. However, you can override the package for a given `<database>` by setting its `package` attribute:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<!-- in author.schema.xml -->
|
||||
<database package="author" name="bookstore">
|
||||
<table name="author">
|
||||
<!-- author columns -->
|
||||
</table>
|
||||
</database>
|
||||
|
||||
<!-- in book.schema.xml -->
|
||||
<database package="book" name="bookstore">
|
||||
<table name="book">
|
||||
<!-- book columns -->
|
||||
</table>
|
||||
<table name="review">
|
||||
<!-- review columns -->
|
||||
</table>
|
||||
</database>
|
||||
}}}
|
||||
|
||||
In this example, thanks to the `package` attribute, the tables are grouped into the following packages:
|
||||
|
||||
* `my_project.author` package: `author` table
|
||||
* `my_project.book` package: `book` and `review` tables
|
||||
|
||||
'''Warning''': If you separate tables related by a foreign key into separate packages (like `book` and `author` in this example), you must enable the `packageObjectModel` build property to let Propel consider other packages for relations.
|
||||
|
||||
You can also override the `package` attribute at the `<table>` element level.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<!-- in author.schema.xml -->
|
||||
<database package="author" name="bookstore">
|
||||
<table name="author">
|
||||
<!-- author columns -->
|
||||
</table>
|
||||
</database>
|
||||
|
||||
<!-- in book.schema.xml -->
|
||||
<database package="book" name="bookstore">
|
||||
<table name="book">
|
||||
<!-- book columns -->
|
||||
</table>
|
||||
<table name="review" package="review">
|
||||
<!-- review columns -->
|
||||
</table>
|
||||
</database>
|
||||
}}}
|
||||
|
||||
This ends up in the following package:
|
||||
|
||||
* `my_project.author` package: `author` table
|
||||
* `my_project.book` package: `book` table
|
||||
* `my_project.review` package: `review` table
|
||||
|
||||
Notice that tables can end up in separated packages even though they belong to the same schema file.
|
||||
|
||||
'''Tip''': You can use dots in a package name to add more package levels.
|
||||
|
||||
=== Packages and Generated Model Files ===
|
||||
|
||||
The `package` attribute of a table translates to the directory in which Propel generates the Model classes for this table.
|
||||
|
||||
For instance, if no `package` attribute is defined at the database of table level, Propel places all classes according to the `propel.targetPackage` from the `build.properties`:
|
||||
|
||||
{{{
|
||||
build/
|
||||
classes/
|
||||
my_project/
|
||||
om/
|
||||
map/
|
||||
Author.php
|
||||
AuthorPeer.php
|
||||
AuthorQuery.php
|
||||
Book.php
|
||||
BookPeer.php
|
||||
BookQuery.php
|
||||
Review.php
|
||||
ReviewPeer.php
|
||||
ReviewQuery.php
|
||||
}}}
|
||||
|
||||
You can further tweak the location where Propel puts the created files by changing the `propel.output.dir` build property. By default this property is set to:
|
||||
|
||||
{{{
|
||||
#!ini
|
||||
propel.output.dir = ${propel.project.dir}/build
|
||||
}}}
|
||||
|
||||
You can change it to use any other directory as your build directory.
|
||||
|
||||
If you set up packages for `<database>` elements, Propel splits up the generated model classes into subdirectories named after the package attribute:
|
||||
|
||||
{{{
|
||||
build/
|
||||
classes/
|
||||
my_project/
|
||||
author/
|
||||
om/
|
||||
map/
|
||||
Author.php
|
||||
AuthorPeer.php
|
||||
AuthorQuery.php
|
||||
book/
|
||||
om/
|
||||
map/
|
||||
Book.php
|
||||
BookPeer.php
|
||||
BookQuery.php
|
||||
Review.php
|
||||
ReviewPeer.php
|
||||
ReviewQuery.php
|
||||
}}}
|
||||
|
||||
And of course, if you specialize the `package` attribute per table, you can have one table use its own package:
|
||||
|
||||
{{{
|
||||
build/
|
||||
classes/
|
||||
my_project/
|
||||
author/
|
||||
om/
|
||||
map/
|
||||
Author.php
|
||||
AuthorPeer.php
|
||||
AuthorQuery.php
|
||||
book/
|
||||
om/
|
||||
map/
|
||||
Book.php
|
||||
BookPeer.php
|
||||
BookQuery.php
|
||||
review/
|
||||
om/
|
||||
map/
|
||||
Review.php
|
||||
ReviewPeer.php
|
||||
ReviewQuery.php
|
||||
}}}
|
||||
|
||||
=== Packages And SQL Files ===
|
||||
|
||||
Propel also considers packages for SQL generation. In practice, Propel generates one SQL file per package. Each file contains the CREATE TABLE SQL statements necessary to create all the tables of a given package.
|
||||
|
||||
So by default, all the tables end up in a single SQL file:
|
||||
|
||||
{{{
|
||||
build/
|
||||
sql/
|
||||
schema.sql
|
||||
}}}
|
||||
|
||||
If you specialize the `package` for each `<database>` element, Propel uses it for SQL files:
|
||||
|
||||
{{{
|
||||
build/
|
||||
sql/
|
||||
author.schema.sql // contains CREATE TABLE author
|
||||
book.schema.sql // contains CREATE TABLE book and CREATE TABLE review
|
||||
}}}
|
||||
|
||||
And, as you probably expect it, a package overridden at the table level also accounts for an independent SQL file:
|
||||
|
||||
{{{
|
||||
build/
|
||||
sql/
|
||||
author.schema.sql // contains CREATE TABLE author
|
||||
book.schema.sql // contains CREATE TABLE book
|
||||
review.schema.sql // contains CREATE TABLE review
|
||||
}}}
|
||||
|
||||
== Understanding The packageObjectModel Build Property ==
|
||||
|
||||
The `propel.packageObjectModel` build property enables the "packaged" build process. This modifies the build tasks behavior by joining `<database>` elements of the same name - but keeping their packages separate. That allows to split a large schema into several files, regardless of foreign key dependencies, since Propel will join all schemas using the same database name.
|
||||
|
||||
To switch this on, simply add the following line to the `build.properties` file in your project directory:
|
||||
{{{
|
||||
propel.packageObjectModel = true
|
||||
}}}
|
||||
|
||||
== The Bookstore Packaged Example ==
|
||||
|
||||
In the bookstore-packaged example you'll find the following schema files:
|
||||
|
||||
* author.schema.xml
|
||||
* book.schema.xml
|
||||
* club.schema.xml
|
||||
* media.schema.xml
|
||||
* publisher.schema.xml
|
||||
* review.schema.xml
|
||||
* log.schema.xml
|
||||
|
||||
Each schema file has to contain a `<database>` tag that has its `package` attribute set to the package name where ''all'' of the tables in this schema file/database belong to.
|
||||
|
||||
For example, in the bookstore-packaged example the `author.schema.xml` contains the following `<database>` tag:
|
||||
|
||||
{{{
|
||||
<database package="core.author" name="bookstore" [...]>
|
||||
}}}
|
||||
|
||||
That means, that the Author OM classes will be created in a subdirectory `core/author/` of the build output directory.
|
||||
|
||||
You can have more than one schema file that belong to one package. For example, in the the bookstore-packaged example both the `book.schema.xml` and `media.schema.xml` belong to the same package "core.book". The generated OM classes for these schemas will therefore end up in the same `core/book/` subdirectory.
|
||||
|
||||
=== The OM build ===
|
||||
|
||||
To run the packaged bookstore example build simply go to the `propel/test/fixtures/bookstore-packages/` directory and type:
|
||||
|
||||
{{{
|
||||
../../../generator/bin/propel-gen om
|
||||
}}}
|
||||
|
||||
This should run without any complaints. When you have a look at the projects/bookstore-packaged/build/classes directory, the following directory tree should have been created:
|
||||
{{{
|
||||
addon/
|
||||
club/
|
||||
BookClubList.php
|
||||
BookClubListPeer.php
|
||||
BookListRel.php
|
||||
BookListRelPeer.php
|
||||
core/
|
||||
author/
|
||||
Author.php
|
||||
AuthorPeer.php
|
||||
book/
|
||||
Book.php
|
||||
BookPeer.php
|
||||
|
||||
Media.php
|
||||
MediaPeer.php
|
||||
publisher/
|
||||
Publisher.php
|
||||
PublisherPeer.php
|
||||
review/
|
||||
Review.php
|
||||
ReviewPeer.php
|
||||
util/
|
||||
log/
|
||||
BookstoreLog.php
|
||||
BookstoreLogPeer.php
|
||||
}}}
|
||||
|
||||
(The additional subdirectories map/ and om/ in each of these directories have been omitted for clarity.)
|
||||
|
||||
== The SQL build ==
|
||||
|
||||
From the same schema files, run the SQL generation by calling:
|
||||
|
||||
{{{
|
||||
../../../generator/bin/propel-gen sql
|
||||
}}}
|
||||
|
||||
Then, have a look at the `build/sql/` directory: you will see that for each package (that is specified as a package attribute in the schema file database tags), one sql file has been created:
|
||||
|
||||
* addon.club.schema.sql
|
||||
* core.author.schema.sql
|
||||
* core.book.schema.sql
|
||||
* core.publisher.schema.sql
|
||||
* core.review.schema.sql
|
||||
* util.log.schema.sql
|
||||
|
||||
These files contain the CREATE TABLE SQL statements necessary for each package.
|
||||
|
||||
When you now run the insert-sql task by typing:
|
||||
{{{
|
||||
../../../generator/bin/propel-gen insert-sql
|
||||
}}}
|
||||
these SQL statements will be executed on a SQLite database located in the Propel/generator/test/ directory.
|
|
@ -1,133 +0,0 @@
|
|||
= How to Use PHP 5.3 Namespaces =
|
||||
|
||||
The generated model classes can use a namespace. It eases the management of large database models, and makes the Propel model classes integrate with PHP 5.3 applications in a clean way.
|
||||
|
||||
== Namespace Declaration And Inheritance ==
|
||||
|
||||
To define a namespace for a model class, you just need to specify it in a `namespace` attribute of the `<table>` element for a single table, or in the `<database>` element to set the same namespace to all the tables.
|
||||
|
||||
Here is an example schema using namespaces:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<?xml version="1.0" encoding="ISO-8859-1" standalone="no"?>
|
||||
<database name="bookstore" defaultIdMethod="native" namespace="Bookstore">
|
||||
|
||||
<table name="book">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="title" type="VARCHAR" required="true" primaryString="true" />
|
||||
<column name="isbn" required="true" type="VARCHAR" size="24" phpName="ISBN" />
|
||||
<column name="price" required="false" type="FLOAT" />
|
||||
<column name="publisher_id" required="false" type="INTEGER" description="Foreign Key Publisher" />
|
||||
<column name="author_id" required="false" type="INTEGER" description="Foreign Key Author" />
|
||||
<foreign-key foreignTable="publisher" onDelete="setnull">
|
||||
<reference local="publisher_id" foreign="id" />
|
||||
</foreign-key>
|
||||
<foreign-key foreignTable="author" onDelete="setnull" onUpdate="cascade">
|
||||
<reference local="author_id" foreign="id" />
|
||||
</foreign-key>
|
||||
</table>
|
||||
|
||||
<table name="author">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER"/>
|
||||
<column name="first_name" required="true" type="VARCHAR" size="128" />
|
||||
<column name="last_name" required="true" type="VARCHAR" size="128" />
|
||||
<column name="email" type="VARCHAR" size="128" />
|
||||
</table>
|
||||
|
||||
<table name="publisher" namespace="Book">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="name" required="true" type="VARCHAR" size="128" default="Penguin" />
|
||||
</table>
|
||||
|
||||
<table name="user" namespace="\Admin">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER"/>
|
||||
<column name="login" required="true" type="VARCHAR" size="128" />
|
||||
<column name="email" type="VARCHAR" size="128" />
|
||||
</table>
|
||||
|
||||
</database>
|
||||
}}}
|
||||
|
||||
The `<database>` element defines a `namespace` attribute. The `book` and `author` tables inherit their namespace from the database, therefore the generated classes for these tables will be `\Bookstore\Book` and `\Bookstore\Author`.
|
||||
|
||||
The `publisher` table defines a `namespace` attribute on ots own, which ''extends'' the database namespace. That means that the generated class will be `\Bookstore\Book\Publisher`.
|
||||
|
||||
As for the `user` table, it defines an absolute namespace (starting with a backslash), which ''overrides'' the database namespace. The generated class for the `user` table will be `Admin\User`.
|
||||
|
||||
'''Tip''': You can use subnamespaces (i.e. namespaces containing backslashes) in the `namespace` attribute.
|
||||
|
||||
== Using Namespaced Models ==
|
||||
|
||||
Namespaced models benefit from the Propel runtime autoloading just like the other model classes. You just need to alias them, or to use their fully qualified name.
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// use an alias
|
||||
use Bookstore\Book;
|
||||
$book = new Book();
|
||||
|
||||
// or use fully qualified name
|
||||
$book = new \Bookstore\Book();
|
||||
}}}
|
||||
|
||||
Relation names forged by Propel don't take the namespace into account. That means that related getter and setters make no mention of it:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$author = new \Bookstore\Author();
|
||||
$book = new \Bookstore\Book();
|
||||
$book->setAuthor($author);
|
||||
$book->save();
|
||||
}}}
|
||||
|
||||
The namespace is used for the ActiveRecord class, but also for the Query and Peer classes. Just remember that when you use relation names ina query, the namespace should not appear:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$author = \Bookstore\AuthorQuery::create()
|
||||
->useBookQuery()
|
||||
->filterByPrice(array('max' => 10))
|
||||
->endUse()
|
||||
->findOne();
|
||||
}}}
|
||||
|
||||
Related tables can have different namespaces, it doesn't interfere with the functionality provided by the object model:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$book = \Bookstore\BookQuery::create()
|
||||
->findOne();
|
||||
echo get_class($book->getPublisher());
|
||||
// \Bookstore\Book\Publisher
|
||||
}}}
|
||||
|
||||
'''Tip''': Using namespaces make generated model code incompatible with versions of PHP less than 5.3. Beware that you will not be able to use your model classes in an older PHP application.
|
||||
|
||||
== Using Namespaces As A Directory Structure ==
|
||||
|
||||
In a schema, you can define a `package` attribute on a `<database>` or a `<table>` tag to generate model classes in a subdirectory (see [wiki:Documentation/1.5/Multi-Component]). If you use namespaces to autoload your classes based on a SplClassAutoloader (see http://groups.google.com/group/php-standards), then you may find yourself repeating the `namespace` data in the `package` attribute:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<database name="bookstore" defaultIdMethod="native"
|
||||
namespace="Foo/Bar" package="Foo.Bar">
|
||||
}}}
|
||||
|
||||
To avoid such repetitions, just set the `propel.namespace.autoPackage` setting to `true` in your `build.properties`:
|
||||
|
||||
{{{
|
||||
#!ini
|
||||
propel.namespace.autoPackage = true
|
||||
}}}
|
||||
|
||||
Now Propel will automatically create a `package` attribute, and therefore distribute model classes in subdirectories, based on the `namespace` attribute, and you can omit the manual `package` attribute in the schema:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<database name="bookstore" defaultIdMethod="native" namespace="Foo/Bar">
|
||||
}}}
|
|
@ -1,183 +0,0 @@
|
|||
= !NestedSet support in Propel =
|
||||
|
||||
'''Warning''': Since Propel 1.5, the support for nested sets was moved to the `nested_set` behavior. The method described here is deprecated.'''
|
||||
|
||||
== Description ==
|
||||
|
||||
With !NestedSet implementation, trees are stored using different approach in databases: [http://www.sitepoint.com/article/hierarchical-data-database]
|
||||
|
||||
Nested Set implementation requires three dedicated fields in table structure
|
||||
|
||||
* left
|
||||
* right
|
||||
|
||||
Plus an optional fields for multi nested set support
|
||||
* scope
|
||||
|
||||
''NB: fields name are free and must be defined in schema.xml''
|
||||
|
||||
To enable !NestedSet support in table, schema.xml must define some specific attributes:
|
||||
'''treeMode''' which must take the value '''!NestedSet'''
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="menu" idMethod="native" treeMode="NestedSet">
|
||||
}}}
|
||||
|
||||
Then, left and right field must be defined that way '''nestedSetLeftKey''' as a boolean value as '''nestedSetRightKey'''
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<column name="lft" type="INTEGER" required="true" default="0" nestedSetLeftKey="true"/>
|
||||
<column name="rgt" type="INTEGER" required="true" default="0" nestedSetRightKey="true"/>
|
||||
}}}
|
||||
|
||||
For multi nestedset support, an other column must be defined with boolean attribute '''treeScopeKey''' set to true
|
||||
{{{
|
||||
#!xml
|
||||
<column name="scope" type="INTEGER" required="true" default="0" treeScopeKey="true"/>
|
||||
}}}
|
||||
|
||||
And then, let's the propel generator automagically create all the needed model and stub classes.
|
||||
|
||||
== !NestedSet usage in Propel ==
|
||||
|
||||
''ex:''
|
||||
'''schema.xml''' extract
|
||||
{{{
|
||||
#!xml
|
||||
<table name="menu" idMethod="native" treeMode="NestedSet">
|
||||
<column name="id" type="INTEGER" required="true" autoIncrement="true" primaryKey="true"/>
|
||||
<column name="lft" type="INTEGER" required="true" default="0" nestedSetLeftKey="true"/>
|
||||
<column name="rgt" type="INTEGER" required="true" default="0" nestedSetRightKey="true"/>
|
||||
<column name="scope" type="INTEGER" required="true" default="0" treeScopeKey="true"/>
|
||||
<column name="text" type="VARCHAR" size="128" required="true" default=""/>
|
||||
<column name="link" type="VARCHAR" size="255" required="true" default=""/>
|
||||
<index name="lft">
|
||||
<index-column name="lft"/>
|
||||
</index>
|
||||
<index name="rgt">
|
||||
<index-column name="rgt"/>
|
||||
</index>
|
||||
<index name="scope">
|
||||
<index-column name="scope"/>
|
||||
</index>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
=== !NestedSet insertion ===
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
|
||||
$root = new Menu();
|
||||
$root->setText('Google');
|
||||
$root->setLink('http://www.google.com');
|
||||
|
||||
$root->makeRoot();
|
||||
$root->save();
|
||||
|
||||
$menu = new Menu();
|
||||
$menu->setText('Google Mail');
|
||||
$menu->setLink('http://mail.google.com');
|
||||
$menu->insertAsLastChildOf($root);
|
||||
$menu->save();
|
||||
|
||||
$child = new Menu();
|
||||
$child->setText('Google Maps');
|
||||
$child->setLink('http://maps.google.com');
|
||||
$child->insertAsLastChildOf($root);
|
||||
$child->save();
|
||||
|
||||
$sibling = new Menu();
|
||||
$sibling->setText('Yahoo!');
|
||||
$sibling->setLink('http://www.yahoo.com');
|
||||
$sibling->insertAsNextSiblingOf($root);
|
||||
$sibling->save();
|
||||
|
||||
$child = new Menu();
|
||||
$child->setText('Yahoo! Mail');
|
||||
$child->setLink('http://mail.yahoo.com');
|
||||
$child->insertAsLastChildOf($sibling);
|
||||
$child->save();
|
||||
}}}
|
||||
|
||||
=== Multi !NestedSet insertion ===
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
|
||||
// Create first root node
|
||||
$root = new Menu();
|
||||
$root->setText('Google');
|
||||
$root->setLink('http://www.google.com');
|
||||
|
||||
$root->makeRoot();
|
||||
$root->setScopeIdValue(1); // Tree 1
|
||||
$root->save();
|
||||
|
||||
$menu = new Menu();
|
||||
$menu->setText('Google Mail');
|
||||
$menu->setLink('http://mail.google.com');
|
||||
$menu->insertAsLastChildOf($root);
|
||||
$menu->save();
|
||||
|
||||
// Create secund root node
|
||||
$root2 = new Menu();
|
||||
$root2->setText('Yahoo!');
|
||||
$root2->setLink('http://www.yahoo.com');
|
||||
|
||||
$root2->makeRoot();
|
||||
$root2->setScopeIdValue(2); // Tree 2
|
||||
$root2->save();
|
||||
|
||||
$menu = new Menu();
|
||||
$menu->setText('Yahoo! Mail');
|
||||
$menu->setLink('http://mail.yahoo.com');
|
||||
$menu->insertAsLastChildOf($root2);
|
||||
$menu->save();
|
||||
}}}
|
||||
|
||||
=== Tree retrieval ===
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
class myMenuOutput extends RecursiveIteratorIterator {
|
||||
function __construct(Menu $m) {
|
||||
parent::__construct($m, self::SELF_FIRST);
|
||||
}
|
||||
|
||||
function beginChildren() {
|
||||
echo str_repeat("\t", $this->getDepth());
|
||||
}
|
||||
|
||||
function endChildren() {
|
||||
echo str_repeat("\t", $this->getDepth() - 1);
|
||||
}
|
||||
}
|
||||
|
||||
$menu = MenuPeer::retrieveTree($scopeId);
|
||||
$it = new myMenuOutput($menu);
|
||||
foreach($it as $m) {
|
||||
echo $m->getText(), '[', $m->getLeftValue(), '-', $m->getRightValue(), "]\n";
|
||||
}
|
||||
}}}
|
||||
=== Tree traversal ===
|
||||
|
||||
!NestetSet implementation use the [http://somabo.de/talks/200504_php_quebec_spl_for_the_masses.pdf SPL RecursiveIterator] as suggested by soenke
|
||||
|
||||
== !NestedSet known broken behaviour ==
|
||||
|
||||
=== Issue description ===
|
||||
For every changes applied on the tree, several entries in the database can be involved. So all already loaded nodes have to be refreshed with their new left/right values.
|
||||
|
||||
=== InstancePool enabled ===
|
||||
In order to refresh all loaded nodes, an automatic internal call is made after each tree change to retrieve all instance in InstancePool and update them.
|
||||
And it works fine.
|
||||
|
||||
=== InstancePool disabled ===
|
||||
When InstancePool is disabled, their is no way to retrieve references to all already loaded node and get them updated.
|
||||
So in most case, all loaded nodes are not updated and it leads to an inconsistency state.
|
||||
So, workaround is to do an explicit reload for any node you use after tree change.
|
||||
|
||||
|
|
@ -1,164 +0,0 @@
|
|||
= Model Introspection At Runtime =
|
||||
|
||||
In addition to the object and peer classes used to do C.R.U.D. operations, Propel generates an object mapping for your tables to allow runtime introspection.
|
||||
|
||||
The intospection objects are instances of the map classes. Propel maps databases, tables, columns, validators, and relations into objects that you can easily use.
|
||||
|
||||
== Retrieving a TableMap ==
|
||||
|
||||
The starting point for runtime introspection is usually a table map. This objects stores every possible property of a table, as defined in the `schema.xml`, but accessible at runtime.
|
||||
|
||||
To retrieve a table map for a table, use the `getTableMap()` static method of the related peer class. For instance, to retrieve the table map for the `book` table, just call:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$bookTable = BookPeer::getTableMap();
|
||||
}}}
|
||||
|
||||
== TableMap properties ==
|
||||
|
||||
A `TableMap` object carries the same information as the schema. Check the following example to see how you can read the general properties of a table from its map:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
echo $bookTable->getName(); // 'table'
|
||||
echo $bookTable->getPhpName(); // 'Table'
|
||||
echo $bookTable->getPackage(); // 'bookstore'
|
||||
echo $bookTable->isUseIdGenerator(); // true
|
||||
}}}
|
||||
|
||||
Tip: A TableMap object also references the `DatabaseMap` that contains it. From the database map, you can also retrieve other table maps using the table name or the table phpName:
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$dbMap = $bookTable->getDatabaseMap();
|
||||
$authorTable = $dbMap->getTable('author');
|
||||
$authorTable = $dbMap->getTablebyPhpName('Author');
|
||||
}}}
|
||||
|
||||
To introspect the columns of a table, use any of the `getColumns()`, `getPrimaryKeys()`, and `getForeignKeys()` `TableMap` methods. They all return an array of `ColumnMap` objects.
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$bookColumns = $bookTable->getColumns();
|
||||
foreach ($bookColumns as $column) {
|
||||
echo $column->getName();
|
||||
}
|
||||
}}}
|
||||
|
||||
Alternatively, if you know a column name, you can retrieve the corresponding ColumnMap directly using the of `getColumn($name)` method.
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$bookTitleColumn = $bookTable->getColumn('title');
|
||||
}}}
|
||||
|
||||
The `DatabaseMap` object offers a shortcut to every `ColumnMap` object if you know the fully qualified column name:
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$bookTitleColumn = $dbMap->getColumn('book.TITLE');
|
||||
}}}
|
||||
|
||||
== ColumnMaps ==
|
||||
|
||||
A `ColumnMap` instance offers a lot of information about a table column. Check the following examples:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$bookTitleColumn->getTableName(); // 'book'
|
||||
$bookTitleColumn->getTablePhpName(); // 'Book'
|
||||
$bookTitleColumn->getType(); // 'VARCHAR'
|
||||
$bookTitleColumn->getSize(); // 255
|
||||
$bookTitleColumn->getDefaultValue(); // null
|
||||
$bookTitleColumn->isLob(); // false
|
||||
$bookTitleColumn->isTemporal(); // false
|
||||
$bookTitleColumn->isEpochTemporal(); // false
|
||||
$bookTitleColumn->isNumeric(); // false
|
||||
$bookTitleColumn->isText(); // true
|
||||
$bookTitleColumn->isPrimaryKey(); // false
|
||||
$bookTitleColumn->isForeignKey(); // false
|
||||
$bookTitleColumn->hasValidators(); // false
|
||||
}}}
|
||||
|
||||
`ColumnMap` objects also keep a reference to their parent `TableMap` object:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$bookTable = $bookTitleColumn->getTable();
|
||||
}}}
|
||||
|
||||
Foreign key columns give access to more information, including the related table and column:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$bookPublisherIdColumn = $bookTable->getColumn('publisher_id');
|
||||
echo $bookPublisherIdColumn->isForeignKey(); // true
|
||||
echo $bookPublisherIdColumn->getRelatedName(); // 'publisher.ID'
|
||||
echo $bookPublisherIdColumn->getRelatedTableName(); // 'publisher'
|
||||
echo $bookPublisherIdColumn->getRelatedColumnName(); // 'ID'
|
||||
$publisherTable = $bookPublisherIdColumn->getRelatedTable();
|
||||
$publisherRelation = $bookPublisherIdColumn->getRelation();
|
||||
}}}
|
||||
|
||||
== RelationMaps ==
|
||||
|
||||
To get an insight on all the relationships of a table, including the ones relying on a foreign key located in another table, you must use the `RelationMap` objects related to a table.
|
||||
|
||||
If you know its name, you can retrieve a `RelationMap` object using `TableMap::getRelation($relationName)`. Note that the relation name is the phpName of the related table, unless the foreign key defines a phpName in the schema. For instance, the name of the `RelationMap` object related to the `book.PUBLISHER_ID` column is 'Publisher'.
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$publisherRelation = $bookTable->getRelation('Publisher');
|
||||
}}}
|
||||
|
||||
alternatively, you can access a `RelationMap` from a foreign key column using `ColumnMap::getRelation()`, as follows:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$publisherRelation = $bookTable->getColumn('publisher_id')->getRelation();
|
||||
}}}
|
||||
|
||||
Once you have a `RelationMap` instance, inspect its properties using any of the following methods:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
echo $publisherRelation->getType(); // RelationMap::MANY_TO_ONE
|
||||
echo $publisherRelation->getOnDelete(); // 'SET NULL'
|
||||
$bookTable = $publisherRelation->getLocalTable();
|
||||
$publisherTable = $publisherRelation->getForeignTable();
|
||||
print_r($publisherRelation->getColumnMappings());
|
||||
// array('book.PUBLISHER_ID' => 'publisher.ID')
|
||||
print_r(publisherRelation->getLocalColumns());
|
||||
// array($bookPublisherIdColumn)
|
||||
print_r(publisherRelation->getForeignColumns());
|
||||
// array($publisherBookIdColumn)
|
||||
}}}
|
||||
|
||||
This also works for relationships referencing the current table:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
$reviewRelation = $bookTable->getRelation('Review');
|
||||
echo $reviewRelation->getType(); // RelationMap::ONE_TO_MANY
|
||||
echo $reviewRelation->getOnDelete(); // 'CASCADE'
|
||||
$reviewTable = $reviewRelation->getLocalTable();
|
||||
$bookTable = $reviewRelation->getForeignTable();
|
||||
print_r($reviewRelation->getColumnMappings());
|
||||
// array('review.BOOK_ID' => 'book.ID')
|
||||
}}}
|
||||
|
||||
To retrieve all the relations of a table, call `TableMap::getRelations()`. You can then iterate over an array of `RelationMap` objects.
|
||||
|
||||
Tip: RelationMap objects are lazy-loaded, which means that the `TableMap` will not instanciate any relation object until you call `getRelations()`. This allows the `TableMap` to remain lightweight for when you don't use relationship introspection.
|
|
@ -1,424 +0,0 @@
|
|||
= How to Write A Behavior =
|
||||
|
||||
Behaviors are a good way to reuse code across models without requiring inheritance (a.k.a. horizontal reuse). This step-by-step tutorial explains how to port model code to a behavior, focusing on a simple example.
|
||||
|
||||
In the tutorial "[http://propel.posterous.com/getting-to-know-propel-15-keeping-an-aggregat Keeping an Aggregate Column up-to-date]", posted in the [http://propel.posterous.com/ Propel blog], the `TotalNbVotes` property of a `PollQuestion` object was updated each time a related `PollAnswer` object was saved, edited, or deleted. This "aggregate column" behavior was implemented by hand using hooks in the model classes. To make it truly reusable, the custom model code needs to be refactored and moved to a Behavior class.
|
||||
|
||||
== Boostrapping A Behavior ==
|
||||
|
||||
A behavior is a class that can alter the generated classes for a table of your model. It must only extend the [browser:branches/1.5/generator/lib/model/Behavior.php `Behavior`] class and implement special "hook" methods. Here is the class skeleton to start with for the `aggregate_column` behavior:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
class AggregateColumnBehavior extends Behavior
|
||||
{
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'name' => null,
|
||||
);
|
||||
}
|
||||
}}}
|
||||
|
||||
Save this class in a file called `AggregateColumnBehavior.php`, and set the path for the class file in the project `build.properties` (just replace directory separators with dots). Remember that the `build.properties` paths are relative to the include path:
|
||||
|
||||
{{{
|
||||
#!ini
|
||||
propel.behavior.aggregate_column.class = path.to.AggregateColumnBehavior
|
||||
}}}
|
||||
|
||||
Test the behavior by adding it to a table of your model, for instance to a `poll_question` table:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<database name="poll" defaultIdMethod="native">
|
||||
<table name="poll_question" phpName="PollQuestion">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="body" type="VARCHAR" size="100" />
|
||||
<behavior name="aggregate_column">
|
||||
<parameter name="name" value="total_nb_votes" />
|
||||
</behavior>
|
||||
</table>
|
||||
</database>
|
||||
}}}
|
||||
|
||||
Rebuild your model, and check the generated `PollQuestionTableMap` class under the `map` subdirectory of your build class directory. This class carries the structure metadata for the `PollQuestion` ActiveRecord class at runtime. The class should feature a `getBehaviors()` method as follows, proving that the behavior was correctly applied:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
class PollQuestionTableMap extends TableMap
|
||||
{
|
||||
// ...
|
||||
|
||||
public function getBehaviors()
|
||||
{
|
||||
return array(
|
||||
'aggregate_column' => array('name' => 'total_nb_votes', ),
|
||||
);
|
||||
} // getBehaviors()
|
||||
}
|
||||
}}}
|
||||
|
||||
== Adding A Column ==
|
||||
|
||||
The behavior works, but it still does nothing at all. Let's make it useful by allowing it to add a column. In the `AggregateColumnBehavior` class, just implement the `modifyTable()` method with the following code:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
class AggregateColumnBehavior extends Behavior
|
||||
{
|
||||
// ...
|
||||
|
||||
public function modifyTable()
|
||||
{
|
||||
$table = $this->getTable();
|
||||
if (!$columnName = $this->getParameter('name')) {
|
||||
throw new InvalidArgumentException(sprintf(
|
||||
'You must define a \'name\' parameter for the \'aggregate_column\' behavior in the \'%s\' table',
|
||||
$table->getName()
|
||||
));
|
||||
}
|
||||
// add the aggregate column if not present
|
||||
if(!$table->containsColumn($columnName)) {
|
||||
$table->addColumn(array(
|
||||
'name' => $columnName,
|
||||
'type' => 'INTEGER',
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
}}}
|
||||
|
||||
This method shows that a behavior class has access to the `<parameters>` defined for it in the `schema.xml` through the `getParameter()` command. Behaviors can also always access the `Table` object attached to them, by calling `getTable()`. A `Table` can check if a column exists and add a new one easily. The `Table` class is one of the numerous generator classes that serve to describe the object model at buildtime, together with `Column`, `ForeignKey`, `Index`, and a lot more classes. You can find all the buildtime model classes under the [browser:branches/1.5/generator/lib/model generator/lib/model] directory.
|
||||
|
||||
'''Tip''': Don't mix up the ''runtime'' database model (`DatabaseMap`, `TableMap`, `ColumnMap`, `ValidatorMap`, `RelationMap`) with the ''buildtime'' database model (`Database`, `Table`, `Column`, `Validator`, etc.). The buildtime model is very detailed, in order to ease the work of the builders that write the ActiveRecord and Query classes. On the other hand, the runtime model is optimized for speed, and carries minimal information to allow correct hydration and binding at runtime. Behaviors use the buildtime object model, because they are run at buildtime, so they have access to the most powerful model.
|
||||
|
||||
Now rebuild the model and the SQL, and sure enough, the new column is there. `BasePollQuestion` offers a `getTotalNbVotes()` and a `setTotalNbVotes()` method, and the table creation SQL now includes the additional `total_nb_votes` column:
|
||||
|
||||
{{{
|
||||
#!sql
|
||||
DROP TABLE IF EXISTS poll_question;
|
||||
CREATE TABLE poll_question
|
||||
(
|
||||
id INTEGER NOT NULL AUTO_INCREMENT,
|
||||
title VARCHAR(100),
|
||||
total_nb_votes INTEGER,
|
||||
PRIMARY KEY (id)
|
||||
)Type=InnoDB;
|
||||
}}}
|
||||
|
||||
'''Tip''': The behavior only adds the column if it's not present (`!$table->containsColumn($columnName)`). So if a user needs to customize the column type, or any other attribute, he can include a `<column>` tag in the table with the same name as defined in the behavior, and the `modifyTable()` will then skip the column addition.
|
||||
|
||||
== Adding A Method To The ActiveRecord Class ==
|
||||
|
||||
In the previous post, a method of the ActiveRecord class was in charge of updating the `total_nb_votes` column. A behavior can easily add such methods by implementing the `objectMethods()` method:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
class AggregateColumnBehavior extends Behavior
|
||||
{
|
||||
// ...
|
||||
|
||||
public function objectMethods()
|
||||
{
|
||||
$script = '';
|
||||
$script .= $this->addUpdateAggregateColumn();
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addUpdateAggregateColumn()
|
||||
{
|
||||
$sql = sprintf('SELECT %s FROM %s WHERE %s = ?',
|
||||
$this->getParameter('expression'),
|
||||
$this->getParameter('foreign_table'),
|
||||
$this->getParameter('foreign_column')
|
||||
);
|
||||
$table = $this->getTable();
|
||||
$aggregateColumn = $table->getColumn($this->getParameter('name'));
|
||||
$columnPhpName = $aggregateColumn->getPhpName();
|
||||
$localColumn = $table->getColumn($this->getParameter('local_column'));
|
||||
return "
|
||||
/**
|
||||
* Updates the aggregate column {$aggregateColumn->getName()}
|
||||
*
|
||||
* @param PropelPDO \$con A connection object
|
||||
*/
|
||||
public function update{$columnPhpName}(PropelPDO \$con)
|
||||
{
|
||||
\$sql = '{$sql}';
|
||||
\$stmt = \$con->prepare(\$sql);
|
||||
\$stmt->execute(array(\$this->get{$localColumn->getPhpName()}()));
|
||||
\$this->set{$columnPhpName}(\$stmt->fetchColumn());
|
||||
\$this->save(\$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
}
|
||||
}}}
|
||||
|
||||
The ActiveRecord class builder expects a string in return to the call to `Behavior::objectMethods()`, and appends this string to the generated code of the ActiveRecord class. Don't bother about indentation: builder classes know how to properly indent a string returned by a behavior. A good rule of thumb is to create one behavior method for each added method, to provide better readability.
|
||||
|
||||
Of course, the schema must be modified to supply the necessary parameters to the behavior:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<database name="poll" defaultIdMethod="native">
|
||||
<table name="poll_question" phpName="PollQuestion">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="body" type="VARCHAR" size="100" />
|
||||
<behavior name="aggregate_column">
|
||||
<parameter name="name" value="total_nb_votes" />
|
||||
<parameter name="expression" value="count(nb_votes)" />
|
||||
<parameter name="foreign_table" value="poll_answer" />
|
||||
<parameter name="foreign_column" value="question_id" />
|
||||
<parameter name="local_column" value="id" />
|
||||
</behavior>
|
||||
</table>
|
||||
<table name="poll_answer" phpName="PollAnswer">
|
||||
<column name="id" required="true" primaryKey="true" autoIncrement="true" type="INTEGER" />
|
||||
<column name="question_id" required="true" type="INTEGER" />
|
||||
<column name="body" type="VARCHAR" size="100" />
|
||||
<column name="nb_votes" type="INTEGER" />
|
||||
<foreign-key foreignTable="poll_question" onDelete="cascade">
|
||||
<reference local="question_id" foreign="id" />
|
||||
</foreign-key>
|
||||
</table>
|
||||
</database>
|
||||
}}}
|
||||
|
||||
Now if you rebuild the model, you will see the new `updateTotalNbVotes()` method in the generated `BasePollQuestion` class:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
class BasePollQuestion extends BaseObject
|
||||
{
|
||||
// ...
|
||||
|
||||
/**
|
||||
* Updates the aggregate column total_nb_votes
|
||||
*
|
||||
* @param PropelPDO $con A connection object
|
||||
*/
|
||||
public function updateTotalNbVotes(PropelPDO $con)
|
||||
{
|
||||
$sql = 'SELECT count(nb_votes) FROM poll_answer WHERE question_id = ?';
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute(array($this->getId()));
|
||||
$this->setTotalNbVotes($stmt->fetchColumn());
|
||||
$this->save($con);
|
||||
}
|
||||
}
|
||||
}}}
|
||||
|
||||
Behaviors offer similar hook methods to allow the addition of methods to the query classes (`queryMethods()`) and to the peer classes (`peerMethods()`). And if you need to add attributes, just implement one of the `objectAttributes()`, `queryAttributes()`, or `peerAttributes()` methods.
|
||||
|
||||
== Using a Template For Generated Code ==
|
||||
|
||||
The behavior's `addUpdateAggregateColumn()` method is somehow hard to read, because of the large string containing the PHP code canvas for the added method. Propel behaviors can take advantage of Propel's simple templating system to use an external file as template for the code to insert.
|
||||
|
||||
Let's refactor the `addUpdateAggregateColumn()` method to take advantage of this feature:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
class AggregateColumnBehavior extends Behavior
|
||||
{
|
||||
// ...
|
||||
|
||||
protected function addUpdateAggregateColumn()
|
||||
{
|
||||
$sql = sprintf('SELECT %s FROM %s WHERE %s = ?',
|
||||
$this->getParameter('expression'),
|
||||
$this->getParameter('foreign_table'),
|
||||
$this->getParameter('foreign_column')
|
||||
);
|
||||
$table = $this->getTable();
|
||||
$aggregateColumn = $table->getColumn($this->getParameter('name'));
|
||||
return $this->renderTemplate('objectUpdateAggregate', array(
|
||||
'aggregateColumn' => $aggregateColumn,
|
||||
'columnPhpName' => $aggregateColumn->getPhpName(),
|
||||
'localColumn' => $table->getColumn($this->getParameter('local_column')),
|
||||
'sql' => $sql,
|
||||
));
|
||||
}
|
||||
}
|
||||
}}}
|
||||
|
||||
The method no longer returns a string created by hand, but a ''rendered template''. Propel templates are simple PHP files executed in a sandbox - they have only access to the variables declared as second argument of the `renderTemplate()` call.
|
||||
|
||||
Now create a `templates/` directory in the same directory as the `AggregateColumnBehavior` class file, and add in a `objectUpdateAggregate.php` file with the following code:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
/**
|
||||
* Updates the aggregate column <?php echo $aggregateColumn->getName() ?>
|
||||
*
|
||||
* @param PropelPDO $con A connection object
|
||||
*/
|
||||
public function update<?php echo $columnPhpName ?>(PropelPDO $con)
|
||||
{
|
||||
$sql = '<?php echo $sql ?>';
|
||||
$stmt = $con->prepare($sql);
|
||||
$stmt->execute(array($this->get<?php echo $localColumn->getPhpName() ?>()));
|
||||
$this->set<?php echo $columnPhpName ?>($stmt->fetchColumn());
|
||||
$this->save($con);
|
||||
}
|
||||
}}}
|
||||
|
||||
No need to escape dollar signs anymore: this syntax allows for a cleaner separation, and is very convenient for large behaviors.
|
||||
|
||||
== Adding Another Behavior From A Behavior ==
|
||||
|
||||
This is where it's getting tricky. In the [http://propel.posterous.com/getting-to-know-propel-15-keeping-an-aggregat blog post] describing the column aggregation technique, the calls to the `updateTotalNbVotes()` method come from the `postSave()` and `postDelete()` hooks of the `PollAnswer` class. But the current behavior is applied to the `poll_question` table, how can it modify the code of a class based on another table?
|
||||
|
||||
The short answer is: it can't. To modify the classes built for the `poll_answer` table, a behavior must be registered on the `poll_answer` table. But a behavior is just like a column or a foreign key: it has an object counterpart in the buildtime database model. So the trick here is to modify the `AggregateColumnBehavior::modifyTable()` method to ''add a new behavior'' to the foreign table. This second behavior will be in charge of implementing the `postSave()` and `postDelete()` hooks of the `PollAnswer` class.
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
class AggregateColumnBehavior extends Behavior
|
||||
{
|
||||
// ...
|
||||
|
||||
public function modifyTable()
|
||||
{
|
||||
// ...
|
||||
|
||||
// add a behavior to the foreign table to autoupdate the aggregate column
|
||||
$foreignTable = $table->getDatabase()->getTable($this->getParameter('foreign_table'));
|
||||
if (!$foreignTable->hasBehavior('concrete_inheritance_parent')) {
|
||||
require_once 'AggregateColumnRelationBehavior.php';
|
||||
$relationBehavior = new AggregateColumnRelationBehavior();
|
||||
$relationBehavior->setName('aggregate_column_relation');
|
||||
$relationBehavior->addParameter(array(
|
||||
'name' => 'foreign_table',
|
||||
'value' => $table->getName()
|
||||
));
|
||||
$relationBehavior->addParameter(array(
|
||||
'name' => 'foreign_column',
|
||||
'value' => $this->getParameter('name')
|
||||
));
|
||||
$foreignTable->addBehavior($relationBehavior);
|
||||
}
|
||||
}
|
||||
}
|
||||
}}}
|
||||
|
||||
In practice, everything now happens as if the `poll_answer` had its own behavior:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<database name="poll" defaultIdMethod="native">
|
||||
<!-- ... -->
|
||||
<table name="poll_answer" phpName="PollAnswer">
|
||||
<!-- ... -->
|
||||
<behavior name="aggregate_column_relation">
|
||||
<parameter name="foreign_table" value="poll_question" />
|
||||
<parameter name="foreign_column" value="total_nb_votes" />
|
||||
</behavior>
|
||||
</table>
|
||||
</database>
|
||||
}}}
|
||||
|
||||
Adding a behavior to a `Table` instance, as well as adding a `Parameter` to a `Behavior` instance, is quite straightforward. And since the second behavior class file is required in the `modifyTable()` method, there is no need to add a path for it in the `build.properties`.
|
||||
|
||||
== Adding Code For Model Hooks ==
|
||||
|
||||
The new `AggregateColumnRelationBehavior` is yet to write. It must implement a call to `PollQuestion::updateTotalNbVotes()` in the `postSave()` and `postDelete()` hooks.
|
||||
|
||||
Adding code to hooks from a behavior is just like adding methods: add a method with the right hook name returning a code string, and the code will get appended at the right place. Unsurprisingly, the behavior hook methods for `postSave()` and `postDelete()` are called `postSave()` and `postDelete()`:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
class AggregateColumnBehavior extends Behavior
|
||||
{
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'foreign_table' => null,
|
||||
'foreignColumn' => null,
|
||||
);
|
||||
|
||||
public function postSave()
|
||||
{
|
||||
$table = $this->getTable();
|
||||
$foreignTable = $table->getDatabase()->getTable($this->getParameter('foreign_table'));
|
||||
$foreignColumn = $foreignTable->getColumn($this->getParameter('foreign_column'));
|
||||
$foreignColumnPhpName = $foreignColumn->getPhpName();
|
||||
return "\$this->updateRelated{$foreignColumnPhpName}(\$con)";
|
||||
}
|
||||
|
||||
public function postDelete()
|
||||
{
|
||||
return $this->postSave();
|
||||
}
|
||||
|
||||
public function objectMethods()
|
||||
{
|
||||
$script = '';
|
||||
$script .= $this->addUpdateRelatedAggregateColumn();
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addUpdateRelatedAggregateColumn()
|
||||
{
|
||||
$table = $this->getTable();
|
||||
$foreignTable = $table->getDatabase()->getTable($this->getParameter('foreign_table'));
|
||||
$foreignTablePhpName = foreignTable->getPhpName();
|
||||
$foreignColumn = $foreignTable->getColumn($this->getParameter('foreign_column'));
|
||||
$foreignColumnPhpName = $foreignColumn->getPhpName();
|
||||
return "
|
||||
/**
|
||||
* Updates an aggregate column in the foreign {$foreignTable->getName()} table
|
||||
*
|
||||
* @param PropelPDO \$con A connection object
|
||||
*/
|
||||
protected function updateRelated{$foreignColumnPhpName}(PropelPDO \$con)
|
||||
{
|
||||
if (\$parent{$foreignTablePhpName} = \$this->get{$foreignTablePhpName}()) {
|
||||
\$parent{$foreignTablePhpName}->update{$foreignColumnPhpName}(\$con);
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
}
|
||||
}}}
|
||||
|
||||
The `postSave()` and `postDelete()` behavior hooks will not add code to the ActiveRecord `postSave()` and `postDelete()` methods - to allow users to further implement these methods - but instead it adds code directly to the `save()` and `delete()` methods, inside a transaction. Check the generated `BasePollAnswer` class for the added code in these methods:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
// aggregate_column_relation behavior
|
||||
$this->updateRelatedTotalNbVotes($con);
|
||||
}}}
|
||||
|
||||
You will also see the new `updateRelatedTotalNbVotes()` method added by `AggregateColumnBehavior::objectMethods()`:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
/**
|
||||
* Updates an aggregate column in the foreign poll_question table
|
||||
*
|
||||
* @param PropelPDO $con A connection object
|
||||
*/
|
||||
protected function updateRelatedTotalNbVotes(PropelPDO $con)
|
||||
{
|
||||
if ($parentPollQuestion = $this->getPollQuestion()) {
|
||||
$parentPollQuestion->updateTotalNbVotes($con);
|
||||
}
|
||||
}
|
||||
}}}
|
||||
|
||||
== What's Left ==
|
||||
|
||||
These are the basics of behavior writing: implement one of the methods documented in the [wiki:Documentation/1.5/Behaviors#WritingaBehavior behaviors chapter] of the Propel guide, and return strings containing the code to be added to the ActiveRecord, Query, and Peer classes. In addition to the behavior code, you should always write unit tests - all the behaviors bundled with Propel have full unit test coverage. And to make your behavior usable by others, documentation is highly recommended. Once again, Propel core behaviors are fully documented, to let users understand the behavior usage without having to peek into the code.
|
||||
|
||||
As for the `AggregateColumnBehavior`, the job is not finished. The [http://propel.posterous.com/getting-to-know-propel-15-keeping-an-aggregat blog post] emphasized the need for hooks in the Query class, and these are not yet implemented in the above code. Besides, the post kept quiet about one use case that left the aggregate column not up to date (when a question is detached from a poll without deleting it). Lastly, the parameters required for this behavior are currently a bit verbose, especially concerning the need to define the foreign table and the foreign key - this could be simplified thanks to the knowledge of the object model that behaviors have.
|
||||
|
||||
All this is left to the reader as an exercise. Fortunately, the final behavior is part of the Propel core behaviors, so the [browser:branches/1.5/generator/lib/behavior/aggregate_column code], [browser:branches/1.5/test/testsuite/generator/behavior/aggregate_column unit tests], and [wiki:Documentation/1.5/Behaviors/aggregate_column documentation] are all ready to help you to further understand the power of Propel's behavior system.
|
|
@ -1,164 +0,0 @@
|
|||
= 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.
|
|
@ -1,350 +0,0 @@
|
|||
= 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!
|
|
@ -1,319 +0,0 @@
|
|||
= 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
|
||||
}}}
|
|
@ -1,386 +0,0 @@
|
|||
= 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
|
||||
}
|
||||
}
|
||||
}}}
|
|
@ -1,253 +0,0 @@
|
|||
= 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.
|
|
@ -1,291 +0,0 @@
|
|||
= 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.
|
||||
|
|
@ -1,280 +0,0 @@
|
|||
= 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.
|
|
@ -1,448 +0,0 @@
|
|||
= 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.
|
|
@ -1,329 +0,0 @@
|
|||
= 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>
|
||||
}}}
|
|
@ -1,312 +0,0 @@
|
|||
= Build Properties Reference =
|
||||
|
||||
[[PageOutline]]
|
||||
|
||||
Here is a list of properties that can be set to affect how Propel builds database files. For a complete list, see the {{{default.properties}}} file that is bundled with your version of Propel generator (this will be in PEAR's data directory if you are using a PEAR-installed version of Propel).
|
||||
|
||||
First, some conventions:
|
||||
|
||||
* Text surrounded by a '''/''' is text that you would provide and is not defined in the language. (i.e. a table name is a good example of this.)
|
||||
* Items where you have an alternative choice have a '''|''' character between them (i.e. true|false)
|
||||
* Alternative choices may be delimited by '''{''' and '''}''' to indicate that this is the default option, if not overridden elsewhere.
|
||||
|
||||
== Where to Specify Properties ==
|
||||
|
||||
=== In the Project build.properties File ===
|
||||
|
||||
The most natural place to specify properties for a file are in the project's {{{build.properties}}} file. This file is expected to be found in the project directory.
|
||||
|
||||
=== In a global build.properties file ===
|
||||
|
||||
You can also create a {{{global build.properties}}} file in the same directory as Propel's {{{default.properties}}} file. For users who have installed Propel using PEAR, this will be in PEAR data directory structure.
|
||||
|
||||
=== On the Command Line ===
|
||||
|
||||
You can also specify properties on the commandline when you invoke Propel:
|
||||
|
||||
{{{
|
||||
$ propel-gen /path/to/project -Dpropel.someOtherProperty=value
|
||||
}}}
|
||||
|
||||
''Note that there is '''no space''' between the -D and the property name.''
|
||||
|
||||
== The Properties ==
|
||||
|
||||
=== General Build Settings ===
|
||||
|
||||
{{{
|
||||
propel.project = Your-Project-Name
|
||||
}}}
|
||||
|
||||
The name of your project. This affects names of generated files, etc.
|
||||
|
||||
{{{
|
||||
propel.targetPackage = {propel.project}
|
||||
}}}
|
||||
|
||||
The package to use for the generated classes. This affects the value of the @package phpdoc tag, and it also affects the directory that the classes are placed in. By default this will be the same as the project. Note that the target package (and thus the target directory for generated classes) can be overridden in each `<database>` and `<table>` element in the XML schema.
|
||||
|
||||
{{{
|
||||
propel.packageObjectModel = true|{false}
|
||||
}}}
|
||||
|
||||
Whether to join schemas using the same database name into a single schema. This allows splitting schemas in packages, and referencing tables in another schema (but in the same database) in a foreign key. Beware that database behaviors will also be joined when this parameter is set to true.
|
||||
|
||||
{{{
|
||||
propel.schema.validate = {true}|false
|
||||
}}}
|
||||
|
||||
Whether to validate the schema using the XSD file. The default XSD file is located under `generator/resources/xsd/database.xsd`, and you can use a custom XSD file by changing the `propel.schema.xsd.file` property.
|
||||
|
||||
{{{
|
||||
propel.schema.transform = true|{false}
|
||||
}}}
|
||||
|
||||
Whether to transform the schema using the XSL file. This was used in previous Propel versions to clean up the schema, but tended to hide problems in the schema. It is disabled by default since Propel 1.5. The default XSL file is located under `generator/resources/xsd/database.xsl`, and you can use a custom XSL file by changing the `propel.schema.xsl.file` property.
|
||||
|
||||
=== Database Settings ===
|
||||
|
||||
{{{
|
||||
propel.database = pgsql|mysql|sqlite|mssql|oracle
|
||||
}}}
|
||||
|
||||
The Propel platform that will be used to determine how to build the SQL DDL, etc.
|
||||
|
||||
|
||||
{{{
|
||||
propel.database.url = /PDO database connection string/
|
||||
propel.database.user =
|
||||
propel.database.password =
|
||||
}}}
|
||||
|
||||
Propel will use this information as the default to connect to your database. Note that for PDO some drivers (e.g. mysql, oracle) require that you specify the username and password separately from the DSN, which is why they are available as options.
|
||||
|
||||
|
||||
{{{
|
||||
propel.database.buildUrl = /PDO database connection string, defaults to use ${propel.database.url}/
|
||||
}}}
|
||||
|
||||
This property is used by Propel to connect to a database to reverse engineer or data dump. The default is to use the database connection defined by the ''propel.database.url'' property.
|
||||
|
||||
|
||||
{{{
|
||||
propel.database.createUrl = /PDO database connection string, defaults to use ${propel.database.url}/
|
||||
}}}
|
||||
|
||||
This property is used by Propel for creating a database. Of course, Propel is unable to create many databases because they do not provide a SQL method for creation; therefore, it is usually recommended that you actually create your database by hand.
|
||||
|
||||
{{{
|
||||
propel.database.schema = /schema-name/
|
||||
}}}
|
||||
|
||||
Where supported by the RDBMS, you can specify a schema name for Propel to use.
|
||||
|
||||
{{{
|
||||
propel.database.encoding =
|
||||
}}}
|
||||
The encoding to use for the database. This can affect things such as transforming charsets when exporting to XML, etc.
|
||||
|
||||
{{{
|
||||
propel.tablePrefix = {empty}|string
|
||||
}}}
|
||||
|
||||
Add a prefix to all the table names in the database. This does not affect the tables phpName. This setting can be overridden on a per-database basis in the schema.
|
||||
|
||||
=== Reverse-Engineering Settings ===
|
||||
|
||||
{{{
|
||||
propel.samePhpName = true|{false}
|
||||
}}}
|
||||
Whether to specify PHP names that are the same as the column names.
|
||||
|
||||
{{{
|
||||
propel.addVendorInfo = true|{false}
|
||||
}}}
|
||||
Whether to add the vendor info. This is currently only used for MySQL, but does provide additional information (such as full-text indexes) which can affect the generation of the DDL from the schema.
|
||||
|
||||
{{{
|
||||
propel.addValidators = {none}|maxvalue|type|required|unique|all
|
||||
}}}
|
||||
Which Propel validators to add to the generated schema (based on the db constraints).
|
||||
|
||||
=== Customizing Generated Object Model ===
|
||||
|
||||
{{{
|
||||
propel.addGenericAccessors = true|{false}
|
||||
propel.addGenericMutators = true|{false}
|
||||
}}}
|
||||
Whether to add generic getter/setter methods -- e.g. '''getByName()''', '''setByName()'''.
|
||||
|
||||
{{{
|
||||
propel.addTimeStamp = true|{false}
|
||||
}}}
|
||||
Whether to add a timestamp to the phpdoc header of generated OM classes.
|
||||
|
||||
{{{
|
||||
propel.addValidateMethod = {true}|false
|
||||
}}}
|
||||
Whether to add `validate()` method to your classes. Set to false if you don't use Propel validation.
|
||||
|
||||
{{{
|
||||
propel.addIncludes = {true}|false
|
||||
}}}
|
||||
Whether to add `require` statements on the generated stub classes. Set to false if you autoload every classe at runtime.
|
||||
|
||||
{{{
|
||||
propel.addHooks = {true}|false
|
||||
}}}
|
||||
Whether to support pre- and post- hooks on `save()` and `delete()` methods. Set to false if you never use these hooks for a small speed boost.
|
||||
|
||||
{{{
|
||||
propel.basePrefix = {Base}|/YourPrefix/
|
||||
}}}
|
||||
The prefix to use for the base (super) classes that are generated.
|
||||
|
||||
{{{
|
||||
propel.classPrefix = {empty}|string;
|
||||
}}}
|
||||
Some sort of "namespacing": All Propel classes with get the Prefix "My_ORM_Prefix_" just like "My_ORM_Prefix_BookPeer".
|
||||
|
||||
{{{
|
||||
propel.disableIdentifierQuoting = true|{false}
|
||||
}}}
|
||||
Identifier quoting is only implemented at the DDL layer at this point. Since this may result in undesired behavior (especially in Postgres), it can be disabled by setting this property to true.
|
||||
|
||||
{{{
|
||||
propel.useLeftJoinsInDoJoinMethods = {true}|false
|
||||
}}}
|
||||
Set whether the '''doSelectJoin*()''' methods use LEFT JOIN or INNER JOIN (see ticket:491 and ticket:588 to understand more about why this might be important).
|
||||
|
||||
=== MySQL-specific Settings ===
|
||||
|
||||
{{{
|
||||
propel.mysqlTableType = /DefaultTableEngine/
|
||||
}}}
|
||||
Default table engine - defaults to MyISAM. You can override this setting if you wish to default to another engine for all tables (for instance InnoDB, or HEAP). This setting can also be overridden on a per-table basis using the `<vendor>` element in the schema (see [wiki:Documentation/1.5/Schema#AddingVendorInfo]).
|
||||
|
||||
{{{
|
||||
propel.mysqlTableEngineKeyword = /EngineKeyword/
|
||||
}}}
|
||||
Keyword used to specify the table engine in the CREATE SQL statement. Defaults to 'ENGINE', users of MYSQL < 5 should use 'TYPE' instead.
|
||||
|
||||
=== Date/Time Settings ===
|
||||
|
||||
{{{
|
||||
propel.useDateTimeClass = true|{false}
|
||||
}}}
|
||||
This is how you enable full use of the new DateTime class in Propel. Setting this to true means that getter methods for date/time/timestamp columns will return a DateTime object ''when the default format is empty''. Note that the current default of ''false'' is only for backwards compatibility; in the future ''true'' will be the only option here.
|
||||
|
||||
{{{
|
||||
propel.dateTimeClass = {DateTime}|string
|
||||
}}}
|
||||
Specify a custom DateTime subclass that you wish to have Propel use for temporal values.
|
||||
|
||||
{{{
|
||||
propel.defaultTimeStampFormat = {Y-m-d H:i:s}|string
|
||||
propel.defaultTimeFormat = {%X}|string
|
||||
propel.defaultDateFormat = {%x}|string
|
||||
}}}
|
||||
These are the default formats that will be used when fetching values from temporal columns in Propel. You can always specify these when calling the methods directly, but for methods like getByName() it is nice to change the defaults.
|
||||
|
||||
To have these methods return DateTime objects instead, you should set these to empty values, for example:
|
||||
{{{
|
||||
propel.defaultTimeStampFormat =
|
||||
}}}
|
||||
|
||||
=== Directories ===
|
||||
|
||||
{{{
|
||||
propel.project.dir = default-depends-on-installation-type
|
||||
}}}
|
||||
|
||||
''This is not necessarily a property you can change.'' The project directory is the directory where you project files (build.properties, schema.xml, runtime-conf.xml, etc.) are located. For example, if you use the {{{propel-gen}}} script, this value will get overridden to the path you pass to {{{propel-gen}}}.
|
||||
|
||||
{{{
|
||||
propel.output.dir = ${propel.project.dir}/build
|
||||
}}}
|
||||
The default top-level directory for output of classes, sql, config, etc.
|
||||
|
||||
{{{
|
||||
propel.schema.dir = ${propel.project.dir}
|
||||
}}}
|
||||
The directory where Propel expects to find your schema.xml file.
|
||||
|
||||
{{{
|
||||
propel.conf.dir = ${propel.project.dir}
|
||||
}}}
|
||||
The directory where Propel expects to find your {{{runtime-conf.xml}}} file.
|
||||
|
||||
{{{
|
||||
propel.php.dir = ${propel.output.dir}/classes
|
||||
}}}
|
||||
The directory where Propel will create generated object model classes.
|
||||
|
||||
{{{
|
||||
propel.phpconf.dir = ${propel.output.dir}/conf
|
||||
}}}
|
||||
The directory where Propel will place the php-ified version of your {{{runtime-conf.xml}}}.
|
||||
|
||||
{{{
|
||||
propel.sql.dir = ${propel.output.dir}/sql
|
||||
}}}
|
||||
The directory where Propel will place generated DDL (or data insert statements, etc.)
|
||||
|
||||
|
||||
=== Overriding Builder Classes ===
|
||||
|
||||
{{{
|
||||
# Object Model builders
|
||||
propel.builder.peer.class = propel.engine.builder.om.php5.PHP5ComplexPeerBuilder
|
||||
propel.builder.object.class = propel.engine.builder.om.php5.PHP5ComplexObjectBuilder
|
||||
propel.builder.objectstub.class = propel.engine.builder.om.php5.PHP5ExtensionObjectBuilder
|
||||
propel.builder.peerstub.class = propel.engine.builder.om.php5.PHP5ExtensionPeerBuilder
|
||||
|
||||
propel.builder.objectmultiextend.class = propel.engine.builder.om.php5.PHP5MultiExtendObjectBuilder
|
||||
|
||||
propel.builder.tablemap.class = propel.engine.builder.om.php5.PHP5TableMapBuilder
|
||||
|
||||
propel.builder.interface.class = propel.engine.builder.om.php5.PHP5InterfaceBuilder
|
||||
|
||||
propel.builder.node.class = propel.engine.builder.om.php5.PHP5NodeBuilder
|
||||
propel.builder.nodepeer.class = propel.engine.builder.om.php5.PHP5NodePeerBuilder
|
||||
propel.builder.nodestub.class = propel.engine.builder.om.php5.PHP5ExtensionNodeBuilder
|
||||
propel.builder.nodepeerstub.class = propel.engine.builder.om.php5.PHP5ExtensionNodePeerBuilder
|
||||
|
||||
propel.builder.nestedset.class = propel.engine.builder.om.php5.PHP5NestedSetBuilder
|
||||
propel.builder.nestedsetpeer.class = propel.engine.builder.om.php5.PHP5NestedSetPeerBuilder
|
||||
|
||||
# SQL builders
|
||||
|
||||
propel.builder.ddl.class = propel.engine.builder.sql.${propel.database}.${propel.database}DDLBuilder
|
||||
propel.builder.datasql.class = propel.engine.builder.sql.${propel.database}.${propel.database}DataSQLBuilder
|
||||
|
||||
# Platform classes
|
||||
|
||||
propel.platform.class = propel.engine.platform.${propel.database}Platform
|
||||
|
||||
# Pluralizer class (used to generate plural forms)
|
||||
|
||||
propel.builder.pluralizer.class = propel.engine.builder.util.DefaultEnglishPluralizer
|
||||
}}}
|
||||
|
||||
As you can see, you can specify your own builder and platform classes if you want to extend & override behavior in the default classes
|
||||
|
||||
=== Adding Behaviors ===
|
||||
|
||||
{{{
|
||||
propel.behavior.timestampable.class = propel.engine.behavior.TimestampableBehavior
|
||||
}}}
|
||||
|
||||
Define the path to the class to be used for the `timestampable` behavior. This behavior is bundled wit hPropel, but if you want to override it, you can specify a different path.
|
||||
|
||||
If you want to add more behaviors, write their path following the same model:
|
||||
|
||||
{{{
|
||||
propel.behavior.my_behavior.class = my.custom.path.to.MyBehaviorClass
|
||||
}}}
|
||||
|
||||
Behaviors are enabled on a per-table basis in the `schema.xml`. However, you can add behaviors for all your schemas, provided that you define them in the `propel.behavior.default` setting:
|
||||
|
||||
{{{
|
||||
propel.behavior.default = soft_delete,my_behavior
|
||||
}}}
|
File diff suppressed because it is too large
Load Diff
|
@ -1,318 +0,0 @@
|
|||
= Runtime Configuration File =
|
||||
|
||||
[[PageOutline]]
|
||||
|
||||
== Example {{{runtime-conf.xml}}} File ==
|
||||
|
||||
Here is a the sample runtime configuration file.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<?xml version="1.0"?>
|
||||
<config>
|
||||
<log>
|
||||
<ident>propel-bookstore</ident>
|
||||
<name>console</name>
|
||||
<level>7</level>
|
||||
</log>
|
||||
<propel>
|
||||
<datasources default="bookstore">
|
||||
<datasource id="bookstore">
|
||||
<adapter>sqlite</adapter>
|
||||
<connection>
|
||||
<classname>DebugPDO</classname>
|
||||
<dsn>mysql:host=localhost;dbname=bookstore</dsn>
|
||||
<user>testuser</user>
|
||||
<password>password</password>
|
||||
<options>
|
||||
<option id="ATTR_PERSISTENT">false</option>
|
||||
</options>
|
||||
<attributes>
|
||||
<option id="ATTR_EMULATE_PREPARES">true</option>
|
||||
</attributes>
|
||||
<settings>
|
||||
<setting id="charset">utf8</setting>
|
||||
<setting id="queries">
|
||||
<query>set search_path myschema, public</query><!-- automatically set postgresql's search_path -->
|
||||
<query>INSERT INTO BAR ('hey', 'there')</query><!-- execute some other query -->
|
||||
</setting>
|
||||
</settings>
|
||||
</connection>
|
||||
<slaves>
|
||||
<connection>
|
||||
<dsn>mysql:host=slave-server1; dbname=bookstore</dsn>
|
||||
</connection>
|
||||
<connection>
|
||||
<dsn>mysql:host=slave-server2; dbname=bookstore</dsn>
|
||||
</connection>
|
||||
</slaves>
|
||||
</datasource>
|
||||
</datasources>
|
||||
<debugpdo>
|
||||
<logging>
|
||||
<details>
|
||||
<method>
|
||||
<enabled>true</enabled>
|
||||
</method>
|
||||
<time>
|
||||
<enabled>true</enabled>
|
||||
<precision>3</precision>
|
||||
</time>
|
||||
<mem>
|
||||
<enabled>true</enabled>
|
||||
<precision>1</precision>
|
||||
</mem>
|
||||
</details>
|
||||
</logging>
|
||||
</debugpdo>
|
||||
</propel>
|
||||
</config>
|
||||
}}}
|
||||
|
||||
== Explanation of Configuration Sections ==
|
||||
|
||||
Below you will find an explanation of the primary elements in the configuration.
|
||||
|
||||
=== <log> ===
|
||||
|
||||
If the '''<log>''' element is present, Propel will use the specified information to instantiate a [http://pear.php.net/Log PEAR Log] logger.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<log>
|
||||
<type>file<type>
|
||||
<name>/path/to/logger.log</name>
|
||||
<ident>my-app</ident>
|
||||
<level>7</level>
|
||||
</log>
|
||||
}}}
|
||||
|
||||
The nested elements correspond to the configuration options for the logger (options that would otherwise be passed to '''Log::factory()''' method).
|
||||
|
||||
||'''Element'''||'''Default'''||'''Description'''||
|
||||
||'''<type>'''||file||The logger type.||
|
||||
||'''<name>'''||./propel.log||Name of log, meaning is dependent on type specified. (For ''file'' type this is the filename).||
|
||||
||'''<ident>'''||propel||The identifier tag for the log.||
|
||||
||'''<level>'''||7 (PEAR_LOG_DEBUG)||The logging level.||
|
||||
|
||||
This log configuring API is designed to provide a simple way to get log output from Propel; however, if your application already has a logging mechanism, we recommend instead that you use your existing logger (writing a simple log adapter, if you are using an unsupported logger). See the [wiki:Documentation/1.5/07-Logging Logging documentation] for more info.
|
||||
|
||||
=== <datasources> ===
|
||||
|
||||
This is the top-level tag for Propel datasources configuration.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
}}}
|
||||
|
||||
=== <datasource> ===
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
<datasource id="bookstore">
|
||||
}}}
|
||||
A specific datasource being configured.
|
||||
* The @id must match the <database> @name attribute from your {{{schema.xml}}}.
|
||||
|
||||
=== <adapter> ===
|
||||
|
||||
The adapter to use for Propel. Currently supported adapters: sqlite, pgsql, mysql, oracle, mssql. Note that it is possible that your adapter could be different from your connection driver (e.g. if using ODBC to connect to MSSQL database, you would use an ODBC PDO driver, but MSSQL Propel adapter).
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
<datasource>
|
||||
<adapter>sqlite</adapter>
|
||||
}}}
|
||||
|
||||
=== <connection> ===
|
||||
|
||||
The PDO database connection for the specified datasource.
|
||||
|
||||
Nested elements define the DSN, connection options, other PDO attributes, and finally some Propel-specific initialization settings.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
<datasource>
|
||||
<connection>
|
||||
}}}
|
||||
|
||||
==== <classname> ====
|
||||
|
||||
A custom PDO class (must be a PropelPDO subclass) that you would like to use for the PDO connection.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
<datasource>
|
||||
<connection>
|
||||
<classname>DebugPDO</classname>
|
||||
}}}
|
||||
|
||||
This can be used to specify the alternative '''DebugPDO''' class bundled with Propel, or your own subclass. ''Your class must extend PropelPDO, because Propel requires the ability to nest transactions (without having exceptions being thrown by PDO).''
|
||||
|
||||
==== <dsn> ====
|
||||
|
||||
The PDO DSN that Propel will use to connect to the database for this datasource.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
<datasource>
|
||||
<connection>
|
||||
<dsn>mysql:host=localhost;dbname=bookstore</dsn>
|
||||
}}}
|
||||
|
||||
See the PHP documentation for specific format:
|
||||
* [http://www.php.net/manual/en/ref.pdo-mysql.connection.php MySQL DSN]
|
||||
* [http://www.php.net/manual/en/ref.pdo-pgsql.connection.php PostgreSQL DSN]
|
||||
* [http://www.php.net/manual/en/ref.pdo-sqlite.connection.php SQLite DSN]
|
||||
* [http://www.php.net/manual/en/ref.pdo-oci.connection.php Oracle DSN]
|
||||
* [http://www.php.net/manual/en/ref.pdo-dblib.connection.php MSSQL DSN]
|
||||
|
||||
Note that some database (e.g. PostgreSQL) specify username and password as part of the DSN while the others specify user and password separately.
|
||||
|
||||
==== <user> and <password> ====
|
||||
|
||||
Specifies credentials for databases that specify username and password separately (e.g. MySQL, Oracle).
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
<datasource>
|
||||
<connection>
|
||||
<dsn>mysql:host=localhost;dbname=bookstore</dsn>
|
||||
<user>test</user>
|
||||
<password>testpass</password>
|
||||
}}}
|
||||
|
||||
==== <options> ====
|
||||
|
||||
Specify any options which ''must'' be specified when the PDO connection is created. For example, the ATTR_PERSISTENT option must be specified at object creation time.
|
||||
|
||||
See the [http://www.php.net/pdo PDO documentation] for more details.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
<datasource>
|
||||
<connection>
|
||||
<!-- ... -->
|
||||
<options>
|
||||
<option id="ATTR_PERSISTENT">false</option>
|
||||
</options>
|
||||
}}}
|
||||
|
||||
==== <attributes> ====
|
||||
|
||||
`<attributes>` are similar to `<options>`; the difference is that options specified in `<attributes>` are set after the PDO object has been created. These are set using the [http://us.php.net/PDO-setAttribute PDO->setAttribute()] method.
|
||||
|
||||
In addition to the standard attributes that can be set on the PDO object, there are also the following Propel-specific attributes that change the behavior of the PropelPDO connection:
|
||||
|
||||
|| '''Attribute constant''' || '''Valid Values (Default)''' || '''Description''' ||
|
||||
|| PropelPDO::PROPEL_ATTR_CACHE_PREPARES || true/false (false) || Whether to have the PropelPDO connection cache the PDOStatement prepared statements. This will improve performance if you are executing the same query multiple times by your script (within a single request / script run). ||
|
||||
|
||||
''Note that attributes in the XML can be specified with or without the PDO:: (or PropelPDO::) constant prefix.''
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
<datasource>
|
||||
<connection>
|
||||
<!-- ... -->
|
||||
<attributes>
|
||||
<option id="ATTR_ERRMODE">PDO::ERRMODE_WARNING</option>
|
||||
<option id="ATTR_STATEMENT_CLASS">myPDOStatement</option>
|
||||
<option id="PROPEL_ATTR_CACHE_PREPARES">true</option>
|
||||
</attributes>
|
||||
}}}
|
||||
|
||||
'''Tip''': If you are using MySQL and get the following error : "SQLSTATE[HY000]: General error: 2014 Cannot execute queries while other unbuffered queries are active", you can try adding the following attribute:
|
||||
|
||||
{{{
|
||||
<option id="MYSQL_ATTR_USE_BUFFERED_QUERY">true</option>
|
||||
}}}
|
||||
|
||||
==== <settings> ====
|
||||
|
||||
Settings are Propel-specific options used to further configure the connection -- or perform other user-defined initialization tasks.
|
||||
|
||||
Currently supported settings are:
|
||||
* charset
|
||||
* queries
|
||||
|
||||
===== charset =====
|
||||
|
||||
Specifies the character set to use. Currently you must specify the charset in the way that is understood by your RDBMS. Also note that not all database systems support specifying charset (e.g. SQLite must be compiled with specific charset support). Specifying this option will likely result in an exception if your database doesn't support the specified charset.
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
<datasource>
|
||||
<connection>
|
||||
<!-- ... -->
|
||||
<settings>
|
||||
<setting id="charset">utf8</setting>
|
||||
</settings>
|
||||
}}}
|
||||
|
||||
===== queries =====
|
||||
|
||||
Specifies any SQL statements to run when the database connection is initialized. This can be used for any environment setup or db initialization you would like to perform. These statements will be executed with every Propel initialization (e.g. every PHP script load).
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
<datasource>
|
||||
<connection>
|
||||
<!-- ... -->
|
||||
<settings>
|
||||
<setting id="queries">
|
||||
<query>set search_path myschema, public</query><!-- automatically set postgresql's search_path -->
|
||||
<query>INSERT INTO BAR ('hey', 'there')</query>
|
||||
</setting>
|
||||
</settings>
|
||||
}}}
|
||||
|
||||
=== <slaves> ===
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<config>
|
||||
<propel>
|
||||
<datasources>
|
||||
<datasource>
|
||||
<slaves>
|
||||
}}}
|
||||
|
||||
The `<slaves>` tag groups slave `<connection>` elements which provide support for configuring slave db servers -- when using Propel in a master-slave replication environment. See the [wiki:Documentation/1.5/Master-Slave Master-Slave documentation] for more information. The nested `<connection>` elements are configured the same way as the top-level `<connection>` element is configured.
|
||||
|
||||
=== <debugpdo> ===
|
||||
|
||||
The optional `<debugpdo>` element may be provided to pass additional logging configuration options to DebugPDO. Note that these settings have no effect unless DebugPDO has been selected in [1.5/RuntimeConfiguration#debugpdo `runtime-conf.xml`] as the PDO connection class. See the [wiki:Documentation/1.5/07-Logging Logging documentation] for more information on configuring DebugPDO.
|
|
@ -1,398 +0,0 @@
|
|||
= Database Schema =
|
||||
|
||||
[[PageOutline]]
|
||||
|
||||
The schema for `schema.xml` contains a small number of elements with required and optional attributes. The Propel generator contains a [source:branches/1.5/generator/resources/dtd/database.dtd DTD] that can be used to validate your `schema.xml` document. Also, when you build your SQL and OM, the Propel generator will automatically validate your `schema.xml` file using a highly-detailed [source:branches/1.5/generator/resources/xsd/database.xsd XSD].
|
||||
|
||||
== At-a-Glance ==
|
||||
|
||||
The hierarchical tree relationship for the elements is:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<database>
|
||||
<external-schema />
|
||||
<table>
|
||||
<column>
|
||||
<inheritance />
|
||||
</column>
|
||||
<foreign-key>
|
||||
<reference />
|
||||
</foreign-key>
|
||||
<index>
|
||||
<index-column />
|
||||
</index>
|
||||
<unique>
|
||||
<unique-column />
|
||||
</unique>
|
||||
<id-method-parameter/>
|
||||
</table>
|
||||
</database>
|
||||
}}}
|
||||
|
||||
**Tip**: If you use an IDE supporting autocompletion in XML documents, you can take advantage of the XSD describing the `schema.xml` syntax to suggest elements and attributes as you type. To enable it, add a `xmlns:xsi` and a `xsi:noNamespaceSchemaLocation` attribute to the leading `<database>` tag:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<database name="my_connection_name" defaultIdMethod="native"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:noNamespaceSchemaLocation="http://svn.propelorm.org/branches/1.5/generator/resources/xsd/database.xsd" >
|
||||
}}}
|
||||
|
||||
== Detailed Reference ==
|
||||
|
||||
This page provides an alternate rendering of the Appendix B - Schema Reference from the user's guide.
|
||||
It spells out in specific detail, just where each attribute or element belongs.
|
||||
|
||||
First, some conventions:
|
||||
|
||||
* Text surrounded by a '''/''' is text that you would provide and is not defined in the language. (i.e. a table name is a good example of this.)
|
||||
* Optional items are surrounded by '''[''' and ''']''' characters.
|
||||
* Items where you have an alternative choice have a '''|''' character between them (i.e. true|false)
|
||||
* Alternative choices may be delimited by '''{''' and '''}''' to indicate that this is the default option, if not overridden elsewhere.
|
||||
* '''...''' means repeat the previous item.
|
||||
|
||||
=== <database> element ===
|
||||
|
||||
Starting with the {{{<database>}}} element. The ''attributes'' and ''elements'' available are:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<database
|
||||
name="/DatabaseName/"
|
||||
defaultIdMethod="native|none"
|
||||
[package="/ProjectName/"]
|
||||
[namespace="/ClassNamespace/"]
|
||||
[baseClass="/baseClassName/"]
|
||||
[basePeer="/baseClassPeerName/"]
|
||||
[defaultPhpNamingMethod="nochange|{underscore}|phpname|clean"
|
||||
[heavyIndexing="true|false"]
|
||||
[tablePrefix="/tablePrefix/"]
|
||||
>
|
||||
<external-schema>
|
||||
<table>
|
||||
...
|
||||
</database>
|
||||
}}}
|
||||
|
||||
The `package`, `baseClass`, `basePeer`, `defaultPhpNamingMethod`, and `heavyIndexing` attributes are generally optional.
|
||||
A Database element may include an `<external-schema>` element, or multiple `<table>` elements.
|
||||
|
||||
* `defaultIdMethod` sets the default id method to use for auto-increment columns.
|
||||
* `package` specifies the "package" for the generated classes. Classes are created in subdirectories according to the `package` value.
|
||||
* `namespace` specifies the default namespace that generated model classes will use (PHP 5.3 only). This attribute can be completed or overridden at the table level.
|
||||
* `baseClass` allows you to specify a default base class that all generated Propel objects should extend (in place of `propel.om.BaseObject`).
|
||||
* `basePeer` instructs Propel to use a different SQL-generating `BasePeer` class (or sub-class of `BasePeer`) for all generated objects.
|
||||
* `defaultPhpNamingMethod` the default naming method to use for tables of this database. Defaults to `underscore`, which transforms table names into CamelCase phpNames.
|
||||
* `heavyIndexing` adds indexes for each component of the primary key (when using composite primary keys).
|
||||
* `tablePrefix` adds a prefix to all the SQL table names.
|
||||
|
||||
=== <external-schema> element ===
|
||||
|
||||
The `<external-schema>` element is pretty simple. It just includes a schema file from somewhere on the file systems. The format is:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<external-schema filename="/a path to a file/" />
|
||||
}}}
|
||||
|
||||
=== <table> element ===
|
||||
|
||||
The `<table>` element is the most complicated of the usable elements. Its definition looks like this:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table
|
||||
name = "/TableName/"
|
||||
[idMethod = "native|{none}"]
|
||||
[phpName = "/PhpObjectName/"]
|
||||
[package="/PhpObjectPackage/"]
|
||||
[namespace = "/PhpObjectNamespace/"]
|
||||
[skipSql = "true|false"]
|
||||
[abstract = "true|false"]
|
||||
[phpNamingMethod = "nochange|{underscore}|phpname|clean"]
|
||||
[baseClass = "/baseClassName/"]
|
||||
[basePeer = "/baseClassPeerName/"]
|
||||
[description="/A text description of the table/"]
|
||||
[heavyIndexing = "true|false"]
|
||||
[readOnly = "true|false"]
|
||||
[treeMode = "NestedSet|MaterializedPath"]
|
||||
[reloadOnInsert = "true|false"]
|
||||
[reloadOnUpdate = "true|false"]
|
||||
[allowPkInsert = "true|false"]
|
||||
>
|
||||
|
||||
<column>
|
||||
...
|
||||
<foreign-key>
|
||||
...
|
||||
<index>
|
||||
...
|
||||
<unique>
|
||||
...
|
||||
<id-method-parameter>
|
||||
...
|
||||
</table>
|
||||
}}}
|
||||
|
||||
According to the schema, `name` is the only required attribute. Also, the `idMethod`, `package`, `namespace`, `phpNamingMethod`, `baseClass`, `basePeer`, and `heavyIndexing` attributes all default to what is specified by the `<database>` element.
|
||||
|
||||
==== Description of Attributes ====
|
||||
|
||||
* `idMethod` sets the id method to use for auto-increment columns.
|
||||
* `phpName` specifies object model class name. By default, Propel uses a CamelCase version of the table name as phpName.
|
||||
* `package` specifies the "package" (or subdirectory) in which model classes get generated.
|
||||
* `namespace` specifies the namespace that the generated model classes will use (PHP 5.3 only). If the table namespace starts with a `\`, it overrides the namespace defined in the `<database>` tag; otherwise, the actual table namespace is the concatenation of the database namespace and the table namespace.
|
||||
* `skipSql` instructs Propel not to generate DDL SQL for the specified table. This can be used together with `readOnly` for supperting VIEWS in Propel.
|
||||
* `abstract` Whether the generated ''stub'' class will be abstract (e.g. if you're using inheritance)
|
||||
* `phpNamingMethod` the naming method to use. Defaults to `underscore`, which transforms the table name into a CamelCase phpName.
|
||||
* `baseClass` allows you to specify a class that the generated Propel objects should extend ({{{in place of propel.om.BaseObject}}}).
|
||||
* `basePeer` instructs Propel to use a different SQL-generating `BasePeer` class (or sub-class of `BasePeer`).
|
||||
* `heavyIndexing` adds indexes for each component of the primary key (when using composite primary keys).
|
||||
* `readOnly` suppresses the mutator/setter methods, save() and delete() methods.
|
||||
* `treeMode` is used to indicate that this table is part of a node tree. Currently the only supported values are "!NestedSet" (see [wiki:Documentation/1.5/Behaviors/nested_set]) and "!MaterializedPath" (deprecated).
|
||||
* `reloadOnInsert` is used to indicate that the object should be reloaded from the database when an INSERT is performed. This is useful if you have triggers (or other server-side functionality like column default expressions) that alters the database row on INSERT.
|
||||
* `reloadOnUpdate` is used to indicate that the object should be reloaded from the database when an UPDATE is performed. This is useful if you have triggers (or other server-side functionality like column default expressions) that alters the database row on UPDATE.
|
||||
* `allowPkInsert` can be used if you want to define the primary key of a new object being inserted. By default if idMethod is "native", Propel would throw an exception. However, in some cases this feature is useful, for example if you do some replication of data in an master-master environment. It defaults to false.
|
||||
|
||||
=== <column> element ===
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<column
|
||||
name = "/ColumnName/"
|
||||
[phpName = "/PHPColumnName/"]
|
||||
[peerName = "/PEERNAME/"]
|
||||
[primaryKey = "true|{false}"]
|
||||
[required = "true|{false}"]
|
||||
[type = "BOOLEAN|TINYINT|SMALLINT|INTEGER|BIGINT|DOUBLE|FLOAT|REAL|DECIMAL|CHAR|{VARCHAR}|LONGVARCHAR|DATE|TIME|TIMESTAMP|BLOB|CLOB"]
|
||||
[phpType = "boolean|int|integer|double|float|string|/BuiltInClassName/|/UserDefinedClassName/"]
|
||||
[sqlType = "/NativeDatabaseColumnType/"
|
||||
[size = "/NumericLengthOfColumn/"]
|
||||
[scale = "/DigitsAfterDecimalPlace/"]
|
||||
[defaultValue = "/AnyDefaultValueMatchingType/"]
|
||||
[defaultExpr = "/AnyDefaultExpressionMatchingType/"]
|
||||
[autoIncrement = "true|{false}"]
|
||||
[lazyLoad = "true|{false}"]
|
||||
[description = "/Column Description/"]
|
||||
[primaryString = "true|{false}"]
|
||||
[phpNamingMethod = "nochange|underscore|phpname"]
|
||||
[inheritance = "single|{false}"]
|
||||
[inputValidator = "NameOfInputValidatorClass"]
|
||||
>
|
||||
[<inheritance key="/KeyName/" class="/ClassName/" [extends="/BaseClassName/"] />]
|
||||
</column>
|
||||
}}}
|
||||
|
||||
==== Description of Attributes ====
|
||||
|
||||
* {{{defaultValue}}} The default value that the object will have for this column in the PHP instance after creating a "new Object". This value is always interpreted as a string.
|
||||
* {{{defaultExpr}}} The default value for this column as expressed in SQL. This value is used solely for the "sql" target which builds your database from the schema.xml file. The defaultExpr is the SQL expression used as the "default" for the column.
|
||||
* {{{primaryString}}} A column defined as primary string serves as default value for a `__toString()` method in the generated Propel object.
|
||||
|
||||
=== <foreign-key> element ===
|
||||
|
||||
To link a column to another table use the following syntax:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<foreign-key
|
||||
foreignTable = "/TheOtherTableName/"
|
||||
[name = "/Name for this foreign key/"]
|
||||
[phpName = "/Name for the foreign object in methods generated in this class/"]
|
||||
[refPhpName = "/Name for this object in methods generated in the foreign class/"]
|
||||
[onDelete = "cascade|setnull|restrict|none"]
|
||||
[onUpdate = "cascade|setnull|restrict|none"]
|
||||
[defaultJoin= "Criteria::INNER_JOIN|Criteria::LEFT_JOIN"]
|
||||
>
|
||||
<reference local="/LocalColumnName/" foreign="/ForeignColumnName/" />
|
||||
</foreign-key>
|
||||
}}}
|
||||
|
||||
==== Description of Attributes ====
|
||||
|
||||
* {{{defaultJoin}}} This affects the default join type used in the generated `joinXXX()` methods in the model query class. Propel uses an INNER JOIN for foreign keys attached to a required column, and a LEFT JOIN for foreign keys attached to a non-required column, but you can override this in the foreign key element.
|
||||
|
||||
=== <index> element ===
|
||||
|
||||
To create an index on one or more columns, use the following syntax:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<index>
|
||||
<index-column name="/ColumnName/" [size="/LengthOfIndexColumn/"] />
|
||||
...
|
||||
</index>
|
||||
}}}
|
||||
|
||||
In some cases your RDBMS may require you to specify an index size.
|
||||
|
||||
=== <unique> element ===
|
||||
|
||||
To create a unique index on one or more columns, use the following syntax:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<unique>
|
||||
<unique-column name="/ColumnName/" [size="/LengthOfIndexColumn/"] />
|
||||
...
|
||||
</unique>
|
||||
}}}
|
||||
|
||||
In some cases your RDBMS may require you to specify an index size for unique indexes.
|
||||
|
||||
=== <id-method-parameter> element ===
|
||||
|
||||
If you are using a database that uses sequences for auto-increment columns (e.g. PostgreSQL or Oracle), you can customize the name of the sequence using the <id-method-paramter/> tag:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<id-method-parameter value="my_custom_sequence_name"/>
|
||||
}}}
|
||||
|
||||
== Column Types ==
|
||||
|
||||
Here are the Propel column types with some example mappings to native database and PHP types. There are also several ways to customize the mapping between these types.
|
||||
|
||||
=== Text Types ===
|
||||
|
||||
||'''Propel Type'''||'''Desc'''||'''Example Default DB Type (MySQL)'''||'''Default PHP Native Type'''||
|
||||
||CHAR||Fixed-lenght character data||CHAR||string||
|
||||
||VARCHAR||Variable-lenght character data||VARCHAR||string||
|
||||
||LONGVARCHAR||Long variable-length character data||TEXT||string||
|
||||
||CLOB||Character LOB (locator object)||LONGTEXT||string||
|
||||
|
||||
=== Numeric Types ===
|
||||
|
||||
||'''Propel Type'''||'''Desc'''||'''Example Default DB Type (MySQL)'''||'''Default PHP Native Type'''||
|
||||
||NUMERIC||Numeric data||DECIMAL||string (PHP int is limited)||
|
||||
||DECIMAL||Decimal data||DECIMAL||string (PHP int is limited)||
|
||||
||TINYINT||Tiny integer ||TINYINT||int||
|
||||
||SMALLINT||Small integer ||SMALLINT||int||
|
||||
||INTEGER||Integer||INTEGER||int||
|
||||
||BIGINT||Large integer||BIGINT||string (PHP int is limited)||
|
||||
||REAL||Real number||REAL||double||
|
||||
||FLOAT||Floating point number||FLOAT||double||
|
||||
||DOUBLE||Floating point number||DOUBLE||double||
|
||||
|
||||
=== Binary Types ===
|
||||
|
||||
||'''Propel Type'''||'''Desc'''||'''Example Default DB Type (MySQL)'''||'''Default PHP Native Type'''||
|
||||
||BINARY||Fixed-length binary data||BLOB||double||
|
||||
||VARBINARY||Variable-length binary data||MEDIUMBLOB||double||
|
||||
||LONGVARBINARY||Long variable-length binary data||LONGBLOB||double||
|
||||
||BLOB||Binary LOB (locator object)||LONGBLOB||string||
|
||||
|
||||
=== Temporal (Date/Time) Types ===
|
||||
|
||||
|
||||
||'''Propel Type'''||'''Desc'''||'''Example Default DB Type (MySQL)'''||'''Default PHP Native Type'''||
|
||||
||DATE||Date (e.g. YYYY-MM-DD)||DATE||DateTime object||
|
||||
||TIME||Time (e.g. HH:MM:SS)||TIME||DateTime object||
|
||||
||TIMESTAMP||Date + time (e.g. YYYY-MM-DD HH:MM:SS)||TIMESTAMP||DateTime object||
|
||||
|
||||
==== Legacy Temporal Types ====
|
||||
|
||||
The following Propel 1.2 types are still supported, but are no longer needed with Propel 1.3.
|
||||
|
||||
||'''Propel Type'''||'''Desc'''||'''Example Default DB Type (MySQL)'''||'''Default PHP Native Type'''||
|
||||
||BU_DATE||Pre-/post-epoch date (e.g. 1201-03-02)||DATE||DateTime object||
|
||||
||BU_TIMESTAMP||Pre-/post-epoch Date + time (e.g. 1201-03-02 12:33:00)||TIMESTAMP||DateTime object||
|
||||
|
||||
== Customizing Mappings ==
|
||||
|
||||
=== Specify Column Attributes ===
|
||||
|
||||
You can change the way that Propel maps its own types to native SQL types or to PHP types by overriding the values for a specific column.
|
||||
|
||||
For example:
|
||||
|
||||
(Overriding PHP type)
|
||||
{{{
|
||||
#!xml
|
||||
<column name="population_served" type="INTEGER" phpType="string"/>
|
||||
}}}
|
||||
|
||||
(Overriding SQL type)
|
||||
{{{
|
||||
#!xml
|
||||
<column name="ip_address" type="VARCHAR" sqlType="inet"/>
|
||||
}}}
|
||||
|
||||
=== Adding Vendor Info ===
|
||||
|
||||
Propel supports database-specific elements in the schema (currently only for MySQL). This "vendor" parameters affect the generated SQL. To add vendor data, add a `<vendor>` tag with a `type` attribute specifying the target database vendor. In the `<vendor>` tag, add `<parameter>` tags with a `name` and a `value` attribue. For instance:
|
||||
|
||||
{{{
|
||||
#!xml
|
||||
<table name="book">
|
||||
<vendor type="mysql">
|
||||
<parameter name="Engine" value="InnoDB"/>
|
||||
<parameter name="Charset" value="utf8"/>
|
||||
</vendor>
|
||||
</table>
|
||||
}}}
|
||||
|
||||
This will change the generated SQL table creation to look like:
|
||||
|
||||
{{{
|
||||
#!sql
|
||||
CREATE TABLE book
|
||||
()
|
||||
ENGINE = InnoDB
|
||||
DEFAULT CHARACTER SET utf8;
|
||||
}}}
|
||||
|
||||
Propel supports the following vendor parameters for MySQL:
|
||||
|
||||
{{{
|
||||
Name | Example values
|
||||
-----------------|---------------
|
||||
// in <table> element
|
||||
Engine | MYISAM (default), BDB, HEAP, ISAM, InnoDB, MERGE, MRG_MYISAM
|
||||
Charset | utf8, latin1, etc.
|
||||
Collate | utf8_unicode_ci, latin1_german1_ci, etc.
|
||||
Checksum | 0, 1
|
||||
Pack_Keys | 0, 1, DEFAULT
|
||||
Delay_key_write | 0, 1
|
||||
// in <column> element
|
||||
Charset | utf8, latin1, etc.
|
||||
Collate | utf8_unicode_ci, latin1_german1_ci, etc.
|
||||
// in <index> element
|
||||
Index_type | FULLTEXT
|
||||
}}}
|
||||
|
||||
=== Using Custom Platform ===
|
||||
|
||||
For overriding the mapping between Propel types and native SQL types, you can create your own Platform class and override the mapping.
|
||||
|
||||
For example:
|
||||
|
||||
{{{
|
||||
#!php
|
||||
<?php
|
||||
require_once 'propel/engine/platform/MysqlPlatform .php';
|
||||
class CustomMysqlPlatform extends MysqlPlatform {
|
||||
|
||||
/**
|
||||
* Initializes custom domain mapping.
|
||||
*/
|
||||
protected function initialize()
|
||||
{
|
||||
parent::initialize();
|
||||
$this->setSchemaDomainMapping(new Domain(PropelTypes::NUMERIC, "DECIMAL"));
|
||||
$this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARCHAR, "TEXT"));
|
||||
$this->setSchemaDomainMapping(new Domain(PropelTypes::BINARY, "BLOB"));
|
||||
$this->setSchemaDomainMapping(new Domain(PropelTypes::VARBINARY, "MEDIUMBLOB"));
|
||||
$this->setSchemaDomainMapping(new Domain(PropelTypes::LONGVARBINARY, "LONGBLOB"));
|
||||
$this->setSchemaDomainMapping(new Domain(PropelTypes::BLOB, "LONGBLOB"));
|
||||
$this->setSchemaDomainMapping(new Domain(PropelTypes::CLOB, "LONGTEXT"));
|
||||
}
|
||||
}
|
||||
}}}
|
||||
|
||||
You must then specify that mapping in the {{{build.properties}}} for your project:
|
||||
|
||||
{{{
|
||||
propel.platform.class = propel.engine.platform.${propel.database}Platform
|
||||
}}}
|
|
@ -1,70 +0,0 @@
|
|||
#!/bin/sh
|
||||
# Shell wrapper for Propel generator
|
||||
# $Id$
|
||||
#
|
||||
# This script will do the following:
|
||||
# - check for PHING_COMMAND env, if found, use it.
|
||||
# - if not found assume php is on the path
|
||||
# - check for PROPEL_GEN_HOME env, if found use it
|
||||
# - if not look for it
|
||||
|
||||
if [ -z "$PROPEL_GEN_HOME" ] ; then
|
||||
|
||||
# try to find Propel
|
||||
if [ -d /opt/propel/generator ] ; then
|
||||
PROPEL_GEN_HOME=/opt/propel/generator
|
||||
fi
|
||||
|
||||
if [ -d "${HOME}/opt/propel/generator" ] ; then
|
||||
PROPEL_GEN_HOME="${HOME}/opt/propel/generator"
|
||||
fi
|
||||
|
||||
if [ -d "/usr/local/propel/generator" ] ; then
|
||||
PROPEL_GEN_HOME="/usr/local/propel/generator"
|
||||
fi
|
||||
|
||||
if [ -d "${HOME}/usr/propel/generator" ] ; then
|
||||
PROPEL_GEN_HOME="${HOME}/usr/propel/generator"
|
||||
fi
|
||||
|
||||
## resolve links - the script name may be a link to phing's home
|
||||
PRG="$0"
|
||||
progname=`basename "$0"`
|
||||
saveddir=`pwd`
|
||||
|
||||
# need this for relative symlinks
|
||||
dirname_prg=`dirname "$PRG"`
|
||||
cd "$dirname_prg"
|
||||
|
||||
while [ -h "$PRG" ] ; do
|
||||
ls=`ls -ld "$PRG"`
|
||||
link=`expr "$ls" : '.*-> \(.*\)$'`
|
||||
if expr "$link" : '/.*' > /dev/null; then
|
||||
PRG="$link"
|
||||
else
|
||||
PRG=`dirname "$PRG"`"/$link"
|
||||
fi
|
||||
done
|
||||
|
||||
cd "$saveddir"
|
||||
|
||||
PROPEL_GEN_HOME=`dirname "$PRG"`/..
|
||||
|
||||
# make it fully qualified
|
||||
PROPEL_GEN_HOME=`cd "$PROPEL_GEN_HOME" && pwd`
|
||||
|
||||
# make it available in PHP via getenv("PROPEL_GEN_HOME")
|
||||
export PROPEL_GEN_HOME
|
||||
|
||||
fi
|
||||
|
||||
if [ -z "$PHING_COMMAND" ] ; then
|
||||
# echo "WARNING: PHING_COMMAND environment not set. (Assuming phing on PATH)"
|
||||
export PHING_COMMAND="phing"
|
||||
fi
|
||||
|
||||
if [ $# = 1 ] ; then
|
||||
$PHING_COMMAND -f $PROPEL_GEN_HOME/build.xml -Dusing.propel-gen=true -Dproject.dir=$saveddir $*
|
||||
else
|
||||
$PHING_COMMAND -f $PROPEL_GEN_HOME/build.xml -Dusing.propel-gen=true -Dproject.dir=$*
|
||||
fi
|
|
@ -1,513 +0,0 @@
|
|||
<project name="propel" default="main">
|
||||
|
||||
<!--
|
||||
Note - You should not have to edit this file.
|
||||
|
||||
Instead, if calling build-propel.xml directly, edit the build.properties
|
||||
that is in the same directory. If calling build-propel.xml via another
|
||||
build file, you can also use the build.properties in the same directory,
|
||||
or set the property propel.contextProperties to the file
|
||||
to use in place of build.properties (e.g. project.properties).
|
||||
-->
|
||||
|
||||
<property name="build.properties" value="build.properties"/>
|
||||
<property name="propel.contextProperties" value="./${build.properties}"/>
|
||||
<property name="propel.home" value="."/>
|
||||
|
||||
<available file="${propel.home}/build.properties" property="globalBuildPopertiesExists"/>
|
||||
|
||||
<if>
|
||||
<and>
|
||||
<isset property="globalBuildPopertiesExists"/>
|
||||
</and>
|
||||
<then>
|
||||
<property file="${propel.home}/build.properties"/>
|
||||
</then>
|
||||
</if>
|
||||
|
||||
<!--
|
||||
The default.properties file will map old properties to the new ones along
|
||||
with setting the corret defaults.
|
||||
-->
|
||||
<property file="${propel.home}/default.properties"/>
|
||||
|
||||
<!--
|
||||
Do forward declarations of all of our tasks to
|
||||
centralize them and clean up the targets.
|
||||
-->
|
||||
|
||||
<path id="propelclasses">
|
||||
<pathelement dir="${propel.home}/lib/"/>
|
||||
<pathelement dir="${propel.project.dir}/"/>
|
||||
</path>
|
||||
|
||||
<taskdef
|
||||
name="propel-data-model"
|
||||
classname="task.PropelDataModelTemplateTask" classpathRef="propelclasses"/>
|
||||
<taskdef
|
||||
name="propel-om"
|
||||
classname="task.PropelOMTask" classpathRef="propelclasses"/>
|
||||
<taskdef
|
||||
name="propel-data-dtd"
|
||||
classname="task.PropelDataDTDTask" classpathRef="propelclasses"/>
|
||||
<taskdef
|
||||
name="propel-data-dump"
|
||||
classname="task.PropelDataDumpTask" classpathRef="propelclasses"/>
|
||||
<taskdef
|
||||
name="propel-data-sql"
|
||||
classname="task.PropelDataSQLTask" classpathRef="propelclasses"/>
|
||||
<taskdef
|
||||
name="propel-schema-reverse"
|
||||
classname="task.PropelSchemaReverseTask" classpathRef="propelclasses"/>
|
||||
<taskdef
|
||||
name="propel-sql"
|
||||
classname="task.PropelSQLTask" classpathRef="propelclasses"/>
|
||||
<taskdef
|
||||
name="propel-sql-exec"
|
||||
classname="task.PropelSQLExec" classpathRef="propelclasses"/>
|
||||
<taskdef
|
||||
name="propel-graphviz"
|
||||
classname="task.PropelGraphvizTask" classpathRef="propelclasses"/>
|
||||
<taskdef
|
||||
name="propel-convert-conf"
|
||||
classname="task.PropelConvertConfTask" classpathRef="propelclasses"/>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- M A I N T A R G E T -->
|
||||
<!-- ================================================================ -->
|
||||
<!-- This default target will run all the targets that generate -->
|
||||
<!-- source. You will probably only run this target once then -->
|
||||
<!-- call individual targets as necessary to update your sources -->
|
||||
<!-- when you change your XML schema. -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<target
|
||||
name="main"
|
||||
depends="mysqli-check"
|
||||
description="==> generates sql + om classes">
|
||||
|
||||
<phingcall target="sql"/>
|
||||
<phingcall target="om"/>
|
||||
<phingcall target="convert-conf"/>
|
||||
</target>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- C H E C K R U N O N L Y O N S C H E M A C H A N G E -->
|
||||
<!-- ================================================================ -->
|
||||
<!-- Maps the propel.runOnlyOnSchemaChange to -->
|
||||
<!-- propel.internal.runOnlyOnSchemaChange -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<target name="check-run-only-on-schema-change">
|
||||
<condition property="propel.internal.runOnlyOnSchemaChange">
|
||||
<equals arg1="${propel.runOnlyOnSchemaChange}" arg2="true"/>
|
||||
</condition>
|
||||
</target>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- G E N E R A T E P R O J E C T S Q L -->
|
||||
<!-- ================================================================ -->
|
||||
<!-- Generate the SQL for your project, These are in addition -->
|
||||
<!-- to the base Turbine tables! The tables you require for your -->
|
||||
<!-- project should be specified in project-schema.xml. -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<target
|
||||
name="sql-check"
|
||||
depends="check-run-only-on-schema-change"
|
||||
if="propel.internal.runOnlyOnSchemaChange">
|
||||
<uptodate
|
||||
property="propel.internal.sql.uptodate"
|
||||
targetfile="${propel.sql.dir}/${propel.schema.default.basename}.sql">
|
||||
<srcfiles dir="${propel.schema.dir}" includes="**/${propel.schema.default.basename}.xml" />
|
||||
</uptodate>
|
||||
</target>
|
||||
|
||||
<!-- temporary target to check whether postgres is being used with identifier quoting ON.
|
||||
If so, a warning is issued, since identifier quoting is only paritally implemented & this point. -->
|
||||
<target name="pgsql-quoting-check">
|
||||
<if>
|
||||
<and>
|
||||
<equals arg1="${propel.database}" arg2="pgsql"/>
|
||||
<equals arg1="${propel.disableIdentifierQuoting}" arg2=""/>
|
||||
</and>
|
||||
<then>
|
||||
<warn>ATTENTION: It appears you are using PostgreSQL and you have identifier-quoting turned on.</warn>
|
||||
<warn>It is suggested that you disable identifier quoting when using PostgreSQL -- especially if you</warn>
|
||||
<warn>have case-sensitive columns in your database.</warn>
|
||||
<warn></warn>
|
||||
<warn>To disable identifier quoting, add the following property to your build.properties (or specify</warn>
|
||||
<warn>it using -D on commandline):</warn>
|
||||
<warn></warn>
|
||||
<warn>propel.disableIdentifierQuoting=true</warn>
|
||||
<warn></warn>
|
||||
<warn>You can ignore this warning if you understand the issues related to case-sensitivity and Propel's</warn>
|
||||
<warn>DDL-only implementation of identifier quoting.</warn>
|
||||
</then>
|
||||
</if>
|
||||
</target>
|
||||
|
||||
<!-- temporary target to check whether mysqli is being used
|
||||
If so, a warning is issued, since this is deprecated -->
|
||||
<target name="mysqli-check">
|
||||
<if>
|
||||
<and>
|
||||
<equals arg1="${propel.database}" arg2="mysqli"/>
|
||||
</and>
|
||||
<then>
|
||||
<warn>ATTENTION: It appears you are using the mysqli driver.</warn>
|
||||
<warn></warn>
|
||||
<warn>This driver is no longer supported by Propel because Propel now uses PDO for database connections.</warn>
|
||||
<warn>Please use mysqli driver instead.</warn>
|
||||
<fail>Use 'mysql' instead of 'mysqli' for your propel.database property.</fail>
|
||||
</then>
|
||||
</if>
|
||||
</target>
|
||||
|
||||
<target
|
||||
name="sql"
|
||||
depends="sql-check,pgsql-quoting-check,mysqli-check"
|
||||
unless="propel.internal.sql.uptodate"
|
||||
description="==> generates the SQL for your project">
|
||||
|
||||
<echo message="+------------------------------------------+"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="| Generating SQL for YOUR Propel project! |"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="+------------------------------------------+"/>
|
||||
|
||||
<phingcall target="sql-template"/>
|
||||
|
||||
</target>
|
||||
|
||||
<target name="sql-template">
|
||||
<propel-sql
|
||||
validate="${propel.schema.validate}"
|
||||
xsd="${propel.schema.xsd.file}"
|
||||
xsl="${propel.schema.xsl.file}"
|
||||
outputDirectory="${propel.sql.dir}"
|
||||
sqldbmap="${propel.sql.dir}/sqldb.map"
|
||||
targetDatabase="${propel.database}"
|
||||
packageObjectModel="${propel.packageObjectModel}"
|
||||
url="${propel.database.url}"
|
||||
userId="${propel.database.user}"
|
||||
password="${propel.database.password}">
|
||||
<mapper type="glob" from="${propel.sql.mapper.from}" to="${propel.sql.mapper.to}"/>
|
||||
<schemafileset dir="${propel.schema.dir}"
|
||||
includes="${propel.schema.sql.includes}"
|
||||
excludes="${propel.schema.sql.excludes}"
|
||||
/>
|
||||
</propel-sql>
|
||||
</target>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- C R E A T E T A R G E T D A T A B A S E -->
|
||||
<!-- ================================================================ -->
|
||||
<!-- Create the target database by executing a generated script -->
|
||||
<!-- that is capable of performing the task. -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<target name="create-db-check">
|
||||
<condition property="propel.internal.manualCreation">
|
||||
<equals arg1="${propel.database.manualCreation}" arg2="true"/>
|
||||
</condition>
|
||||
</target>
|
||||
|
||||
<target
|
||||
name="create-db"
|
||||
unless="propel.internal.manualCreation"
|
||||
depends="create-db-check,mysqli-check"
|
||||
description="==> generates the target database">
|
||||
|
||||
<fail message="create-db target temporarily disabled, while we replace creole components."/>
|
||||
|
||||
<!--
|
||||
<propel-data-model
|
||||
validate="${propel.schema.validate}"
|
||||
xsd="${propel.schema.xsd.file}"
|
||||
xsl="${propel.schema.xsl.file}"
|
||||
controlTemplate="${propel.template.sqlDbInit}"
|
||||
outputDirectory="${propel.sql.dir}"
|
||||
outputFile="create-db.sql"
|
||||
targetDatabase="${propel.database}"
|
||||
dbEncoding="${propel.database.encoding}"
|
||||
templatePath="${propel.templatePath}"
|
||||
packageObjectModel="${propel.packageObjectModel}">
|
||||
<schemafileset dir="${propel.schema.dir}"
|
||||
includes="${propel.schema.create-db.includes}"
|
||||
excludes="${propel.schema.create-db.excludes}"
|
||||
/>
|
||||
</propel-data-model>
|
||||
|
||||
<echo message="Executing the create-db.sql script ..."/>
|
||||
|
||||
<sql
|
||||
autocommit="true"
|
||||
driver="${propel.database.driver}"
|
||||
onerror="continue"
|
||||
src="${propel.sql.dir}/create-db.sql"
|
||||
url="${propel.database.createUrl}"
|
||||
/>
|
||||
-->
|
||||
</target>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- I N S E R T S I N G L E S Q L F I L E S -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<target
|
||||
name="insert-sql"
|
||||
description="==> inserts the generated sql ">
|
||||
|
||||
<propel-sql-exec
|
||||
autocommit="true"
|
||||
onerror="continue"
|
||||
sqldbmap="${propel.sql.dir}/sqldb.map"
|
||||
srcDir="${propel.sql.dir}"
|
||||
url="${propel.database.buildUrl}"
|
||||
userId="${propel.database.user}"
|
||||
password="${propel.database.password}"
|
||||
/>
|
||||
</target>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- N E W R E V E R S E T O X M L -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<target
|
||||
name="reverse"
|
||||
description="==> generate xml schema from reverse-engineered database (new)">
|
||||
|
||||
<echo message="+-----------------------------------------------+"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="| Generating XML from PDO connection ! |"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="+-----------------------------------------------+"/>
|
||||
|
||||
<propel-schema-reverse
|
||||
databaseName="${propel.project}"
|
||||
dbSchema="${propel.database.schema}"
|
||||
dbEncoding="${propel.database.encoding}"
|
||||
url="${propel.database.buildUrl}"
|
||||
userId="${propel.database.user}"
|
||||
password="${propel.database.password}"
|
||||
outputFile="${propel.schema.dir}/${propel.default.schema.basename}.xml"
|
||||
samePhpName="${propel.samePhpName}"
|
||||
addVendorInfo="${propel.addVendorInfo}"
|
||||
addValidators="${propel.addValidators}"
|
||||
/>
|
||||
|
||||
</target>
|
||||
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- Generate SQL from XML data file -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<target
|
||||
name="datasql"
|
||||
description="==> generates sql from data xml">
|
||||
|
||||
<echo message="+-----------------------------------------------+"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="| Generating SQL from data XML ! |"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="+-----------------------------------------------+"/>
|
||||
|
||||
<propel-data-sql
|
||||
validate="${propel.schema.validate}"
|
||||
xsd="${propel.schema.xsd.file}"
|
||||
xsl="${propel.schema.xsl.file}"
|
||||
outputDirectory="${propel.sql.dir}"
|
||||
sqldbmap="${propel.sql.dir}/sqldb.map"
|
||||
dbEncoding="${propel.database.encoding}"
|
||||
targetDatabase="${propel.database}"
|
||||
datadbmap="${propel.schema.dir}/datadb.map"
|
||||
srcDir="${propel.schema.dir}">
|
||||
<mapper type="glob" from="${propel.datasql.mapper.from}" to="${propel.datasql.mapper.to}"/>
|
||||
<schemafileset dir="${propel.schema.dir}"
|
||||
includes="${propel.schema.datadtd.includes}"
|
||||
excludes="${propel.schema.datadtd.excludes}"
|
||||
/>
|
||||
</propel-data-sql>
|
||||
</target>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- Dump data from database into xml file -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<target
|
||||
name="datadump"
|
||||
description="==> dump data from database into xml file">
|
||||
|
||||
<echo message="+-----------------------------------------------+"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="| Dumping the data from database into XML |"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="+-----------------------------------------------+"/>
|
||||
|
||||
<propel-data-dump
|
||||
validate="${propel.schema.validate}"
|
||||
xsd="${propel.schema.xsd.file}"
|
||||
xsl="${propel.schema.xsl.file}"
|
||||
targetDatabase="${propel.database}"
|
||||
datadbmap="${propel.schema.dir}/datadb.map"
|
||||
databaseDriver="${propel.database.driver}"
|
||||
dbEncoding="${propel.database.encoding}"
|
||||
databaseUrl="${propel.database.url}"
|
||||
databaseUser="${propel.database.user}"
|
||||
databasePassword="${propel.database.password}"
|
||||
outputDirectory="${propel.schema.dir}">
|
||||
<mapper type="glob" from="${propel.datadump.mapper.from}" to="${propel.datadump.mapper.to}"/>
|
||||
<schemafileset dir="${propel.schema.dir}"
|
||||
includes="${propel.schema.datadtd.includes}"
|
||||
excludes="${propel.schema.datadtd.excludes}"
|
||||
/>
|
||||
</propel-data-dump>
|
||||
</target>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- G E N E R A T E P R O J E C T D A T A D T D -->
|
||||
<!-- ================================================================ -->
|
||||
<!-- Generate the DATA DTD for your project -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<target
|
||||
name="datadtd"
|
||||
description="==> generates the DATA DTD for your project">
|
||||
|
||||
<echo message="+-----------------------------------------------+"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="| Generating Data DTD for YOUR Propel project! |"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="+-----------------------------------------------+"/>
|
||||
|
||||
<propel-data-dtd
|
||||
validate="${propel.schema.validate}"
|
||||
xsd="${propel.schema.xsd.file}"
|
||||
xsl="${propel.schema.xsl.file}"
|
||||
targetDatabase="${propel.database}"
|
||||
outputDirectory="${propel.output.dir}"
|
||||
templatePath="${propel.templatePath}">
|
||||
<!-- TODO: add properties for the mapper type, from, and to -->
|
||||
<mapper type="glob" from="${propel.datadtd.mapper.from}" to="${propel.datadtd.mapper.to}"/>
|
||||
<schemafileset dir="${propel.schema.dir}"
|
||||
includes="${propel.schema.datadtd.includes}"
|
||||
excludes="${propel.schema.datadtd.excludes}"
|
||||
/>
|
||||
</propel-data-dtd>
|
||||
</target>
|
||||
|
||||
<!-- ================================================================ -->
|
||||
<!-- G E N E R A T E P R O J E C T P E E R B A S E D O M -->
|
||||
<!-- ================================================================ -->
|
||||
<!-- Generate the Peer-based object model for your project. -->
|
||||
<!-- These are in addition to the base Propel OM! -->
|
||||
<!-- ================================================================ -->
|
||||
|
||||
<target
|
||||
name="om-check"
|
||||
depends="check-run-only-on-schema-change"
|
||||
if="propel.internal.runOnlyOnSchemaChange">
|
||||
<uptodate
|
||||
property="propel.internal.om.uptodate"
|
||||
targetfile="${propel.php.dir}/report.${propel.project}.om.generation">
|
||||
<srcfiles dir="${propel.schema.dir}" includes="**/${propel.schema.om.includes}.xml" />
|
||||
</uptodate>
|
||||
</target>
|
||||
|
||||
<target
|
||||
name="om"
|
||||
depends="om-check,mysqli-check"
|
||||
unless="propel.internal.om.uptodate"
|
||||
description="==> generates the Peer-based object model for your project">
|
||||
|
||||
<echo message="+------------------------------------------+"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="| Generating Peer-based Object Model for |"/>
|
||||
<echo message="| YOUR Propel project! |"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="+------------------------------------------+"/>
|
||||
|
||||
<phingcall target="om-template"/>
|
||||
<!--<phingcall target="om-tar"/>-->
|
||||
</target>
|
||||
|
||||
<target name="om-template">
|
||||
<propel-om
|
||||
validate="${propel.schema.validate}"
|
||||
xsd="${propel.schema.xsd.file}"
|
||||
xsl="${propel.schema.xsl.file}"
|
||||
outputDirectory="${propel.php.dir}"
|
||||
targetDatabase="${propel.database}"
|
||||
targetPackage="${propel.targetPackage}"
|
||||
targetPlatform="${propel.targetPlatform}"
|
||||
packageObjectModel="${propel.packageObjectModel}">
|
||||
<schemafileset dir="${propel.schema.dir}"
|
||||
includes="${propel.schema.om.includes}"
|
||||
excludes="${propel.schema.om.excludes}"
|
||||
/>
|
||||
</propel-om>
|
||||
</target>
|
||||
|
||||
<!-- ================================================================== -->
|
||||
<!-- X M L R U N T I M E C O N F T O P H P A R R A Y -->
|
||||
<!-- ================================================================== -->
|
||||
|
||||
<target
|
||||
name="convert-conf"
|
||||
description="==> converts properties file to PHP array">
|
||||
|
||||
<echo message="+------------------------------------------+"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="| Converting runtime config file to an |"/>
|
||||
<echo message="| array dump for improved performance. |"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="+------------------------------------------+"/>
|
||||
|
||||
<echo>Output file: ${propel.runtime.phpconf.file}</echo>
|
||||
<echo>XMLFile: ${propel.conf.dir}/${propel.runtime.conf.file}</echo>
|
||||
|
||||
<propel-convert-conf
|
||||
targetDatabase="${propel.database}"
|
||||
xsd="${propel.schema.xsd.file}"
|
||||
xsl="${propel.schema.xsl.file}"
|
||||
xmlConfFile="${propel.conf.dir}/${propel.runtime.conf.file}"
|
||||
outputDirectory="${propel.phpconf.dir}"
|
||||
outputFile="${propel.runtime.phpconf.file}"
|
||||
packageObjectModel="${propel.packageObjectModel}">
|
||||
<schemafileset dir="${propel.schema.dir}"
|
||||
includes="${propel.schema.sql.includes}"
|
||||
excludes="${propel.schema.sql.excludes}"
|
||||
/>
|
||||
</propel-convert-conf>
|
||||
|
||||
</target>
|
||||
|
||||
<target
|
||||
name="graphviz"
|
||||
depends="sql-check"
|
||||
description="==> generates Graphviz file for your project">
|
||||
|
||||
<echo message="+------------------------------------------+"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="| Generating Graphiz for YOUR Propel |"/>
|
||||
<echo message="| project! |"/>
|
||||
<echo message="| |"/>
|
||||
<echo message="+------------------------------------------+"/>
|
||||
|
||||
<propel-graphviz
|
||||
outputDirectory="${propel.graph.dir}"
|
||||
targetDatabase="${propel.database}"
|
||||
sqldbmap="${propel.sql.dir}/sqldb.map"
|
||||
packageObjectModel="${propel.packageObjectModel}">
|
||||
<mapper type="glob" from="${propel.sql.mapper.from}" to="${propel.sql.mapper.to}"/>
|
||||
<schemafileset dir="${propel.schema.dir}"
|
||||
includes="${propel.schema.sql.includes}"
|
||||
excludes="${propel.schema.sql.excludes}"
|
||||
/>
|
||||
</propel-graphviz>
|
||||
</target>
|
||||
|
||||
|
||||
</project>
|
|
@ -1,192 +0,0 @@
|
|||
# -------------------------------------------------------------------
|
||||
#
|
||||
# P R O P E L C O N F I G U R A T I O N F I L E
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
# This file contains some example properties. Ideally properties
|
||||
# should be specified in the project-specific build.properties file;
|
||||
# however, this file can be used to specify non-default properties
|
||||
# that you would like to use accross all of your Propel projects.
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
|
||||
propel.home = .
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# P R O J E C T
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
# This is the name of your Propel project. The name of your Propel
|
||||
# project is used (by default) to determine where the generator will
|
||||
# find needed configuration files and will place resuilting build
|
||||
# files. E.g. if your project is named 'killerapp', Propel will
|
||||
# look here for schema.xml and runtime-conf.xml files:
|
||||
#
|
||||
# projects/killerapp/
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
# You can set this here, but it's preferrable to set this in a
|
||||
# project-specific build.properties file.
|
||||
#
|
||||
# propel.project = bookstore
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# T A R G E T D A T A B A S E
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
# This is the target database, only considered when generating
|
||||
# the SQL for your Propel project. Your possible choices are:
|
||||
#
|
||||
# mssql, mysql, oracle, pgsql, sqlite
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
# You can set this here, but it's preferrable to set this in a
|
||||
# project-specific build.properties file.
|
||||
#
|
||||
# propel.database = mysql
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# O B J E C T M O D E L I N F O R M A T I O N
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
# These settings will allow you to customize the way your
|
||||
# Peer-based object model is created.
|
||||
# -------------------------------------------------------------------
|
||||
# addGenericAccessors
|
||||
# If true, Propel adds methods to get database fields by name/position.
|
||||
#
|
||||
# addGenericMutators
|
||||
# If true, Propel adds methods to set database fields by name/position.
|
||||
#
|
||||
# addSaveMethod
|
||||
# If true, Propel adds tracking code to determine how to save objects.
|
||||
#
|
||||
# addTimeStamp
|
||||
# If true, Propel true puts time stamps in phpdoc of generated om files.
|
||||
#
|
||||
# basePrefix
|
||||
# A string to pre-pend to the file names of base data and peer objects.
|
||||
#
|
||||
# complexObjectModel
|
||||
# If true, Propel generates data objects with collection support and
|
||||
# methods to easily retreive foreign key relationships.
|
||||
#
|
||||
# targetPackage
|
||||
# Sets the PHP "package" the om files will generated to, e.g.
|
||||
# "com.company.project.om".
|
||||
#
|
||||
# targetPlatform
|
||||
# Sets whether Propel is building classes for php5 (default)
|
||||
# or php4 (experimental).
|
||||
#
|
||||
# packageObjectModel
|
||||
# Sets whether Propel is packaging ObjectModel fro several
|
||||
# [package].schema.xml files. The <database package="packageName">
|
||||
# attribute has to be set then. (warning: this is experimental!)
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
# classes will be put in (and included from) this directory
|
||||
# e.g. if package is "bookstore" then om will expect include('bookstore/Book.php'); to work.
|
||||
# use dot-path notation -- e.g. my.bookstore -> my/bookstore.
|
||||
#
|
||||
propel.targetPackage = ${propel.project}
|
||||
|
||||
propel.addGenericAccessors = false
|
||||
propel.addGenericMutators = false
|
||||
propel.addSaveMethod = true
|
||||
propel.addTimeStamp = true
|
||||
propel.basePrefix = Base
|
||||
propel.complexObjectModel = true
|
||||
propel.targetPlatform = php5
|
||||
propel.packageObjectModel = false
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# D B C O N N E C T I O N S E T T I N G S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
# PDO connection settings. These connection settings are used by
|
||||
# build tagets that perform database operations (e.g. 'insert-sql',
|
||||
# 'reverse').
|
||||
#
|
||||
# You can set them here, but it's preferrable to set these properties
|
||||
# in a project-specific build.properties file.
|
||||
#
|
||||
|
||||
# If you want to use a custom driver, specify it below, otherwise
|
||||
# leave it blank or comment it out to use Creole stock driver.
|
||||
#
|
||||
# propel.database.driver = creole.drivers.sqlite.SQLiteConnection
|
||||
|
||||
# Note that if you do not wish to specify the database (e.g. if you
|
||||
# are using multiple databses) you can use the @DB@ token which
|
||||
# will be replaced with a database at runtime.
|
||||
#
|
||||
# propel.database.url = mysql:host=$host;dbname=$database
|
||||
|
||||
# For MySQL or Oracle, you also need to specify username & password
|
||||
# propel.database.user = [db username]
|
||||
# propel.database.password = [db password]
|
||||
|
||||
# Use the URL below to specify a DSN to used to create the database.
|
||||
# Note that this URL should not contain the database name, as you will
|
||||
# get an error if the database does not exist.
|
||||
# (This does not apply to SQLite since the databse is automatically created
|
||||
# when the connection is made -- if it does not already exist.)
|
||||
#
|
||||
# propel.database.createUrl = mysql:host=$host;dbname=$database
|
||||
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# D A T A B A S E TO X M L
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# samePhpName
|
||||
# If true, the reverse task will set the phpName attribute for the
|
||||
# tables and columns to be the same as SQL name.
|
||||
#
|
||||
# addVendorInfo
|
||||
# If true, the reverse task will add vendor specific information
|
||||
# to the database schema
|
||||
#
|
||||
# addValidators
|
||||
# Bitfield like option to turn on/off addition of Validator and
|
||||
# Rule tags to the schema. Uses a boolean syntax like in php.ini.
|
||||
# Allowed tokens are:
|
||||
# none add no validators)
|
||||
# all add all validators)
|
||||
# maxlength add maxlengths for string type columns)
|
||||
# maxvalue add maxvalue for numeric columns)
|
||||
# type add notmatch validators for numeric columns)
|
||||
# required add required validators for required columns)
|
||||
# unique add unique validators for unique indexes)
|
||||
# Allowed operators are:
|
||||
# & bitwise AND
|
||||
# | bitwise OR
|
||||
# ~ bitwise NOT
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
# propel.samePhpName = false
|
||||
# propel.addVendorInfo=true
|
||||
# propel.addValidators=none
|
||||
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# D A T A B A S E B U I L D C O N F I G
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
# Some databases provide some configuration options that can be set
|
||||
# in this script.
|
||||
#
|
||||
# === MySQL
|
||||
# propel.mysql.tableType
|
||||
# Use this property to set the table type of generated tables (e.g. InnoDB, MyISAM).
|
|
@ -1,184 +0,0 @@
|
|||
<!--
|
||||
Use this file to faciliate easy per-project building.
|
||||
|
||||
Simply create a build.properties file in your project directory,
|
||||
for example ./projects/bookstore/build.properties, that contains
|
||||
any needed (i.e. to override) values for that project.
|
||||
|
||||
Call this build script and specify the name of the project and
|
||||
(optionally) the name of the target you wish to execute (default is
|
||||
'main' target) of build-propel.xml.
|
||||
|
||||
Normal use:
|
||||
$> phing -Dproject=bookstore
|
||||
|
||||
Specific target:
|
||||
$> phing -Dproject=bookstore -Dtarget=insert-sql
|
||||
|
||||
-->
|
||||
<project name="propel-project-builder" default="main">
|
||||
|
||||
<!-- in case ${project.dir} was specified on command line, we set the project.dir
|
||||
property here. If it wasn't set, then this will be bogus, but it will
|
||||
be overridden by the "set-project-dir" target. -->
|
||||
<resolvepath propertyName="propel.project.dir" file="${project.dir}" dir="${application.startdir}"/>
|
||||
|
||||
<!-- set a default target if none provided -->
|
||||
<property name="target" value="main"/>
|
||||
|
||||
<!-- Set a default name for the build.properties file.
|
||||
This allows for overriding the name of the build.properties file; however,
|
||||
Propel still expects to find the file in the ${propel.project.dir}.
|
||||
-->
|
||||
<property name="build.properties" value="build.properties"/>
|
||||
|
||||
<target name="check-buildprops-exists">
|
||||
<available file="${propel.project.dir}/${build.properties}" property="projBuildPopertiesExists"/>
|
||||
</target>
|
||||
|
||||
<target name="check-buildprops" unless="projBuildPopertiesExists" depends="check-buildprops-exists">
|
||||
<echo message="====================================================="/>
|
||||
<echo message="Could not open ${build.properties} file:"/>
|
||||
<echo message=" ${propel.project.dir}/${build.properties}"/>
|
||||
<echo message=" "/>
|
||||
<echo message="Make sure that '${propel.project.dir}' is a valid path"/>
|
||||
<echo message="and that it contains a ${build.properties} file."/>
|
||||
<echo message="====================================================="/>
|
||||
|
||||
<fail message="Missing configuration file (see description above)."/>
|
||||
</target>
|
||||
|
||||
<target name="check-project-or-dir-set">
|
||||
<condition property="projectOrDirSet">
|
||||
<or>
|
||||
<isset property="project"/>
|
||||
<isset property="project.dir"/>
|
||||
</or>
|
||||
</condition>
|
||||
</target>
|
||||
|
||||
<target name="check-buildprops-for-propel-gen" if="using.propel-gen" unless="projBuildPopertiesExists" depends="check-buildprops-exists">
|
||||
<echo message="=========================================================="/>
|
||||
<echo message="Could not open ${build.properties} file:"/>
|
||||
<echo message=" ${propel.project.dir}/${build.properties}"/>
|
||||
<echo message=" "/>
|
||||
<echo message="Project directory not specified or invalid. You must "/>
|
||||
<echo message="specify the path to your project directory and your "/>
|
||||
<echo message="project directory must contain your ${build.properties} "/>
|
||||
<echo message="and schema.xml files. "/>
|
||||
<echo message=" "/>
|
||||
<echo message="Usage: "/>
|
||||
<echo message=" "/>
|
||||
<echo message="$> propel-gen /path/to/projectdir [target]"/>
|
||||
<echo message=" "/>
|
||||
<echo message="=========================================================="/>
|
||||
<fail message="No project directory specified."/>
|
||||
</target>
|
||||
|
||||
<target name="check-project-set" unless="projectOrDirSet" depends="check-project-or-dir-set">
|
||||
<echo message="====================================================="/>
|
||||
<echo message="Project not specified. You must enter a project name. "/>
|
||||
<echo message="In the future you can enter it on the command line: "/>
|
||||
<echo message=" "/>
|
||||
<echo message="-Dproject=bookstore"/>
|
||||
<echo message=" "/>
|
||||
<echo message="This will attempt to find your project directory in"/>
|
||||
<echo message="the default directory (./projects/bookstore)."/>
|
||||
<echo message=" "/>
|
||||
<echo message="You can also avoid this message and specicfy a custom "/>
|
||||
<echo message="directory, using the project.dir property:"/>
|
||||
<echo message=" "/>
|
||||
<echo message="-Dproject.dir=/path/to/bookstore"/>
|
||||
<echo message="====================================================="/>
|
||||
<input propertyname="project" promptChar=":">Project name</input>
|
||||
<property name="propel.project" value="${project}" override="true"/>
|
||||
</target>
|
||||
|
||||
<target name="set-project-dir" unless="project.dir" depends="check-project-set">
|
||||
<echo>No project.dir was specified, using default path: ./projects/${project}</echo>
|
||||
<property name="propel.project.dir" value="./projects/${project}" override="true"/>
|
||||
</target>
|
||||
|
||||
<target name="configure" depends="set-project-dir,check-buildprops-for-propel-gen,check-buildprops">
|
||||
<if>
|
||||
<isset property="additional.properties"/>
|
||||
<then>
|
||||
<echo>Processing additional properties file: ${additional.properties}</echo>
|
||||
<resolvepath propertyName="additional.properties.resolved" file="${additional.properties}" dir="${application.startdir}"/>
|
||||
<property file="${additional.properties.resolved}"/>
|
||||
</then>
|
||||
</if>
|
||||
<echo msg="Loading project-specific props from ${propel.project.dir}/${build.properties}"/>
|
||||
<property file="${propel.project.dir}/${build.properties}"/>
|
||||
</target>
|
||||
|
||||
<target name="main" depends="configure" description="The main target. Includes project-specific build.properties and calls the build-propel.xml script">
|
||||
|
||||
<phing phingfile="./build-propel.xml" target="${target}"/>
|
||||
|
||||
</target>
|
||||
|
||||
<!--
|
||||
Convenience mappings to build-propel.xml main targets
|
||||
|
||||
This makes it possible to use this buildfile w/o needing to specify
|
||||
target as a property, e.g.:
|
||||
|
||||
$> phing -Dproject=bookstore insert-sql
|
||||
|
||||
The main reason for this is just consistency w/ old build-propel.xml file
|
||||
(primarily for documentation & user confusion avoidance reasons). There are relatively
|
||||
few & infrequently changing main targets of build-propel.xml, so it's a non-
|
||||
issue as far as maintenance is concerned.
|
||||
-->
|
||||
|
||||
<target name="convert-conf" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="convert-conf"/>
|
||||
</target>
|
||||
|
||||
<target name="create-db" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="create-db"/>
|
||||
</target>
|
||||
|
||||
<target name="reverse" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="reverse"/>
|
||||
</target>
|
||||
|
||||
<target name="datadtd" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="datadtd"/>
|
||||
</target>
|
||||
|
||||
<target name="datadump" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="datadump"/>
|
||||
</target>
|
||||
|
||||
<target name="datasql" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="datasql"/>
|
||||
</target>
|
||||
|
||||
<target name="insert-sql" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="insert-sql"/>
|
||||
</target>
|
||||
|
||||
<target name="om" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="om"/>
|
||||
</target>
|
||||
|
||||
<target name="new-om" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="new-om"/>
|
||||
</target>
|
||||
|
||||
<target name="sql" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="sql"/>
|
||||
</target>
|
||||
|
||||
<target name="old-sql" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="old-sql"/>
|
||||
</target>
|
||||
|
||||
<target name="graphviz" depends="configure">
|
||||
<phing phingfile="build-propel.xml" target="graphviz"/>
|
||||
</target>
|
||||
|
||||
|
||||
</project>
|
|
@ -1,124 +0,0 @@
|
|||
<!--
|
||||
Use this file to faciliate easy per-project building.
|
||||
|
||||
Simply create a build.properties file in this directory,
|
||||
that contains any needed (i.e. to override) values for this project.
|
||||
|
||||
Call this build script and specify the name of the project and
|
||||
(optionally) the name of the target you wish to execute (default is
|
||||
'main' target) of build-propel.xml.
|
||||
|
||||
Normal use:
|
||||
$> phing
|
||||
|
||||
Specific target:
|
||||
$> phing -Dtarget=insert-sql
|
||||
|
||||
-->
|
||||
<project name="propel-project-builder" default="main">
|
||||
|
||||
<!-- set to this dir -->
|
||||
<property name="project.dir" value="."/>
|
||||
|
||||
<!-- set a default target if none provided -->
|
||||
<property name="target" value="main"/>
|
||||
|
||||
<target name="buildpropescheck">
|
||||
<available file="./build.properties" property="projBuildPopertiesExists"/>
|
||||
</target>
|
||||
|
||||
<target name="init">
|
||||
<echo msg="Loading project-specific props from ./build.properties"/>
|
||||
<property file="./build.properties"/>
|
||||
</target>
|
||||
|
||||
<target name="checkproject" unless="propel.project">
|
||||
<fail msg="Build failed. Please make sure that propel.project is set to your project-name in local build.properties"/>
|
||||
</target>
|
||||
<target name="checkhome" unless="propel.home">
|
||||
<fail msg="Build failed. Please make sure that propel.home is set to the propel-generator-dir in local build.properties"/>
|
||||
</target>
|
||||
<target name="checkschemadir" unless="propel.schema.dir">
|
||||
<fail msg="Build failed. Please make sure that propel.schema.dir is set to '.' in local build.properties"/>
|
||||
</target>
|
||||
<target name="checkconfdir" unless="propel.conf.dir">
|
||||
<fail msg="Build failed. Please make sure that propel.conf.dir is set to '.' in local build.properties"/>
|
||||
</target>
|
||||
<target name="checkoutputdir" unless="propel.output.dir">
|
||||
<fail msg="Build failed. Please make sure that propel.output.dir is set to a directory of your choice (e.g. './build/') local build.properties"/>
|
||||
</target>
|
||||
<target name="configure" depends="init,checkproject,checkhome,checkschemadir,checkconfdir,checkoutputdir">
|
||||
<property name="project" value="{$propel.project}"/>
|
||||
</target>
|
||||
|
||||
<target name="main" depends="configure"
|
||||
description="The main target. Includes project-specific build.properties and calls the build-propel.xml script">
|
||||
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="${target}"/>
|
||||
|
||||
</target>
|
||||
|
||||
<!--
|
||||
Convenience mappings to build-propel.xml main targets
|
||||
|
||||
This makes it possible to use this buildfile w/o needing to specify
|
||||
target as a property, e.g.:
|
||||
|
||||
$> phing -Dproject=bookstore insert-sql
|
||||
|
||||
The main reason for this is just consistency w/ old build-propel.xml file
|
||||
(primarily for documentation & user confusion avoidance reasons). There are relatively
|
||||
few & infrequently changing main targets of build-propel.xml, so it's a non-
|
||||
issue as far as maintenance is concerned.
|
||||
-->
|
||||
|
||||
<target name="convert-props" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="convert-props"/>
|
||||
</target>
|
||||
|
||||
<target name="create-db" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="create-db"/>
|
||||
</target>
|
||||
|
||||
<target name="creole" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="creole"/>
|
||||
</target>
|
||||
|
||||
<target name="datadtd" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="datadtd"/>
|
||||
</target>
|
||||
|
||||
<target name="datadump" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="datadump"/>
|
||||
</target>
|
||||
|
||||
<target name="datasql" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="datasql"/>
|
||||
</target>
|
||||
|
||||
<target name="insert-sql" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="insert-sql"/>
|
||||
</target>
|
||||
|
||||
<target name="om" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="om"/>
|
||||
</target>
|
||||
|
||||
<target name="new-om" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="new-om"/>
|
||||
</target>
|
||||
|
||||
<target name="sql" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="sql"/>
|
||||
</target>
|
||||
|
||||
<target name="old-sql" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="old-sql"/>
|
||||
</target>
|
||||
|
||||
<target name="graphviz" depends="configure">
|
||||
<phing phingfile="${propel.home}/build-propel.xml" target="graphviz"/>
|
||||
</target>
|
||||
|
||||
|
||||
</project>
|
|
@ -1,267 +0,0 @@
|
|||
# -------------------------------------------------------------------
|
||||
#
|
||||
# D E F A U L T P R O P E R T I E S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
# This file sets default properties. You can override any of these
|
||||
# by specifying your new value in the build.properties file for your
|
||||
# project or a top-level build.properties file. Either way, you
|
||||
# should not need to edit this file.
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# B A S I C P R O P E R T I E S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
propel.version = 1.5.2
|
||||
|
||||
propel.home = .
|
||||
|
||||
propel.project =
|
||||
propel.database =
|
||||
propel.targetPackage = ${propel.project}
|
||||
propel.runOnlyOnSchemaChange = false
|
||||
|
||||
# Default behavior settings
|
||||
#
|
||||
propel.targetPlatform = php5
|
||||
propel.packageObjectModel = false
|
||||
propel.useDateTimeClass = true
|
||||
propel.dateTimeClass = DateTime
|
||||
|
||||
propel.schema.validate = true
|
||||
propel.schema.transform = false
|
||||
|
||||
# controls what type of joins will be used in the doSelectJoin*() peer methods,
|
||||
# if set to true, LEFT JOINS will be used, INNER JOINS otherwise
|
||||
# see ticket #491, #588
|
||||
propel.useLeftJoinsInDoJoinMethods = true
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# D A T A B A S E S E T T I N G S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
propel.database.url =
|
||||
propel.database.buildUrl = ${propel.database.url}
|
||||
propel.database.createUrl = ${propel.database.buildUrl}
|
||||
|
||||
propel.database.driver =
|
||||
|
||||
propel.database.schema =
|
||||
propel.database.encoding =
|
||||
propel.database.manualCreation = false
|
||||
|
||||
# if these arent blank then when we try to connect with insert-sql to a database
|
||||
# that doesnt require them and it isnt in the build.properties it sends
|
||||
# the ${blah} for the username and password
|
||||
propel.database.user =
|
||||
propel.database.password =
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# D A T A B A S E T O X M L S E T T I N G S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
propel.samePhpName = false
|
||||
propel.addVendorInfo = false
|
||||
propel.addValidators = none
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# T E M P L A T E V A R I A B L E S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
propel.addGenericAccessors = true
|
||||
propel.addGenericMutators = true
|
||||
propel.addSaveMethod = true
|
||||
propel.addTimeStamp = false
|
||||
propel.addValidateMethod = true
|
||||
propel.addIncludes = false
|
||||
propel.addHooks = true
|
||||
propel.basePrefix = Base
|
||||
propel.saveException = PropelException
|
||||
propel.emulateForeignKeyConstraints = false
|
||||
|
||||
# Identifier quoting is only implemented at the DDL layer at this point.
|
||||
# Since this may result in undesired behavior (especially in Postgres),
|
||||
# it can be disabled by setting this property to true in your build.properties file.
|
||||
propel.disableIdentifierQuoting = false
|
||||
|
||||
# These are the default formats that will be used when fetching values
|
||||
# from temporal columns in Propel. You can always specify these when
|
||||
# calling the methods directly, but for methods like getByName()
|
||||
# it is nice to change the defaults.
|
||||
|
||||
propel.defaultTimeStampFormat = Y-m-d H:i:s
|
||||
propel.defaultTimeFormat = %X
|
||||
propel.defaultDateFormat = %x
|
||||
|
||||
propel.namespace.om = om
|
||||
propel.namespace.map = map
|
||||
propel.namespace.autoPackage = false
|
||||
|
||||
propel.omtar.src.base = false
|
||||
propel.omtar.src.extension = false
|
||||
propel.omtar.bin.base = false
|
||||
propel.omtar.bin.extension = false
|
||||
propel.omtar.deleteFiles = false
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# D I R E C T O R I E S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
propel.project.dir = ${propel.home}/projects/${propel.project}
|
||||
|
||||
propel.output.dir = ${propel.project.dir}/build
|
||||
propel.schema.dir = ${propel.project.dir}
|
||||
propel.templatePath = ${propel.home}/templates
|
||||
propel.conf.dir = ${propel.project.dir}
|
||||
|
||||
propel.doc.dir = ${propel.output.dir}/doc
|
||||
propel.php.dir = ${propel.output.dir}/classes
|
||||
propel.phpconf.dir = ${propel.output.dir}/conf
|
||||
propel.phpdoc.dir = ${propel.output.dir}/phpdoc
|
||||
propel.sql.dir = ${propel.output.dir}/sql
|
||||
propel.graph.dir = ${propel.output.dir}/graph
|
||||
propel.omtar.dir = ${propel.output.dir}
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# D E F A U L T F I L E N A M ES
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
# propel.sqlfile
|
||||
|
||||
propel.runtime.conf.file = runtime-conf.xml
|
||||
propel.runtime.phpconf.file = ${propel.project}-conf.php
|
||||
propel.runtime.phpconf-classmap.file = ${propel.project}-classmap.php
|
||||
propel.default.schema.basename = schema
|
||||
|
||||
# Can't use because of inconsistencies in where the files
|
||||
# are named (some from build-propel.xml, but some from within templates)
|
||||
# propel.default.data.basename = ${propel.project}-data
|
||||
|
||||
propel.schema.xsd.file = ${propel.home}/resources/xsd/database.xsd
|
||||
propel.schema.xsl.file = ${propel.home}/resources/xsl/database.xsl
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# I N C L U D E A N D E X C L U D E S E T T I N G S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
propel.schema.sql.includes = *schema.xml
|
||||
propel.schema.sql.excludes =
|
||||
propel.schema.doc.includes = *schema.xml
|
||||
propel.schema.doc.excludes =
|
||||
propel.schema.create-db.includes = *schema.xml
|
||||
propel.schema.create-db.excludes =
|
||||
propel.schema.init-sql.includes = *schema.xml
|
||||
propel.schema.init-sql.excludes = id-table-schema.xml
|
||||
propel.schema.om.includes = *schema.xml
|
||||
propel.schema.om.excludes = id-table-schema.xml
|
||||
propel.schema.datadtd.includes = *schema.xml
|
||||
propel.schema.datadtd.excludes = id-table-schema.xml
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# M A P P E R S E T T I N G S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
# (note: data xml files are selected based on datadbmap file)
|
||||
propel.datasql.mapper.from = *.xml
|
||||
propel.datasql.mapper.to = *.sql
|
||||
|
||||
propel.datadump.mapper.from = *schema.xml
|
||||
propel.datadump.mapper.to = *data.xml
|
||||
|
||||
propel.datadtd.mapper.from = *.xml
|
||||
propel.datadtd.mapper.to = *.dtd
|
||||
|
||||
propel.sql.mapper.from = *.xml
|
||||
propel.sql.mapper.to = *.sql
|
||||
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# B U I L D E R S E T T I N G S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
# Object Model builders
|
||||
propel.builder.peer.class = builder.om.PHP5PeerBuilder
|
||||
propel.builder.object.class = builder.om.PHP5ObjectBuilder
|
||||
propel.builder.objectstub.class = builder.om.PHP5ExtensionObjectBuilder
|
||||
propel.builder.peerstub.class = builder.om.PHP5ExtensionPeerBuilder
|
||||
|
||||
propel.builder.objectmultiextend.class = builder.om.PHP5MultiExtendObjectBuilder
|
||||
|
||||
propel.builder.tablemap.class = builder.om.PHP5TableMapBuilder
|
||||
propel.builder.query.class = builder.om.QueryBuilder
|
||||
propel.builder.querystub.class = builder.om.ExtensionQueryBuilder
|
||||
propel.builder.queryinheritance.class = builder.om.QueryInheritanceBuilder
|
||||
propel.builder.queryinheritancestub.class = builder.om.ExtensionQueryInheritanceBuilder
|
||||
|
||||
propel.builder.interface.class = builder.om.PHP5InterfaceBuilder
|
||||
|
||||
propel.builder.node.class = builder.om.PHP5NodeBuilder
|
||||
propel.builder.nodepeer.class = builder.om.PHP5NodePeerBuilder
|
||||
propel.builder.nodestub.class = builder.om.PHP5ExtensionNodeBuilder
|
||||
propel.builder.nodepeerstub.class = builder.om.PHP5ExtensionNodePeerBuilder
|
||||
|
||||
propel.builder.nestedset.class = builder.om.PHP5NestedSetBuilder
|
||||
propel.builder.nestedsetpeer.class = builder.om.PHP5NestedSetPeerBuilder
|
||||
|
||||
propel.builder.pluralizer.class = builder.util.DefaultEnglishPluralizer
|
||||
|
||||
# SQL builders
|
||||
|
||||
propel.builder.ddl.class = builder.sql.${propel.database}.${propel.database}DDLBuilder
|
||||
propel.builder.datasql.class = builder.sql.${propel.database}.${propel.database}DataSQLBuilder
|
||||
|
||||
# Platform classes
|
||||
|
||||
propel.platform.class = platform.${propel.database}Platform
|
||||
|
||||
# Schema Parser (reverse-engineering) classes
|
||||
|
||||
propel.reverse.parser.class = reverse.${propel.database}.${propel.database}SchemaParser
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# M Y S Q L S P E C I F I C S E T T I N G S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
# Default table type
|
||||
propel.mysqlTableType = MyISAM
|
||||
# Keyword used to specify table type. MYSQL < 5 should use TYPE instead
|
||||
propel.mysqlTableEngineKeyword = ENGINE
|
||||
|
||||
# -------------------------------------------------------------------
|
||||
#
|
||||
# B E H A V I O R S E T T I N G S
|
||||
#
|
||||
# -------------------------------------------------------------------
|
||||
|
||||
propel.behavior.timestampable.class = behavior.TimestampableBehavior
|
||||
propel.behavior.alternative_coding_standards.class = behavior.AlternativeCodingStandardsBehavior
|
||||
propel.behavior.soft_delete.class = behavior.SoftDeleteBehavior
|
||||
propel.behavior.auto_add_pk.class = behavior.AutoAddPkBehavior
|
||||
propel.behavior.nested_set.class = behavior.nestedset.NestedSetBehavior
|
||||
propel.behavior.sortable.class = behavior.sortable.SortableBehavior
|
||||
propel.behavior.sluggable.class = behavior.sluggable.SluggableBehavior
|
||||
propel.behavior.concrete_inheritance.class = behavior.concrete_inheritance.ConcreteInheritanceBehavior
|
||||
propel.behavior.query_cache.class = behavior.query_cache.QueryCacheBehavior
|
||||
propel.behavior.aggregate_column.class = behavior.aggregate_column.AggregateColumnBehavior
|
|
@ -1,133 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Changes the coding standard of Propel generated Model classes
|
||||
* - Opening brackets always use newline, e.g.
|
||||
* if ($foo) {
|
||||
* ...
|
||||
* } else {
|
||||
* ...
|
||||
* }
|
||||
* Becomes:
|
||||
* if ($foo)
|
||||
* {
|
||||
* ...
|
||||
* }
|
||||
* else
|
||||
* {
|
||||
* ...
|
||||
* }
|
||||
* - closing comments are removed, e.g.
|
||||
* } // save()
|
||||
* Becomes:
|
||||
* }
|
||||
* - tabs are replaced by 2 whitespaces
|
||||
* - comments are stripped (optional)
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @version $Revision: 1612 $
|
||||
* @package propel.generator.behavior
|
||||
*/
|
||||
class AlternativeCodingStandardsBehavior extends Behavior
|
||||
{
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'brackets_newline' => 'true',
|
||||
'remove_closing_comments' => 'true',
|
||||
'use_whitespace' => 'true',
|
||||
'tab_size' => 2,
|
||||
'strip_comments' => 'false'
|
||||
);
|
||||
|
||||
public function objectFilter(&$script)
|
||||
{
|
||||
return $this->filter($script);
|
||||
}
|
||||
|
||||
public function extensionObjectFilter(&$script)
|
||||
{
|
||||
return $this->filter($script);
|
||||
}
|
||||
|
||||
public function queryFilter(&$script)
|
||||
{
|
||||
return $this->filter($script);
|
||||
}
|
||||
|
||||
public function extensionQueryFilter(&$script)
|
||||
{
|
||||
return $this->filter($script);
|
||||
}
|
||||
|
||||
public function peerFilter(&$script)
|
||||
{
|
||||
return $this->filter($script);
|
||||
}
|
||||
|
||||
public function extensionPeerFilter(&$script)
|
||||
{
|
||||
return $this->filter($script);
|
||||
}
|
||||
|
||||
public function tableMapFilter(&$script)
|
||||
{
|
||||
return $this->filter($script);
|
||||
}
|
||||
|
||||
/**
|
||||
* Transform the coding standards of a PHP sourcecode string
|
||||
*
|
||||
* @param string $script A script string to be filtered, passed as reference
|
||||
*/
|
||||
protected function filter(&$script)
|
||||
{
|
||||
$filter = array();
|
||||
if($this->getParameter('brackets_newline') == 'true') {
|
||||
$filter['#^(\t*)\}\h(else|elseif|catch)(.*)\h\{$#m'] = "$1}
|
||||
$1$2$3
|
||||
$1{";
|
||||
$filter['#^(\t*)(\w.*)\h\{$#m'] = "$1$2
|
||||
$1{";
|
||||
}
|
||||
if ($this->getParameter('remove_closing_comments') == 'true') {
|
||||
$filter['#^(\t*)} //.*$#m'] = "$1}";
|
||||
}
|
||||
if ($this->getParameter('use_whitespace') == 'true') {
|
||||
$filter['#\t#'] = str_repeat(' ', $this->getParameter('tab_size'));
|
||||
}
|
||||
|
||||
$script = preg_replace(array_keys($filter), array_values($filter), $script);
|
||||
|
||||
if ($this->getParameter('strip_comments') == 'true') {
|
||||
$script = self::stripComments($script);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove inline and codeblock comments from a PHP code string
|
||||
* @param string $code The input code
|
||||
* @return string The input code, without comments
|
||||
*/
|
||||
public static function stripComments($code)
|
||||
{
|
||||
$output = '';
|
||||
$commentTokens = array(T_COMMENT, T_DOC_COMMENT);
|
||||
foreach (token_get_all($code) as $token) {
|
||||
if (is_array($token)) {
|
||||
if (in_array($token[0], $commentTokens)) continue;
|
||||
$token = $token[1];
|
||||
}
|
||||
$output .= $token;
|
||||
}
|
||||
|
||||
return $output;
|
||||
}
|
||||
}
|
|
@ -1,54 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Adds a primary key to models defined without one
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @version $Revision: 1745 $
|
||||
* @package propel.generator.behavior
|
||||
*/
|
||||
class AutoAddPkBehavior extends Behavior
|
||||
{
|
||||
protected $isEarly = true;
|
||||
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'name' => 'id',
|
||||
'autoIncrement' => 'true',
|
||||
'type' => 'INTEGER'
|
||||
);
|
||||
|
||||
/**
|
||||
* Copy the behavior to the database tables
|
||||
* Only for tables that have no Pk
|
||||
*/
|
||||
public function modifyDatabase()
|
||||
{
|
||||
foreach ($this->getDatabase()->getTables() as $table) {
|
||||
if(!$table->hasPrimaryKey()) {
|
||||
$b = clone $this;
|
||||
$table->addBehavior($b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add the primary key to the current table
|
||||
*/
|
||||
public function modifyTable()
|
||||
{
|
||||
$table = $this->getTable();
|
||||
if (!$table->hasPrimaryKey() && !$table->hasBehavior('concrete_inheritance')) {
|
||||
$columnAttributes = array_merge(array('primaryKey' => 'true'), $this->getParameters());
|
||||
$this->getTable()->addColumn($columnAttributes);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -1,467 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Gives a model class the ability to remain in database even when the user deletes object
|
||||
* Uses an additional column storing the deletion date
|
||||
* And an additional condition for every read query to only consider rows with no deletion date
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @version $Revision: 1807 $
|
||||
* @package propel.generator.behavior
|
||||
*/
|
||||
class SoftDeleteBehavior extends Behavior
|
||||
{
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'deleted_column' => 'deleted_at',
|
||||
);
|
||||
|
||||
/**
|
||||
* Add the deleted_column to the current table
|
||||
*/
|
||||
public function modifyTable()
|
||||
{
|
||||
if(!$this->getTable()->containsColumn($this->getParameter('deleted_column'))) {
|
||||
$this->getTable()->addColumn(array(
|
||||
'name' => $this->getParameter('deleted_column'),
|
||||
'type' => 'TIMESTAMP'
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
protected function getColumnSetter()
|
||||
{
|
||||
return 'set' . $this->getColumnForParameter('deleted_column')->getPhpName();
|
||||
}
|
||||
|
||||
public function objectMethods($builder)
|
||||
{
|
||||
$script = '';
|
||||
$this->addObjectForceDelete($script);
|
||||
$this->addObjectUndelete($script);
|
||||
return $script;
|
||||
}
|
||||
|
||||
public function addObjectForceDelete(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Bypass the soft_delete behavior and force a hard delete of the current object
|
||||
*/
|
||||
public function forceDelete(PropelPDO \$con = null)
|
||||
{
|
||||
{$this->getTable()->getPhpName()}Peer::disableSoftDelete();
|
||||
\$this->delete(\$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addObjectUndelete(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Undelete a row that was soft_deleted
|
||||
*
|
||||
* @return int The number of rows affected by this update and any referring fk objects' save() operations.
|
||||
*/
|
||||
public function unDelete(PropelPDO \$con = null)
|
||||
{
|
||||
\$this->{$this->getColumnSetter()}(null);
|
||||
return \$this->save(\$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function preDelete($builder)
|
||||
{
|
||||
return <<<EOT
|
||||
if (!empty(\$ret) && {$builder->getStubQueryBuilder()->getClassname()}::isSoftDeleteEnabled()) {
|
||||
\$this->{$this->getColumnSetter()}(time());
|
||||
\$this->save(\$con);
|
||||
\$con->commit();
|
||||
{$builder->getStubPeerBuilder()->getClassname()}::removeInstanceFromPool(\$this);
|
||||
return;
|
||||
}
|
||||
EOT;
|
||||
}
|
||||
|
||||
public function queryAttributes()
|
||||
{
|
||||
return "protected static \$softDelete = true;
|
||||
protected \$localSoftDelete = true;
|
||||
";
|
||||
}
|
||||
|
||||
public function queryMethods($builder)
|
||||
{
|
||||
$this->builder = $builder;
|
||||
$script = '';
|
||||
$this->addQueryIncludeDeleted($script);
|
||||
$this->addQuerySoftDelete($script);
|
||||
$this->addQueryForceDelete($script);
|
||||
$this->addQueryForceDeleteAll($script);
|
||||
$this->addQueryUnDelete($script);
|
||||
$this->addQueryEnableSoftDelete($script);
|
||||
$this->addQueryDisableSoftDelete($script);
|
||||
$this->addQueryIsSoftDeleteEnabled($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
public function addQueryIncludeDeleted(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Temporarily disable the filter on deleted rows
|
||||
* Valid only for the current query
|
||||
*
|
||||
* @see {$this->builder->getStubQueryBuilder()->getClassname()}::disableSoftDelete() to disable the filter for more than one query
|
||||
*
|
||||
* @return {$this->builder->getStubQueryBuilder()->getClassname()} The current query, for fuid interface
|
||||
*/
|
||||
public function includeDeleted()
|
||||
{
|
||||
\$this->localSoftDelete = false;
|
||||
return \$this;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addQuerySoftDelete(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Soft delete the selected rows
|
||||
*
|
||||
* @param PropelPDO \$con an optional connection object
|
||||
*
|
||||
* @return int Number of updated rows
|
||||
*/
|
||||
public function softDelete(PropelPDO \$con = null)
|
||||
{
|
||||
return \$this->update(array('{$this->getColumnForParameter('deleted_column')->getPhpName()}' => time()), \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addQueryForceDelete(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Bypass the soft_delete behavior and force a hard delete of the selected rows
|
||||
*
|
||||
* @param PropelPDO \$con an optional connection object
|
||||
*
|
||||
* @return int Number of deleted rows
|
||||
*/
|
||||
public function forceDelete(PropelPDO \$con = null)
|
||||
{
|
||||
return {$this->builder->getPeerClassname()}::doForceDelete(\$this, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addQueryForceDeleteAll(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Bypass the soft_delete behavior and force a hard delete of all the rows
|
||||
*
|
||||
* @param PropelPDO \$con an optional connection object
|
||||
*
|
||||
* @return int Number of deleted rows
|
||||
*/
|
||||
public function forceDeleteAll(PropelPDO \$con = null)
|
||||
{
|
||||
return {$this->builder->getPeerClassname()}::doForceDeleteAll(\$con);}
|
||||
";
|
||||
}
|
||||
|
||||
public function addQueryUnDelete(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Undelete selected rows
|
||||
*
|
||||
* @param PropelPDO \$con an optional connection object
|
||||
*
|
||||
* @return int The number of rows affected by this update and any referring fk objects' save() operations.
|
||||
*/
|
||||
public function unDelete(PropelPDO \$con = null)
|
||||
{
|
||||
return \$this->update(array('{$this->getColumnForParameter('deleted_column')->getPhpName()}' => null), \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addQueryEnableSoftDelete(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Enable the soft_delete behavior for this model
|
||||
*/
|
||||
public static function enableSoftDelete()
|
||||
{
|
||||
self::\$softDelete = true;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addQueryDisableSoftDelete(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Disable the soft_delete behavior for this model
|
||||
*/
|
||||
public static function disableSoftDelete()
|
||||
{
|
||||
self::\$softDelete = false;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addQueryIsSoftDeleteEnabled(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Check the soft_delete behavior for this model
|
||||
*
|
||||
* @return boolean true if the soft_delete behavior is enabled
|
||||
*/
|
||||
public static function isSoftDeleteEnabled()
|
||||
{
|
||||
return self::\$softDelete;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function preSelectQuery($builder)
|
||||
{
|
||||
return <<<EOT
|
||||
if ({$builder->getStubQueryBuilder()->getClassname()}::isSoftDeleteEnabled() && \$this->localSoftDelete) {
|
||||
\$this->addUsingAlias({$this->getColumnForParameter('deleted_column')->getConstantName()}, null, Criteria::ISNULL);
|
||||
} else {
|
||||
{$this->getTable()->getPhpName()}Peer::enableSoftDelete();
|
||||
}
|
||||
EOT;
|
||||
}
|
||||
|
||||
public function preDeleteQuery($builder)
|
||||
{
|
||||
return <<<EOT
|
||||
if ({$builder->getStubQueryBuilder()->getClassname()}::isSoftDeleteEnabled() && \$this->localSoftDelete) {
|
||||
return \$this->softDelete(\$con);
|
||||
} else {
|
||||
return \$this->hasWhereClause() ? \$this->forceDelete(\$con) : \$this->forceDeleteAll(\$con);
|
||||
}
|
||||
EOT;
|
||||
}
|
||||
|
||||
public function staticMethods($builder)
|
||||
{
|
||||
$builder->declareClassFromBuilder($builder->getStubQueryBuilder());
|
||||
$this->builder = $builder;
|
||||
$script = '';
|
||||
$this->addPeerEnableSoftDelete($script);
|
||||
$this->addPeerDisableSoftDelete($script);
|
||||
$this->addPeerIsSoftDeleteEnabled($script);
|
||||
$this->addPeerDoSoftDelete($script);
|
||||
$this->addPeerDoDelete2($script);
|
||||
$this->addPeerDoSoftDeleteAll($script);
|
||||
$this->addPeerDoDeleteAll2($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
public function addPeerEnableSoftDelete(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Enable the soft_delete behavior for this model
|
||||
*/
|
||||
public static function enableSoftDelete()
|
||||
{
|
||||
{$this->builder->getStubQueryBuilder()->getClassname()}::enableSoftDelete();
|
||||
// some soft_deleted objects may be in the instance pool
|
||||
{$this->builder->getStubPeerBuilder()->getClassname()}::clearInstancePool();
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addPeerDisableSoftDelete(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Disable the soft_delete behavior for this model
|
||||
*/
|
||||
public static function disableSoftDelete()
|
||||
{
|
||||
{$this->builder->getStubQueryBuilder()->getClassname()}::disableSoftDelete();
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addPeerIsSoftDeleteEnabled(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Check the soft_delete behavior for this model
|
||||
* @return boolean true if the soft_delete behavior is enabled
|
||||
*/
|
||||
public static function isSoftDeleteEnabled()
|
||||
{
|
||||
return {$this->builder->getStubQueryBuilder()->getClassname()}::isSoftDeleteEnabled();
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addPeerDoSoftDelete(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Soft delete records, given a {$this->getTable()->getPhpName()} or Criteria object OR a primary key value.
|
||||
*
|
||||
* @param mixed \$values Criteria or {$this->getTable()->getPhpName()} object or primary key or array of primary keys
|
||||
* which is used to create the DELETE statement
|
||||
* @param PropelPDO \$con the connection to use
|
||||
* @return int The number of affected rows (if supported by underlying database driver).
|
||||
* @throws PropelException Any exceptions caught during processing will be
|
||||
* rethrown wrapped into a PropelException.
|
||||
*/
|
||||
public static function doSoftDelete(\$values, PropelPDO \$con = null)
|
||||
{
|
||||
if (\$values instanceof Criteria) {
|
||||
// rename for clarity
|
||||
\$criteria = clone \$values;
|
||||
} elseif (\$values instanceof {$this->getTable()->getPhpName()}) {
|
||||
// create criteria based on pk values
|
||||
\$criteria = \$values->buildPkeyCriteria();
|
||||
} else {
|
||||
// it must be the primary key
|
||||
\$criteria = new Criteria(self::DATABASE_NAME);";
|
||||
$pks = $this->getTable()->getPrimaryKey();
|
||||
if (count($pks)>1) {
|
||||
$i = 0;
|
||||
foreach ($pks as $col) {
|
||||
$script .= "
|
||||
\$criteria->add({$col->getConstantName()}, \$values[$i], Criteria::EQUAL);";
|
||||
$i++;
|
||||
}
|
||||
} else {
|
||||
$col = $pks[0];
|
||||
$script .= "
|
||||
\$criteria->add({$col->getConstantName()}, (array) \$values, Criteria::IN);";
|
||||
}
|
||||
$script .= "
|
||||
}
|
||||
\$criteria->add({$this->getColumnForParameter('deleted_column')->getConstantName()}, time());
|
||||
return {$this->getTable()->getPhpName()}Peer::doUpdate(\$criteria, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addPeerDoDelete2(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Delete or soft delete records, depending on {$this->getTable()->getPhpName()}Peer::\$softDelete
|
||||
*
|
||||
* @param mixed \$values Criteria or {$this->getTable()->getPhpName()} object or primary key or array of primary keys
|
||||
* which is used to create the DELETE statement
|
||||
* @param PropelPDO \$con the connection to use
|
||||
* @return int The number of affected rows (if supported by underlying database driver).
|
||||
* @throws PropelException Any exceptions caught during processing will be
|
||||
* rethrown wrapped into a PropelException.
|
||||
*/
|
||||
public static function doDelete2(\$values, PropelPDO \$con = null)
|
||||
{
|
||||
if ({$this->getTable()->getPhpName()}Peer::isSoftDeleteEnabled()) {
|
||||
return {$this->getTable()->getPhpName()}Peer::doSoftDelete(\$values, \$con);
|
||||
} else {
|
||||
return {$this->getTable()->getPhpName()}Peer::doForceDelete(\$values, \$con);
|
||||
}
|
||||
}";
|
||||
}
|
||||
|
||||
public function addPeerDoSoftDeleteAll(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Method to soft delete all rows from the {$this->getTable()->getName()} table.
|
||||
*
|
||||
* @param PropelPDO \$con the connection to use
|
||||
* @return int The number of affected rows (if supported by underlying database driver).
|
||||
* @throws PropelException Any exceptions caught during processing will be
|
||||
* rethrown wrapped into a PropelException.
|
||||
*/
|
||||
public static function doSoftDeleteAll(PropelPDO \$con = null)
|
||||
{
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection({$this->getTable()->getPhpName()}Peer::DATABASE_NAME, Propel::CONNECTION_WRITE);
|
||||
}
|
||||
\$selectCriteria = new Criteria();
|
||||
\$selectCriteria->add({$this->getColumnForParameter('deleted_column')->getConstantName()}, null, Criteria::ISNULL);
|
||||
\$selectCriteria->setDbName({$this->getTable()->getPhpName()}Peer::DATABASE_NAME);
|
||||
\$modifyCriteria = new Criteria();
|
||||
\$modifyCriteria->add({$this->getColumnForParameter('deleted_column')->getConstantName()}, time());
|
||||
return BasePeer::doUpdate(\$selectCriteria, \$modifyCriteria, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addPeerDoDeleteAll2(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Delete or soft delete all records, depending on {$this->getTable()->getPhpName()}Peer::\$softDelete
|
||||
*
|
||||
* @param PropelPDO \$con the connection to use
|
||||
* @return int The number of affected rows (if supported by underlying database driver).
|
||||
* @throws PropelException Any exceptions caught during processing will be
|
||||
* rethrown wrapped into a PropelException.
|
||||
*/
|
||||
public static function doDeleteAll2(PropelPDO \$con = null)
|
||||
{
|
||||
if ({$this->getTable()->getPhpName()}Peer::isSoftDeleteEnabled()) {
|
||||
return {$this->getTable()->getPhpName()}Peer::doSoftDeleteAll(\$con);
|
||||
} else {
|
||||
return {$this->getTable()->getPhpName()}Peer::doForceDeleteAll(\$con);
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function preSelect($builder)
|
||||
{
|
||||
return <<<EOT
|
||||
if ({$builder->getStubQueryBuilder()->getClassname()}::isSoftDeleteEnabled()) {
|
||||
\$criteria->add({$this->getColumnForParameter('deleted_column')->getConstantName()}, null, Criteria::ISNULL);
|
||||
} else {
|
||||
{$this->getTable()->getPhpName()}Peer::enableSoftDelete();
|
||||
}
|
||||
EOT;
|
||||
}
|
||||
|
||||
public function peerFilter(&$script)
|
||||
{
|
||||
$script = str_replace(array(
|
||||
'public static function doDelete(',
|
||||
'public static function doDelete2(',
|
||||
'public static function doDeleteAll(',
|
||||
'public static function doDeleteAll2('
|
||||
), array(
|
||||
'public static function doForceDelete(',
|
||||
'public static function doDelete(',
|
||||
'public static function doForceDeleteAll(',
|
||||
'public static function doDeleteAll('
|
||||
), $script);
|
||||
}
|
||||
}
|
|
@ -1,171 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Gives a model class the ability to track creation and last modification dates
|
||||
* Uses two additional columns storing the creation and update date
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @version $Revision: 1683 $
|
||||
* @package propel.generator.behavior
|
||||
*/
|
||||
class TimestampableBehavior extends Behavior
|
||||
{
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'create_column' => 'created_at',
|
||||
'update_column' => 'updated_at'
|
||||
);
|
||||
|
||||
/**
|
||||
* Add the create_column and update_columns to the current table
|
||||
*/
|
||||
public function modifyTable()
|
||||
{
|
||||
if(!$this->getTable()->containsColumn($this->getParameter('create_column'))) {
|
||||
$this->getTable()->addColumn(array(
|
||||
'name' => $this->getParameter('create_column'),
|
||||
'type' => 'TIMESTAMP'
|
||||
));
|
||||
}
|
||||
if(!$this->getTable()->containsColumn($this->getParameter('update_column'))) {
|
||||
$this->getTable()->addColumn(array(
|
||||
'name' => $this->getParameter('update_column'),
|
||||
'type' => 'TIMESTAMP'
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the setter of one of the columns of the behavior
|
||||
*
|
||||
* @param string $column One of the behavior colums, 'create_column' or 'update_column'
|
||||
* @return string The related setter, 'setCreatedOn' or 'setUpdatedOn'
|
||||
*/
|
||||
protected function getColumnSetter($column)
|
||||
{
|
||||
return 'set' . $this->getColumnForParameter($column)->getPhpName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add code in ObjectBuilder::preUpdate
|
||||
*
|
||||
* @return string The code to put at the hook
|
||||
*/
|
||||
public function preUpdate()
|
||||
{
|
||||
return "if (\$this->isModified() && !\$this->isColumnModified(" . $this->getColumnForParameter('update_column')->getConstantName() . ")) {
|
||||
\$this->" . $this->getColumnSetter('update_column') . "(time());
|
||||
}";
|
||||
}
|
||||
|
||||
/**
|
||||
* Add code in ObjectBuilder::preInsert
|
||||
*
|
||||
* @return string The code to put at the hook
|
||||
*/
|
||||
public function preInsert()
|
||||
{
|
||||
return "if (!\$this->isColumnModified(" . $this->getColumnForParameter('create_column')->getConstantName() . ")) {
|
||||
\$this->" . $this->getColumnSetter('create_column') . "(time());
|
||||
}
|
||||
if (!\$this->isColumnModified(" . $this->getColumnForParameter('update_column')->getConstantName() . ")) {
|
||||
\$this->" . $this->getColumnSetter('update_column') . "(time());
|
||||
}";
|
||||
}
|
||||
|
||||
public function objectMethods($builder)
|
||||
{
|
||||
return "
|
||||
/**
|
||||
* Mark the current object so that the update date doesn't get updated during next save
|
||||
*
|
||||
* @return " . $builder->getStubObjectBuilder()->getClassname() . " The current object (for fluent API support)
|
||||
*/
|
||||
public function keepUpdateDateUnchanged()
|
||||
{
|
||||
\$this->modifiedColumns[] = " . $this->getColumnForParameter('update_column')->getConstantName() . ";
|
||||
return \$this;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function queryMethods($builder)
|
||||
{
|
||||
$queryClassName = $builder->getStubQueryBuilder()->getClassname();
|
||||
$updateColumnConstant = $this->getColumnForParameter('update_column')->getConstantName();
|
||||
$createColumnConstant = $this->getColumnForParameter('create_column')->getConstantName();
|
||||
return "
|
||||
/**
|
||||
* Filter by the latest updated
|
||||
*
|
||||
* @param int \$nbDays Maximum age of the latest update in days
|
||||
*
|
||||
* @return $queryClassName The current query, for fuid interface
|
||||
*/
|
||||
public function recentlyUpdated(\$nbDays = 7)
|
||||
{
|
||||
return \$this->addUsingAlias($updateColumnConstant, time() - \$nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Filter by the latest created
|
||||
*
|
||||
* @param int \$nbDays Maximum age of in days
|
||||
*
|
||||
* @return $queryClassName The current query, for fuid interface
|
||||
*/
|
||||
public function recentlyCreated(\$nbDays = 7)
|
||||
{
|
||||
return \$this->addUsingAlias($createColumnConstant, time() - \$nbDays * 24 * 60 * 60, Criteria::GREATER_EQUAL);
|
||||
}
|
||||
|
||||
/**
|
||||
* Order by update date desc
|
||||
*
|
||||
* @return $queryClassName The current query, for fuid interface
|
||||
*/
|
||||
public function lastUpdatedFirst()
|
||||
{
|
||||
return \$this->addDescendingOrderByColumn($updateColumnConstant);
|
||||
}
|
||||
|
||||
/**
|
||||
* Order by update date asc
|
||||
*
|
||||
* @return $queryClassName The current query, for fuid interface
|
||||
*/
|
||||
public function firstUpdatedFirst()
|
||||
{
|
||||
return \$this->addAscendingOrderByColumn($updateColumnConstant);
|
||||
}
|
||||
|
||||
/**
|
||||
* Order by create date desc
|
||||
*
|
||||
* @return $queryClassName The current query, for fuid interface
|
||||
*/
|
||||
public function lastCreatedFirst()
|
||||
{
|
||||
return \$this->addDescendingOrderByColumn($createColumnConstant);
|
||||
}
|
||||
|
||||
/**
|
||||
* Order by create date asc
|
||||
*
|
||||
* @return $queryClassName The current query, for fuid interface
|
||||
*/
|
||||
public function firstCreatedFirst()
|
||||
{
|
||||
return \$this->addAscendingOrderByColumn($createColumnConstant);
|
||||
}
|
||||
";
|
||||
}
|
||||
}
|
|
@ -1,122 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
require_once 'AggregateColumnRelationBehavior.php';
|
||||
|
||||
/**
|
||||
* Keeps an aggregate column updated with related table
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @version $Revision: 1785 $
|
||||
* @package propel.generator.behavior.aggregate_column
|
||||
*/
|
||||
class AggregateColumnBehavior extends Behavior
|
||||
{
|
||||
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'name' => null,
|
||||
'expression' => null,
|
||||
'foreign_table' => null,
|
||||
);
|
||||
|
||||
/**
|
||||
* Add the aggregate key to the current table
|
||||
*/
|
||||
public function modifyTable()
|
||||
{
|
||||
$table = $this->getTable();
|
||||
if (!$columnName = $this->getParameter('name')) {
|
||||
throw new InvalidArgumentException(sprintf('You must define a \'name\' parameter for the \'aggregate_column\' behavior in the \'%s\' table', $table->getName()));
|
||||
}
|
||||
|
||||
// add the aggregate column if not present
|
||||
if(!$this->getTable()->containsColumn($columnName)) {
|
||||
$column = $this->getTable()->addColumn(array(
|
||||
'name' => $columnName,
|
||||
'type' => 'INTEGER',
|
||||
));
|
||||
}
|
||||
|
||||
// add a behavior in the foreign table to autoupdate the aggregate column
|
||||
$foreignTable = $this->getForeignTable();
|
||||
if (!$foreignTable->hasBehavior('concrete_inheritance_parent')) {
|
||||
$relationBehavior = new AggregateColumnRelationBehavior();
|
||||
$relationBehavior->setName('aggregate_column_relation');
|
||||
$foreignKey = $this->getForeignKey();
|
||||
$relationBehavior->addParameter(array('name' => 'foreign_table', 'value' => $table->getName()));
|
||||
$relationBehavior->addParameter(array('name' => 'update_method', 'value' => 'update' . $this->getColumn()->getPhpName()));
|
||||
$foreignTable->addBehavior($relationBehavior);
|
||||
}
|
||||
}
|
||||
|
||||
public function objectMethods($builder)
|
||||
{
|
||||
if (!$foreignTableName = $this->getParameter('foreign_table')) {
|
||||
throw new InvalidArgumentException(sprintf('You must define a \'foreign_table\' parameter for the \'aggregate_column\' behavior in the \'%s\' table', $this->getTable()->getName()));
|
||||
}
|
||||
$script = '';
|
||||
$script .= $this->addObjectCompute();
|
||||
$script .= $this->addObjectUpdate();
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addObjectCompute()
|
||||
{
|
||||
$conditions = array();
|
||||
$bindings = array();
|
||||
foreach ($this->getForeignKey()->getColumnObjectsMapping() as $index => $columnReference) {
|
||||
$conditions[] = $columnReference['local']->getFullyQualifiedName() . ' = :p' . ($index + 1);
|
||||
$bindings[$index + 1] = $columnReference['foreign']->getPhpName();
|
||||
}
|
||||
$sql = sprintf('SELECT %s FROM %s WHERE %s',
|
||||
$this->getParameter('expression'),
|
||||
$this->getTable()->getDatabase()->getPlatform()->quoteIdentifier($this->getParameter('foreign_table')),
|
||||
implode(' AND ', $conditions)
|
||||
);
|
||||
|
||||
return $this->renderTemplate('objectCompute', array(
|
||||
'column' => $this->getColumn(),
|
||||
'sql' => $sql,
|
||||
'bindings' => $bindings,
|
||||
));
|
||||
}
|
||||
|
||||
protected function addObjectUpdate()
|
||||
{
|
||||
return $this->renderTemplate('objectUpdate', array(
|
||||
'column' => $this->getColumn(),
|
||||
));
|
||||
}
|
||||
|
||||
protected function getForeignTable()
|
||||
{
|
||||
return $this->getTable()->getDatabase()->getTable($this->getParameter('foreign_table'));
|
||||
}
|
||||
|
||||
protected function getForeignKey()
|
||||
{
|
||||
$foreignTable = $this->getForeignTable();
|
||||
// let's infer the relation from the foreign table
|
||||
$fks = $foreignTable->getForeignKeysReferencingTable($this->getTable()->getName());
|
||||
if (!$fks) {
|
||||
throw new InvalidArgumentException(sprintf('You must define a foreign key to the \'%s\' table in the \'%s\' table to enable the \'aggregate_column\' behavior', $this->getTable()->getName(), $foreignTable->getName()));
|
||||
}
|
||||
// FIXME doesn't work when more than one fk to the same table
|
||||
return array_shift($fks);
|
||||
}
|
||||
|
||||
protected function getColumn()
|
||||
{
|
||||
return $this->getTable()->getColumn($this->getParameter('name'));
|
||||
}
|
||||
|
||||
}
|
|
@ -1,164 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
require_once 'AggregateColumnRelationBehavior.php';
|
||||
|
||||
/**
|
||||
* Keeps an aggregate column updated with related table
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @version $Revision: 1785 $
|
||||
* @package propel.generator.behavior.aggregate_column
|
||||
*/
|
||||
class AggregateColumnRelationBehavior extends Behavior
|
||||
{
|
||||
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'foreign_table' => '',
|
||||
'update_method' => '',
|
||||
);
|
||||
|
||||
public function postSave($builder)
|
||||
{
|
||||
$relationName = $this->getRelationName($builder);
|
||||
return "\$this->updateRelated{$relationName}(\$con);";
|
||||
}
|
||||
|
||||
// no need for a postDelete() hook, since delete() uses Query::delete(),
|
||||
// which already has a hook
|
||||
|
||||
public function objectAttributes($builder)
|
||||
{
|
||||
$relationName = $this->getRelationName($builder);
|
||||
return "protected \$old{$relationName};
|
||||
";
|
||||
}
|
||||
|
||||
public function objectMethods($builder)
|
||||
{
|
||||
return $this->addObjectUpdateRelated($builder);
|
||||
}
|
||||
|
||||
protected function addObjectUpdateRelated($builder)
|
||||
{
|
||||
$relationName = $this->getRelationName($builder);
|
||||
$updateMethodName = $this->getParameter('update_method');
|
||||
return $this->renderTemplate('objectUpdateRelated', array(
|
||||
'relationName' => $relationName,
|
||||
'variableName' => self::lcfirst($relationName),
|
||||
'updateMethodName' => $this->getParameter('update_method'),
|
||||
));
|
||||
}
|
||||
|
||||
public function objectFilter(&$script, $builder)
|
||||
{
|
||||
$relationName = $this->getRelationName($builder);
|
||||
$relatedClass = $this->getForeignTable()->getPhpName();
|
||||
$search = " public function set{$relationName}({$relatedClass} \$v = null)
|
||||
{";
|
||||
$replace = $search . "
|
||||
// aggregate_column_relation behavior
|
||||
if (null !== \$this->a{$relationName} && \$v !== \$this->a{$relationName}) {
|
||||
\$this->old{$relationName} = \$this->a{$relationName};
|
||||
}";
|
||||
$script = str_replace($search, $replace, $script);
|
||||
}
|
||||
|
||||
public function preUpdateQuery($builder)
|
||||
{
|
||||
return $this->getFindRelated($builder);
|
||||
}
|
||||
|
||||
public function preDeleteQuery($builder)
|
||||
{
|
||||
return $this->getFindRelated($builder);
|
||||
}
|
||||
|
||||
protected function getFindRelated($builder)
|
||||
{
|
||||
$relationName = $this->getRelationName($builder);
|
||||
return "\$this->findRelated{$relationName}s(\$con);";
|
||||
}
|
||||
|
||||
public function postUpdateQuery($builder)
|
||||
{
|
||||
return $this->getUpdateRelated($builder);
|
||||
}
|
||||
|
||||
public function postDeleteQuery($builder)
|
||||
{
|
||||
return $this->getUpdateRelated($builder);
|
||||
}
|
||||
|
||||
protected function getUpdateRelated($builder)
|
||||
{
|
||||
$relationName = $this->getRelationName($builder);
|
||||
return "\$this->updateRelated{$relationName}s(\$con);";
|
||||
}
|
||||
|
||||
public function queryMethods($builder)
|
||||
{
|
||||
$script = '';
|
||||
$script .= $this->addQueryFindRelated($builder);
|
||||
$script .= $this->addQueryUpdateRelated($builder);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addQueryFindRelated($builder)
|
||||
{
|
||||
$foreignKey = $this->getForeignKey();
|
||||
$relationName = $this->getRelationName($builder);
|
||||
return $this->renderTemplate('queryFindRelated', array(
|
||||
'foreignTable' => $this->getForeignTable(),
|
||||
'relationName' => $relationName,
|
||||
'variableName' => self::lcfirst($relationName),
|
||||
'foreignQueryName' => $foreignKey->getForeignTable()->getPhpName() . 'Query',
|
||||
'refRelationName' => $builder->getRefFKPhpNameAffix($foreignKey),
|
||||
));
|
||||
}
|
||||
|
||||
protected function addQueryUpdateRelated($builder)
|
||||
{
|
||||
$relationName = $this->getRelationName($builder);
|
||||
return $this->renderTemplate('queryUpdateRelated', array(
|
||||
'relationName' => $relationName,
|
||||
'variableName' => self::lcfirst($relationName),
|
||||
'updateMethodName' => $this->getParameter('update_method'),
|
||||
));
|
||||
}
|
||||
|
||||
protected function getForeignTable()
|
||||
{
|
||||
return $this->getTable()->getDatabase()->getTable($this->getParameter('foreign_table'));
|
||||
}
|
||||
|
||||
protected function getForeignKey()
|
||||
{
|
||||
$foreignTable = $this->getForeignTable();
|
||||
// let's infer the relation from the foreign table
|
||||
$fks = $this->getTable()->getForeignKeysReferencingTable($foreignTable->getName());
|
||||
// FIXME doesn't work when more than one fk to the same table
|
||||
return array_shift($fks);
|
||||
}
|
||||
|
||||
protected function getRelationName($builder)
|
||||
{
|
||||
return $builder->getFKPhpNameAffix($this->getForeignKey());
|
||||
}
|
||||
|
||||
protected static function lcfirst($input)
|
||||
{
|
||||
// no lcfirst in php<5.3...
|
||||
$input[0] = strtolower($input[0]);
|
||||
return $input;
|
||||
}
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
|
||||
/**
|
||||
* Computes the value of the aggregate column <?php echo $column->getName() ?>
|
||||
*
|
||||
* @param PropelPDO $con A connection object
|
||||
*
|
||||
* @return mixed The scalar result from the aggregate query
|
||||
*/
|
||||
public function compute<?php echo $column->getPhpName() ?>(PropelPDO $con)
|
||||
{
|
||||
$stmt = $con->prepare('<?php echo $sql ?>');
|
||||
<?php foreach ($bindings as $key => $binding): ?>
|
||||
$stmt->bindValue(':p<?php echo $key ?>', $this->get<?php echo $binding ?>());
|
||||
<?php endforeach; ?>
|
||||
$stmt->execute();
|
||||
return $stmt->fetchColumn();
|
||||
}
|
|
@ -1,11 +0,0 @@
|
|||
|
||||
/**
|
||||
* Updates the aggregate column <?php echo $column->getName() ?>
|
||||
*
|
||||
* @param PropelPDO $con A connection object
|
||||
*/
|
||||
public function update<?php echo $column->getPhpName() ?>(PropelPDO $con)
|
||||
{
|
||||
$this->set<?php echo $column->getPhpName() ?>($this->compute<?php echo $column->getPhpName() ?>($con));
|
||||
$this->save($con);
|
||||
}
|
|
@ -1,16 +0,0 @@
|
|||
|
||||
/**
|
||||
* Update the aggregate column in the related <?php echo $relationName ?> object
|
||||
*
|
||||
* @param PropelPDO $con A connection object
|
||||
*/
|
||||
protected function updateRelated<?php echo $relationName ?>(PropelPDO $con)
|
||||
{
|
||||
if ($<?php echo $variableName ?> = $this->get<?php echo $relationName ?>()) {
|
||||
$<?php echo $variableName ?>-><?php echo $updateMethodName ?>($con);
|
||||
}
|
||||
if ($this->old<?php echo $relationName ?>) {
|
||||
$this->old<?php echo $relationName ?>-><?php echo $updateMethodName ?>($con);
|
||||
$this->old<?php echo $relationName ?> = null;
|
||||
}
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
|
||||
/**
|
||||
* Finds the related <?php echo $foreignTable->getPhpName() ?> objects and keep them for later
|
||||
*
|
||||
* @param PropelPDO $con A connection object
|
||||
*/
|
||||
protected function findRelated<?php echo $relationName ?>s($con)
|
||||
{
|
||||
$criteria = clone $this;
|
||||
if ($this->useAliasInSQL) {
|
||||
$alias = $this->getModelAlias();
|
||||
$criteria->removeAlias($alias);
|
||||
} else {
|
||||
$alias = '';
|
||||
}
|
||||
$this-><?php echo $variableName ?>s = <?php echo $foreignQueryName ?>::create()
|
||||
->join<?php echo $refRelationName ?>($alias)
|
||||
->mergeWith($criteria)
|
||||
->find($con);
|
||||
}
|
|
@ -1,8 +0,0 @@
|
|||
|
||||
protected function updateRelated<?php echo $relationName ?>s($con)
|
||||
{
|
||||
foreach ($this-><?php echo $variableName ?>s as $<?php echo $variableName ?>) {
|
||||
$<?php echo $variableName ?>-><?php echo $updateMethodName ?>($con);
|
||||
}
|
||||
$this-><?php echo $variableName ?>s = array();
|
||||
}
|
|
@ -1,235 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
require_once 'ConcreteInheritanceParentBehavior.php';
|
||||
|
||||
/**
|
||||
* Gives a model class the ability to remain in database even when the user deletes object
|
||||
* Uses an additional column storing the deletion date
|
||||
* And an additional condition for every read query to only consider rows with no deletion date
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @version $Revision: 1774 $
|
||||
* @package propel.generator.behavior.concrete_inheritance
|
||||
*/
|
||||
class ConcreteInheritanceBehavior extends Behavior
|
||||
{
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'extends' => '',
|
||||
'descendant_column' => 'descendant_class',
|
||||
'copy_data_to_parent' => 'true'
|
||||
);
|
||||
|
||||
public function modifyTable()
|
||||
{
|
||||
$table = $this->getTable();
|
||||
$parentTable = $this->getParentTable();
|
||||
|
||||
if ($this->isCopyData()) {
|
||||
// tell the parent table that it has a descendant
|
||||
if (!$parentTable->hasBehavior('concrete_inheritance_parent')) {
|
||||
$parentBehavior = new ConcreteInheritanceParentBehavior();
|
||||
$parentBehavior->setName('concrete_inheritance_parent');
|
||||
$parentBehavior->addParameter(array('name' => 'descendant_column', 'value' => $this->getParameter('descendant_column')));
|
||||
$parentTable->addBehavior($parentBehavior);
|
||||
// The parent table's behavior modifyTable() must be executed before this one
|
||||
$parentBehavior->getTableModifier()->modifyTable();
|
||||
$parentBehavior->setTableModified(true);
|
||||
}
|
||||
}
|
||||
|
||||
// Add the columns of the parent table
|
||||
foreach ($parentTable->getColumns() as $column) {
|
||||
if ($column->getName() == $this->getParameter('descendant_column')) {
|
||||
continue;
|
||||
}
|
||||
if ($table->containsColumn($column->getName())) {
|
||||
continue;
|
||||
}
|
||||
$copiedColumn = clone $column;
|
||||
if ($column->isAutoIncrement() && $this->isCopyData()) {
|
||||
$copiedColumn->setAutoIncrement(false);
|
||||
}
|
||||
$table->addColumn($copiedColumn);
|
||||
if ($column->isPrimaryKey() && $this->isCopyData()) {
|
||||
$fk = new ForeignKey();
|
||||
$fk->setForeignTableName($column->getTable()->getName());
|
||||
$fk->setOnDelete('CASCADE');
|
||||
$fk->setOnUpdate(null);
|
||||
$fk->addReference($copiedColumn, $column);
|
||||
$fk->isParentChild = true;
|
||||
$table->addForeignKey($fk);
|
||||
}
|
||||
}
|
||||
|
||||
// add the foreign keys of the parent table
|
||||
foreach ($parentTable->getForeignKeys() as $fk) {
|
||||
$copiedFk = clone $fk;
|
||||
$copiedFk->setName('');
|
||||
$copiedFk->setRefPhpName('');
|
||||
$this->getTable()->addForeignKey($copiedFk);
|
||||
}
|
||||
|
||||
// add the validators of the parent table
|
||||
foreach ($parentTable->getValidators() as $validator) {
|
||||
$copiedValidator = clone $validator;
|
||||
$this->getTable()->addValidator($copiedValidator);
|
||||
}
|
||||
|
||||
// add the indices of the parent table
|
||||
foreach ($parentTable->getIndices() as $index) {
|
||||
$copiedIndex = clone $index;
|
||||
$copiedIndex->setName('');
|
||||
$this->getTable()->addIndex($copiedIndex);
|
||||
}
|
||||
|
||||
// add the unique indices of the parent table
|
||||
foreach ($parentTable->getUnices() as $unique) {
|
||||
$copiedUnique = clone $unique;
|
||||
$copiedUnique->setName('');
|
||||
$this->getTable()->addUnique($copiedUnique);
|
||||
}
|
||||
|
||||
// give name to newly added foreign keys and indices
|
||||
// (this is already done for other elements of the current table)
|
||||
$table->doNaming();
|
||||
|
||||
// add the Behaviors of the parent table
|
||||
foreach ($parentTable->getBehaviors() as $behavior) {
|
||||
if ($behavior->getName() == 'concrete_inheritance_parent' || $behavior->getName() == 'concrete_inheritance') {
|
||||
continue;
|
||||
}
|
||||
$copiedBehavior = clone $behavior;
|
||||
$this->getTable()->addBehavior($copiedBehavior);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
protected function getParentTable()
|
||||
{
|
||||
return $this->getTable()->getDatabase()->getTable($this->getParameter('extends'));
|
||||
}
|
||||
|
||||
protected function isCopyData()
|
||||
{
|
||||
return $this->getParameter('copy_data_to_parent') == 'true';
|
||||
}
|
||||
|
||||
public function parentClass($builder)
|
||||
{
|
||||
switch (get_class($builder)) {
|
||||
case 'PHP5ObjectBuilder':
|
||||
return $builder->getNewStubObjectBuilder($this->getParentTable())->getClassname();
|
||||
break;
|
||||
case 'QueryBuilder':
|
||||
return $builder->getNewStubQueryBuilder($this->getParentTable())->getClassname();
|
||||
break;
|
||||
default:
|
||||
return null;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public function preSave($script)
|
||||
{
|
||||
if ($this->isCopyData()) {
|
||||
return "\$parent = \$this->getSyncParent(\$con);
|
||||
\$parent->save(\$con);
|
||||
\$this->setPrimaryKey(\$parent->getPrimaryKey());
|
||||
";
|
||||
}
|
||||
}
|
||||
|
||||
public function postDelete($script)
|
||||
{
|
||||
if ($this->isCopyData()) {
|
||||
return "\$this->getParentOrCreate(\$con)->delete(\$con);
|
||||
";
|
||||
}
|
||||
}
|
||||
|
||||
public function objectMethods($builder)
|
||||
{
|
||||
if (!$this->isCopyData()) {
|
||||
return;
|
||||
}
|
||||
$this->builder = $builder;
|
||||
$script .= '';
|
||||
$this->addObjectGetParentOrCreate($script);
|
||||
$this->addObjectGetSyncParent($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addObjectGetParentOrCreate(&$script)
|
||||
{
|
||||
$parentTable = $this->getParentTable();
|
||||
$parentClass = $this->builder->getNewStubObjectBuilder($parentTable)->getClassname();
|
||||
$script .= "
|
||||
/**
|
||||
* Get or Create the parent " . $parentClass . " object of the current object
|
||||
*
|
||||
* @return " . $parentClass . " The parent object
|
||||
*/
|
||||
public function getParentOrCreate(\$con = null)
|
||||
{
|
||||
if (\$this->isNew()) {
|
||||
\$parent = new " . $parentClass . "();
|
||||
\$parent->set" . $this->getParentTable()->getColumn($this->getParameter('descendant_column'))->getPhpName() . "('" . $this->builder->getStubObjectBuilder()->getClassname() . "');
|
||||
return \$parent;
|
||||
} else {
|
||||
return " . $this->builder->getNewStubQueryBuilder($parentTable)->getClassname() . "::create()->findPk(\$this->getPrimaryKey(), \$con);
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addObjectGetSyncParent(&$script)
|
||||
{
|
||||
$parentTable = $this->getParentTable();
|
||||
$pkeys = $parentTable->getPrimaryKey();
|
||||
$cptype = $pkeys[0]->getPhpType();
|
||||
$script .= "
|
||||
/**
|
||||
* Create or Update the parent " . $parentTable->getPhpName() . " object
|
||||
* And return its primary key
|
||||
*
|
||||
* @return " . $cptype . " The primary key of the parent object
|
||||
*/
|
||||
public function getSyncParent(\$con = null)
|
||||
{
|
||||
\$parent = \$this->getParentOrCreate(\$con);";
|
||||
foreach ($parentTable->getColumns() as $column) {
|
||||
if ($column->isPrimaryKey() || $column->getName() == $this->getParameter('descendant_column')) {
|
||||
continue;
|
||||
}
|
||||
$phpName = $column->getPhpName();
|
||||
$script .= "
|
||||
\$parent->set{$phpName}(\$this->get{$phpName}());";
|
||||
}
|
||||
foreach ($parentTable->getForeignKeys() as $fk) {
|
||||
if (isset($fk->isParentChild) && $fk->isParentChild) {
|
||||
continue;
|
||||
}
|
||||
$refPhpName = $this->builder->getFKPhpNameAffix($fk, $plural = false);
|
||||
$script .= "
|
||||
if (\$this->get" . $refPhpName . "() && \$this->get" . $refPhpName . "()->isNew()) {
|
||||
\$parent->set" . $refPhpName . "(\$this->get" . $refPhpName . "());
|
||||
}";
|
||||
}
|
||||
$script .= "
|
||||
|
||||
return \$parent;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
}
|
|
@ -1,89 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Gives a model class the ability to remain in database even when the user deletes object
|
||||
* Uses an additional column storing the deletion date
|
||||
* And an additional condition for every read query to only consider rows with no deletion date
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @version $Revision: 1612 $
|
||||
* @package propel.generator.behavior.concrete_inheritance
|
||||
*/
|
||||
class ConcreteInheritanceParentBehavior extends Behavior
|
||||
{
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'descendant_column' => 'descendant_class'
|
||||
);
|
||||
|
||||
public function modifyTable()
|
||||
{
|
||||
$table = $this->getTable();
|
||||
if (!$table->containsColumn($this->getParameter('descendant_column'))) {
|
||||
$table->addColumn(array(
|
||||
'name' => $this->getParameter('descendant_column'),
|
||||
'type' => 'VARCHAR',
|
||||
'size' => 100
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
protected function getColumnGetter()
|
||||
{
|
||||
return 'get' . $this->getColumnForParameter('descendant_column')->getPhpName();
|
||||
}
|
||||
|
||||
public function objectMethods($builder)
|
||||
{
|
||||
$this->builder = $builder;
|
||||
$script .= '';
|
||||
$this->addHasChildObject($script);
|
||||
$this->addGetChildObject($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addHasChildObject(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Whether or not this object is the parent of a child object
|
||||
*
|
||||
* @return bool
|
||||
*/
|
||||
public function hasChildObject()
|
||||
{
|
||||
return \$this->" . $this->getColumnGetter() . "() !== null;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addGetChildObject(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Get the child object of this object
|
||||
*
|
||||
* @return mixed
|
||||
*/
|
||||
public function getChildObject()
|
||||
{
|
||||
if (!\$this->hasChildObject()) {
|
||||
return null;
|
||||
}
|
||||
\$childObjectClass = \$this->" . $this->getColumnGetter() . "();
|
||||
\$childObject = PropelQuery::from(\$childObjectClass)->findPk(\$this->getPrimaryKey());
|
||||
return \$childObject->hasChildObject() ? \$childObject->getChildObject() : \$childObject;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
}
|
|
@ -1,99 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
require_once dirname(__FILE__) . '/NestedSetBehaviorObjectBuilderModifier.php';
|
||||
require_once dirname(__FILE__) . '/NestedSetBehaviorQueryBuilderModifier.php';
|
||||
require_once dirname(__FILE__) . '/NestedSetBehaviorPeerBuilderModifier.php';
|
||||
|
||||
/**
|
||||
* Behavior to adds nested set tree structure columns and abilities
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @package propel.generator.behavior.nestedset
|
||||
*/
|
||||
class NestedSetBehavior extends Behavior
|
||||
{
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'left_column' => 'tree_left',
|
||||
'right_column' => 'tree_right',
|
||||
'level_column' => 'tree_level',
|
||||
'use_scope' => 'false',
|
||||
'scope_column' => 'tree_scope',
|
||||
'method_proxies' => 'false'
|
||||
);
|
||||
|
||||
protected $objectBuilderModifier, $queryBuilderModifier, $peerBuilderModifier;
|
||||
|
||||
/**
|
||||
* Add the left, right and scope to the current table
|
||||
*/
|
||||
public function modifyTable()
|
||||
{
|
||||
if(!$this->getTable()->containsColumn($this->getParameter('left_column'))) {
|
||||
$this->getTable()->addColumn(array(
|
||||
'name' => $this->getParameter('left_column'),
|
||||
'type' => 'INTEGER'
|
||||
));
|
||||
}
|
||||
if(!$this->getTable()->containsColumn($this->getParameter('right_column'))) {
|
||||
$this->getTable()->addColumn(array(
|
||||
'name' => $this->getParameter('right_column'),
|
||||
'type' => 'INTEGER'
|
||||
));
|
||||
}
|
||||
if(!$this->getTable()->containsColumn($this->getParameter('level_column'))) {
|
||||
$this->getTable()->addColumn(array(
|
||||
'name' => $this->getParameter('level_column'),
|
||||
'type' => 'INTEGER'
|
||||
));
|
||||
}
|
||||
if ($this->getParameter('use_scope') == 'true' &&
|
||||
!$this->getTable()->containsColumn($this->getParameter('scope_column'))) {
|
||||
$this->getTable()->addColumn(array(
|
||||
'name' => $this->getParameter('scope_column'),
|
||||
'type' => 'INTEGER'
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
public function getObjectBuilderModifier()
|
||||
{
|
||||
if (is_null($this->objectBuilderModifier))
|
||||
{
|
||||
$this->objectBuilderModifier = new NestedSetBehaviorObjectBuilderModifier($this);
|
||||
}
|
||||
return $this->objectBuilderModifier;
|
||||
}
|
||||
|
||||
public function getQueryBuilderModifier()
|
||||
{
|
||||
if (is_null($this->queryBuilderModifier))
|
||||
{
|
||||
$this->queryBuilderModifier = new NestedSetBehaviorQueryBuilderModifier($this);
|
||||
}
|
||||
return $this->queryBuilderModifier;
|
||||
}
|
||||
|
||||
public function getPeerBuilderModifier()
|
||||
{
|
||||
if (is_null($this->peerBuilderModifier))
|
||||
{
|
||||
$this->peerBuilderModifier = new NestedSetBehaviorPeerBuilderModifier($this);
|
||||
}
|
||||
return $this->peerBuilderModifier;
|
||||
}
|
||||
|
||||
public function useScope()
|
||||
{
|
||||
return $this->getParameter('use_scope') == 'true';
|
||||
}
|
||||
|
||||
}
|
File diff suppressed because it is too large
Load Diff
|
@ -1,555 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Behavior to adds nested set tree structure columns and abilities
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @author heltem <heltem@o2php.com>
|
||||
* @package propel.generator.behavior.nestedset
|
||||
*/
|
||||
class NestedSetBehaviorPeerBuilderModifier
|
||||
{
|
||||
protected $behavior, $table, $builder, $objectClassname, $peerClassname;
|
||||
|
||||
public function __construct($behavior)
|
||||
{
|
||||
$this->behavior = $behavior;
|
||||
$this->table = $behavior->getTable();
|
||||
}
|
||||
|
||||
protected function getParameter($key)
|
||||
{
|
||||
return $this->behavior->getParameter($key);
|
||||
}
|
||||
|
||||
protected function getColumn($name)
|
||||
{
|
||||
return $this->behavior->getColumnForParameter($name);
|
||||
}
|
||||
|
||||
protected function getColumnAttribute($name)
|
||||
{
|
||||
return strtolower($this->getColumn($name)->getName());
|
||||
}
|
||||
|
||||
protected function getColumnConstant($name)
|
||||
{
|
||||
return strtoupper($this->getColumn($name)->getName());
|
||||
}
|
||||
|
||||
protected function getColumnPhpName($name)
|
||||
{
|
||||
return $this->getColumn($name)->getPhpName();
|
||||
}
|
||||
|
||||
protected function setBuilder($builder)
|
||||
{
|
||||
$this->builder = $builder;
|
||||
$this->objectClassname = $builder->getStubObjectBuilder()->getClassname();
|
||||
$this->peerClassname = $builder->getStubPeerBuilder()->getClassname();
|
||||
}
|
||||
|
||||
public function staticAttributes($builder)
|
||||
{
|
||||
$tableName = $this->table->getName();
|
||||
|
||||
$script = "
|
||||
/**
|
||||
* Left column for the set
|
||||
*/
|
||||
const LEFT_COL = '" . $tableName . '.' . $this->getColumnConstant('left_column') . "';
|
||||
|
||||
/**
|
||||
* Right column for the set
|
||||
*/
|
||||
const RIGHT_COL = '" . $tableName . '.' . $this->getColumnConstant('right_column') . "';
|
||||
|
||||
/**
|
||||
* Level column for the set
|
||||
*/
|
||||
const LEVEL_COL = '" . $tableName . '.' . $this->getColumnConstant('level_column') . "';
|
||||
";
|
||||
|
||||
if ($this->behavior->useScope()) {
|
||||
$script .= "
|
||||
/**
|
||||
* Scope column for the set
|
||||
*/
|
||||
const SCOPE_COL = '" . $tableName . '.' . $this->getColumnConstant('scope_column') . "';
|
||||
";
|
||||
}
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
public function staticMethods($builder)
|
||||
{
|
||||
$this->setBuilder($builder);
|
||||
$script = '';
|
||||
|
||||
if ($this->getParameter('use_scope') == 'true')
|
||||
{
|
||||
$this->addRetrieveRoots($script);
|
||||
}
|
||||
$this->addRetrieveRoot($script);
|
||||
$this->addRetrieveTree($script);
|
||||
$this->addIsValid($script);
|
||||
$this->addDeleteTree($script);
|
||||
$this->addShiftRLValues($script);
|
||||
$this->addShiftLevel($script);
|
||||
$this->addUpdateLoadedNodes($script);
|
||||
$this->addMakeRoomForLeaf($script);
|
||||
$this->addFixLevels($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addRetrieveRoots(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Returns the root nodes for the tree
|
||||
*
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
* @return {$this->objectClassname} Propel object for root node
|
||||
*/
|
||||
public static function retrieveRoots(Criteria \$criteria = null, PropelPDO \$con = null)
|
||||
{
|
||||
if (\$criteria === null) {
|
||||
\$criteria = new Criteria($peerClassname::DATABASE_NAME);
|
||||
}
|
||||
\$criteria->add($peerClassname::LEFT_COL, 1, Criteria::EQUAL);
|
||||
|
||||
return $peerClassname::doSelect(\$criteria, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addRetrieveRoot(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Returns the root node for a given scope
|
||||
*";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to determine which root node to return";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
* @return {$this->objectClassname} Propel object for root node
|
||||
*/
|
||||
public static function retrieveRoot(" . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null)
|
||||
{
|
||||
\$c = new Criteria($peerClassname::DATABASE_NAME);
|
||||
\$c->add($peerClassname::LEFT_COL, 1, Criteria::EQUAL);";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
\$c->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);";
|
||||
}
|
||||
$script .= "
|
||||
|
||||
return $peerClassname::doSelectOne(\$c, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addRetrieveTree(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Returns the whole tree node for a given scope
|
||||
*";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to determine which root node to return";
|
||||
}
|
||||
$script .= "
|
||||
* @param Criteria \$criteria Optional Criteria to filter the query
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
* @return {$this->objectClassname} Propel object for root node
|
||||
*/
|
||||
public static function retrieveTree(" . ($useScope ? "\$scope = null, " : "") . "Criteria \$criteria = null, PropelPDO \$con = null)
|
||||
{
|
||||
if (\$criteria === null) {
|
||||
\$criteria = new Criteria($peerClassname::DATABASE_NAME);
|
||||
}
|
||||
\$criteria->addAscendingOrderByColumn($peerClassname::LEFT_COL);";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
\$criteria->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);";
|
||||
}
|
||||
$script .= "
|
||||
|
||||
return $peerClassname::doSelect(\$criteria, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addIsValid(&$script)
|
||||
{
|
||||
$objectClassname = $this->objectClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Tests if node is valid
|
||||
*
|
||||
* @param $objectClassname \$node Propel object for src node
|
||||
* @return bool
|
||||
*/
|
||||
public static function isValid($objectClassname \$node = null)
|
||||
{
|
||||
if (is_object(\$node) && \$node->getRightValue() > \$node->getLeftValue()) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addDeleteTree(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Delete an entire tree
|
||||
* ";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to determine which tree to delete";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
*
|
||||
* @return int The number of deleted nodes
|
||||
*/
|
||||
public static function deleteTree(" . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null)
|
||||
{";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
\$c = new Criteria($peerClassname::DATABASE_NAME);
|
||||
\$c->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);
|
||||
return $peerClassname::doDelete(\$c, \$con);";
|
||||
} else {
|
||||
$script .= "
|
||||
return $peerClassname::doDeleteAll(\$con);";
|
||||
}
|
||||
$script .= "
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addShiftRLValues(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Adds \$delta to all L and R values that are >= \$first and <= \$last.
|
||||
* '\$delta' can also be negative.
|
||||
*
|
||||
* @param int \$delta Value to be shifted by, can be negative
|
||||
* @param int \$first First node to be shifted
|
||||
* @param int \$last Last node to be shifted (optional)";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to use for the shift";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
*/
|
||||
public static function shiftRLValues(\$delta, \$first, \$last = null" . ($useScope ? ", \$scope = null" : ""). ", PropelPDO \$con = null)
|
||||
{
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE);
|
||||
}
|
||||
|
||||
// Shift left column values
|
||||
\$whereCriteria = new Criteria($peerClassname::DATABASE_NAME);
|
||||
\$criterion = \$whereCriteria->getNewCriterion($peerClassname::LEFT_COL, \$first, Criteria::GREATER_EQUAL);
|
||||
if (null !== \$last) {
|
||||
\$criterion->addAnd(\$whereCriteria->getNewCriterion($peerClassname::LEFT_COL, \$last, Criteria::LESS_EQUAL));
|
||||
}
|
||||
\$whereCriteria->add(\$criterion);";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
\$whereCriteria->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);";
|
||||
}
|
||||
$script .= "
|
||||
|
||||
\$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME);
|
||||
\$valuesCriteria->add($peerClassname::LEFT_COL, array('raw' => $peerClassname::LEFT_COL . ' + ?', 'value' => \$delta), Criteria::CUSTOM_EQUAL);
|
||||
|
||||
{$this->builder->getBasePeerClassname()}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con);
|
||||
|
||||
// Shift right column values
|
||||
\$whereCriteria = new Criteria($peerClassname::DATABASE_NAME);
|
||||
\$criterion = \$whereCriteria->getNewCriterion($peerClassname::RIGHT_COL, \$first, Criteria::GREATER_EQUAL);
|
||||
if (null !== \$last) {
|
||||
\$criterion->addAnd(\$whereCriteria->getNewCriterion($peerClassname::RIGHT_COL, \$last, Criteria::LESS_EQUAL));
|
||||
}
|
||||
\$whereCriteria->add(\$criterion);";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
\$whereCriteria->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);";
|
||||
}
|
||||
$script .= "
|
||||
|
||||
\$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME);
|
||||
\$valuesCriteria->add($peerClassname::RIGHT_COL, array('raw' => $peerClassname::RIGHT_COL . ' + ?', 'value' => \$delta), Criteria::CUSTOM_EQUAL);
|
||||
|
||||
{$this->builder->getBasePeerClassname()}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addShiftLevel(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Adds \$delta to level for nodes having left value >= \$first and right value <= \$last.
|
||||
* '\$delta' can also be negative.
|
||||
*
|
||||
* @param int \$delta Value to be shifted by, can be negative
|
||||
* @param int \$first First node to be shifted
|
||||
* @param int \$last Last node to be shifted";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to use for the shift";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
*/
|
||||
public static function shiftLevel(\$delta, \$first, \$last" . ($useScope ? ", \$scope = null" : ""). ", PropelPDO \$con = null)
|
||||
{
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE);
|
||||
}
|
||||
|
||||
\$whereCriteria = new Criteria($peerClassname::DATABASE_NAME);
|
||||
\$whereCriteria->add($peerClassname::LEFT_COL, \$first, Criteria::GREATER_EQUAL);
|
||||
\$whereCriteria->add($peerClassname::RIGHT_COL, \$last, Criteria::LESS_EQUAL);";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
\$whereCriteria->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);";
|
||||
}
|
||||
$script .= "
|
||||
|
||||
\$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME);
|
||||
\$valuesCriteria->add($peerClassname::LEVEL_COL, array('raw' => $peerClassname::LEVEL_COL . ' + ?', 'value' => \$delta), Criteria::CUSTOM_EQUAL);
|
||||
|
||||
{$this->builder->getBasePeerClassname()}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addUpdateLoadedNodes(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Reload all already loaded nodes to sync them with updated db
|
||||
*
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
*/
|
||||
public static function updateLoadedNodes(PropelPDO \$con = null)
|
||||
{
|
||||
if (Propel::isInstancePoolingEnabled()) {
|
||||
\$keys = array();
|
||||
foreach ($peerClassname::\$instances as \$obj) {
|
||||
\$keys[] = \$obj->getPrimaryKey();
|
||||
}
|
||||
|
||||
if (!empty(\$keys)) {
|
||||
// We don't need to alter the object instance pool; we're just modifying these ones
|
||||
// already in the pool.
|
||||
\$criteria = new Criteria($peerClassname::DATABASE_NAME);";
|
||||
if (count($this->table->getPrimaryKey()) === 1) {
|
||||
$pkey = $this->table->getPrimaryKey();
|
||||
$col = array_shift($pkey);
|
||||
$script .= "
|
||||
\$criteria->add(".$this->builder->getColumnConstant($col).", \$keys, Criteria::IN);
|
||||
";
|
||||
} else {
|
||||
$fields = array();
|
||||
foreach ($this->table->getPrimaryKey() as $k => $col) {
|
||||
$fields[] = $this->builder->getColumnConstant($col);
|
||||
};
|
||||
$script .= "
|
||||
|
||||
// Loop on each instances in pool
|
||||
foreach (\$keys as \$values) {
|
||||
// Create initial Criterion
|
||||
\$cton = \$criteria->getNewCriterion(" . $fields[0] . ", \$values[0]);";
|
||||
unset($fields[0]);
|
||||
foreach ($fields as $k => $col) {
|
||||
$script .= "
|
||||
|
||||
// Create next criterion
|
||||
\$nextcton = \$criteria->getNewCriterion(" . $col . ", \$values[$k]);
|
||||
// And merge it with the first
|
||||
\$cton->addAnd(\$nextcton);";
|
||||
}
|
||||
$script .= "
|
||||
|
||||
// Add final Criterion to Criteria
|
||||
\$criteria->addOr(\$cton);
|
||||
}";
|
||||
}
|
||||
|
||||
$script .= "
|
||||
\$stmt = $peerClassname::doSelectStmt(\$criteria, \$con);
|
||||
while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) {
|
||||
\$key = $peerClassname::getPrimaryKeyHashFromRow(\$row, 0);
|
||||
if (null !== (\$object = $peerClassname::getInstanceFromPool(\$key))) {";
|
||||
$n = 0;
|
||||
foreach ($this->table->getColumns() as $col) {
|
||||
if ($col->getPhpName() == $this->getColumnPhpName('left_column')) {
|
||||
$script .= "
|
||||
\$object->setLeftValue(\$row[$n]);";
|
||||
} else if ($col->getPhpName() == $this->getColumnPhpName('right_column')) {
|
||||
$script .= "
|
||||
\$object->setRightValue(\$row[$n]);";
|
||||
} else if ($col->getPhpName() == $this->getColumnPhpName('level_column')) {
|
||||
$script .= "
|
||||
\$object->setLevel(\$row[$n]);
|
||||
\$object->clearNestedSetChildren();";
|
||||
}
|
||||
$n++;
|
||||
}
|
||||
$script .= "
|
||||
}
|
||||
}
|
||||
\$stmt->closeCursor();
|
||||
}
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addMakeRoomForLeaf(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Update the tree to allow insertion of a leaf at the specified position
|
||||
*
|
||||
* @param int \$left left column value";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
* @param integer \$scope scope column value";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
*/
|
||||
public static function makeRoomForLeaf(\$left" . ($useScope ? ", \$scope" : ""). ", PropelPDO \$con = null)
|
||||
{
|
||||
// Update database nodes
|
||||
$peerClassname::shiftRLValues(2, \$left, null" . ($useScope ? ", \$scope" : "") . ", \$con);
|
||||
|
||||
// Update all loaded nodes
|
||||
$peerClassname::updateLoadedNodes(\$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addFixLevels(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Update the tree to allow insertion of a leaf at the specified position
|
||||
*";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
* @param integer \$scope scope column value";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
*/
|
||||
public static function fixLevels(" . ($useScope ? "\$scope, " : ""). "PropelPDO \$con = null)
|
||||
{
|
||||
\$c = new Criteria();";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
\$c->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);";
|
||||
}
|
||||
$script .= "
|
||||
\$c->addAscendingOrderByColumn($peerClassname::LEFT_COL);
|
||||
\$stmt = $peerClassname::doSelectStmt(\$c, \$con);
|
||||
";
|
||||
if (!$this->table->getChildrenColumn()) {
|
||||
$script .= "
|
||||
// set the class once to avoid overhead in the loop
|
||||
\$cls = $peerClassname::getOMClass(false);";
|
||||
}
|
||||
|
||||
$script .= "
|
||||
\$level = null;
|
||||
// iterate over the statement
|
||||
while (\$row = \$stmt->fetch(PDO::FETCH_NUM)) {
|
||||
|
||||
// hydrate object
|
||||
\$key = $peerClassname::getPrimaryKeyHashFromRow(\$row, 0);
|
||||
if (null === (\$obj = $peerClassname::getInstanceFromPool(\$key))) {";
|
||||
if ($this->table->getChildrenColumn()) {
|
||||
$script .= "
|
||||
// class must be set each time from the record row
|
||||
\$cls = $peerClassname::getOMClass(\$row, 0);
|
||||
\$cls = substr('.'.\$cls, strrpos('.'.\$cls, '.') + 1);
|
||||
" . $this->builder->buildObjectInstanceCreationCode('$obj', '$cls') . "
|
||||
\$obj->hydrate(\$row);
|
||||
$peerClassname::addInstanceToPool(\$obj, \$key);";
|
||||
} else {
|
||||
$script .= "
|
||||
" . $this->builder->buildObjectInstanceCreationCode('$obj', '$cls') . "
|
||||
\$obj->hydrate(\$row);
|
||||
$peerClassname::addInstanceToPool(\$obj, \$key);";
|
||||
}
|
||||
$script .= "
|
||||
}
|
||||
|
||||
// compute level
|
||||
// Algorithm shamelessly stolen from sfPropelActAsNestedSetBehaviorPlugin
|
||||
// Probably authored by Tristan Rivoallan
|
||||
if (\$level === null) {
|
||||
\$level = 0;
|
||||
\$i = 0;
|
||||
\$prev = array(\$obj->getRightValue());
|
||||
} else {
|
||||
while (\$obj->getRightValue() > \$prev[\$i]) {
|
||||
\$i--;
|
||||
}
|
||||
\$level = ++\$i;
|
||||
\$prev[\$i] = \$obj->getRightValue();
|
||||
}
|
||||
|
||||
// update level in node if necessary
|
||||
if (\$obj->getLevel() !== \$level) {
|
||||
\$obj->setLevel(\$level);
|
||||
\$obj->save(\$con);
|
||||
}
|
||||
}
|
||||
\$stmt->closeCursor();
|
||||
}
|
||||
";
|
||||
}
|
||||
}
|
|
@ -1,357 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Behavior to adds nested set tree structure columns and abilities
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @package propel.generator.behavior.nestedset
|
||||
*/
|
||||
class NestedSetBehaviorQueryBuilderModifier
|
||||
{
|
||||
protected $behavior, $table, $builder, $objectClassname, $peerClassname;
|
||||
|
||||
public function __construct($behavior)
|
||||
{
|
||||
$this->behavior = $behavior;
|
||||
$this->table = $behavior->getTable();
|
||||
}
|
||||
|
||||
protected function getParameter($key)
|
||||
{
|
||||
return $this->behavior->getParameter($key);
|
||||
}
|
||||
|
||||
protected function getColumn($name)
|
||||
{
|
||||
return $this->behavior->getColumnForParameter($name);
|
||||
}
|
||||
|
||||
protected function setBuilder($builder)
|
||||
{
|
||||
$this->builder = $builder;
|
||||
$this->objectClassname = $builder->getStubObjectBuilder()->getClassname();
|
||||
$this->queryClassname = $builder->getStubQueryBuilder()->getClassname();
|
||||
$this->peerClassname = $builder->getStubPeerBuilder()->getClassname();
|
||||
}
|
||||
|
||||
public function queryMethods($builder)
|
||||
{
|
||||
$this->setBuilder($builder);
|
||||
$script = '';
|
||||
|
||||
// select filters
|
||||
if ($this->behavior->useScope()) {
|
||||
$this->addTreeRoots($script);
|
||||
$this->addInTree($script);
|
||||
}
|
||||
$this->addDescendantsOf($script);
|
||||
$this->addBranchOf($script);
|
||||
$this->addChildrenOf($script);
|
||||
$this->addSiblingsOf($script);
|
||||
$this->addAncestorsOf($script);
|
||||
$this->addRootsOf($script);
|
||||
// select orders
|
||||
$this->addOrderByBranch($script);
|
||||
$this->addOrderByLevel($script);
|
||||
// select termination methods
|
||||
$this->addFindRoot($script);
|
||||
$this->addFindTree($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addTreeRoots(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Filter the query to restrict the result to root objects
|
||||
*
|
||||
* @return {$this->queryClassname} The current query, for fuid interface
|
||||
*/
|
||||
public function treeRoots()
|
||||
{
|
||||
return \$this->addUsingAlias({$this->peerClassname}::LEFT_COL, 1, Criteria::EQUAL);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addInTree(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Returns the objects in a certain tree, from the tree scope
|
||||
*
|
||||
* @param int \$scope Scope to determine which objects node to return
|
||||
*
|
||||
* @return {$this->queryClassname} The current query, for fuid interface
|
||||
*/
|
||||
public function inTree(\$scope = null)
|
||||
{
|
||||
return \$this->addUsingAlias({$this->peerClassname}::SCOPE_COL, \$scope, Criteria::EQUAL);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addDescendantsOf(&$script)
|
||||
{
|
||||
$objectName = '$' . $this->table->getStudlyPhpName();
|
||||
$script .= "
|
||||
/**
|
||||
* Filter the query to restrict the result to descendants of an object
|
||||
*
|
||||
* @param {$this->objectClassname} $objectName The object to use for descendant search
|
||||
*
|
||||
* @return {$this->queryClassname} The current query, for fuid interface
|
||||
*/
|
||||
public function descendantsOf($objectName)
|
||||
{
|
||||
return \$this";
|
||||
if ($this->behavior->useScope()) {
|
||||
$script .= "
|
||||
->inTree({$objectName}->getScopeValue())";
|
||||
}
|
||||
$script .= "
|
||||
->addUsingAlias({$this->peerClassname}::LEFT_COL, {$objectName}->getLeftValue(), Criteria::GREATER_THAN)
|
||||
->addUsingAlias({$this->peerClassname}::RIGHT_COL, {$objectName}->getRightValue(), Criteria::LESS_THAN);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addBranchOf(&$script)
|
||||
{
|
||||
$objectName = '$' . $this->table->getStudlyPhpName();
|
||||
$script .= "
|
||||
/**
|
||||
* Filter the query to restrict the result to the branch of an object.
|
||||
* Same as descendantsOf(), except that it includes the object passed as parameter in the result
|
||||
*
|
||||
* @param {$this->objectClassname} $objectName The object to use for branch search
|
||||
*
|
||||
* @return {$this->queryClassname} The current query, for fuid interface
|
||||
*/
|
||||
public function branchOf($objectName)
|
||||
{
|
||||
return \$this";
|
||||
if ($this->behavior->useScope()) {
|
||||
$script .= "
|
||||
->inTree({$objectName}->getScopeValue())";
|
||||
}
|
||||
$script .= "
|
||||
->addUsingAlias({$this->peerClassname}::LEFT_COL, {$objectName}->getLeftValue(), Criteria::GREATER_EQUAL)
|
||||
->addUsingAlias({$this->peerClassname}::RIGHT_COL, {$objectName}->getRightValue(), Criteria::LESS_EQUAL);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addChildrenOf(&$script)
|
||||
{
|
||||
$objectName = '$' . $this->table->getStudlyPhpName();
|
||||
$script .= "
|
||||
/**
|
||||
* Filter the query to restrict the result to children of an object
|
||||
*
|
||||
* @param {$this->objectClassname} $objectName The object to use for child search
|
||||
*
|
||||
* @return {$this->queryClassname} The current query, for fuid interface
|
||||
*/
|
||||
public function childrenOf($objectName)
|
||||
{
|
||||
return \$this
|
||||
->descendantsOf($objectName)
|
||||
->addUsingAlias({$this->peerClassname}::LEVEL_COL, {$objectName}->getLevel() + 1, Criteria::EQUAL);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addSiblingsOf(&$script)
|
||||
{
|
||||
$objectName = '$' . $this->table->getStudlyPhpName();
|
||||
$script .= "
|
||||
/**
|
||||
* Filter the query to restrict the result to siblings of an object.
|
||||
* The result does not include the object passed as parameter.
|
||||
*
|
||||
* @param {$this->objectClassname} $objectName The object to use for sibling search
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
*
|
||||
* @return {$this->queryClassname} The current query, for fuid interface
|
||||
*/
|
||||
public function siblingsOf($objectName, PropelPDO \$con = null)
|
||||
{
|
||||
if ({$objectName}->isRoot()) {
|
||||
return \$this->
|
||||
add({$this->peerClassname}::LEVEL_COL, '1<>1', Criteria::CUSTOM);
|
||||
} else {
|
||||
return \$this
|
||||
->childrenOf({$objectName}->getParent(\$con))
|
||||
->prune($objectName);
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addAncestorsOf(&$script)
|
||||
{
|
||||
$objectName = '$' . $this->table->getStudlyPhpName();
|
||||
$script .= "
|
||||
/**
|
||||
* Filter the query to restrict the result to ancestors of an object
|
||||
*
|
||||
* @param {$this->objectClassname} $objectName The object to use for ancestors search
|
||||
*
|
||||
* @return {$this->queryClassname} The current query, for fuid interface
|
||||
*/
|
||||
public function ancestorsOf($objectName)
|
||||
{
|
||||
return \$this";
|
||||
if ($this->behavior->useScope()) {
|
||||
$script .= "
|
||||
->inTree({$objectName}->getScopeValue())";
|
||||
}
|
||||
$script .= "
|
||||
->addUsingAlias({$this->peerClassname}::LEFT_COL, {$objectName}->getLeftValue(), Criteria::LESS_THAN)
|
||||
->addUsingAlias({$this->peerClassname}::RIGHT_COL, {$objectName}->getRightValue(), Criteria::GREATER_THAN);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addRootsOf(&$script)
|
||||
{
|
||||
$objectName = '$' . $this->table->getStudlyPhpName();
|
||||
$script .= "
|
||||
/**
|
||||
* Filter the query to restrict the result to roots of an object.
|
||||
* Same as ancestorsOf(), except that it includes the object passed as parameter in the result
|
||||
*
|
||||
* @param {$this->objectClassname} $objectName The object to use for roots search
|
||||
*
|
||||
* @return {$this->queryClassname} The current query, for fuid interface
|
||||
*/
|
||||
public function rootsOf($objectName)
|
||||
{
|
||||
return \$this";
|
||||
if ($this->behavior->useScope()) {
|
||||
$script .= "
|
||||
->inTree({$objectName}->getScopeValue())";
|
||||
}
|
||||
$script .= "
|
||||
->addUsingAlias({$this->peerClassname}::LEFT_COL, {$objectName}->getLeftValue(), Criteria::LESS_EQUAL)
|
||||
->addUsingAlias({$this->peerClassname}::RIGHT_COL, {$objectName}->getRightValue(), Criteria::GREATER_EQUAL);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addOrderByBranch(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Order the result by branch, i.e. natural tree order
|
||||
*
|
||||
* @param bool \$reverse if true, reverses the order
|
||||
*
|
||||
* @return {$this->queryClassname} The current query, for fuid interface
|
||||
*/
|
||||
public function orderByBranch(\$reverse = false)
|
||||
{
|
||||
if (\$reverse) {
|
||||
return \$this
|
||||
->addDescendingOrderByColumn({$this->peerClassname}::LEFT_COL);
|
||||
} else {
|
||||
return \$this
|
||||
->addAscendingOrderByColumn({$this->peerClassname}::LEFT_COL);
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addOrderByLevel(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Order the result by level, the closer to the root first
|
||||
*
|
||||
* @param bool \$reverse if true, reverses the order
|
||||
*
|
||||
* @return {$this->queryClassname} The current query, for fuid interface
|
||||
*/
|
||||
public function orderByLevel(\$reverse = false)
|
||||
{
|
||||
if (\$reverse) {
|
||||
return \$this
|
||||
->addAscendingOrderByColumn({$this->peerClassname}::RIGHT_COL);
|
||||
} else {
|
||||
return \$this
|
||||
->addDescendingOrderByColumn({$this->peerClassname}::RIGHT_COL);
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addFindRoot(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Returns " . ($useScope ? 'a' : 'the') ." root node for the tree
|
||||
*";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to determine which root node to return";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
*
|
||||
* @return {$this->objectClassname} The tree root object
|
||||
*/
|
||||
public function findRoot(" . ($useScope ? "\$scope = null, " : "") . "\$con = null)
|
||||
{
|
||||
return \$this
|
||||
->addUsingAlias({$this->peerClassname}::LEFT_COL, 1, Criteria::EQUAL)";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
->inTree(\$scope)";
|
||||
}
|
||||
$script .= "
|
||||
->findOne(\$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addFindTree(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Returns " . ($useScope ? 'a' : 'the') ." tree of objects
|
||||
*";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to determine which tree node to return";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
*
|
||||
* @return mixed the list of results, formatted by the current formatter
|
||||
*/
|
||||
public function findTree(" . ($useScope ? "\$scope = null, " : "") . "\$con = null)
|
||||
{
|
||||
return \$this";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
->inTree(\$scope)";
|
||||
}
|
||||
$script .= "
|
||||
->orderByBranch()
|
||||
->find(\$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
}
|
|
@ -1,262 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Speeds up queries on a model by caching the query
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @version $Revision: 1746 $
|
||||
* @package propel.generator.behavior.cacheable
|
||||
*/
|
||||
class QueryCacheBehavior extends Behavior
|
||||
{
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'backend' => 'apc',
|
||||
'lifetime' => 3600,
|
||||
);
|
||||
|
||||
public function queryAttributes($builder)
|
||||
{
|
||||
$script = "protected \$queryKey = '';
|
||||
";
|
||||
switch ($this->getParameter('backend')) {
|
||||
case 'backend':
|
||||
$script .= "protected static \$cacheBackend = array();
|
||||
";
|
||||
break;
|
||||
case 'apc':
|
||||
break;
|
||||
case 'custom':
|
||||
default:
|
||||
$script .= "protected static \$cacheBackend;
|
||||
";
|
||||
break;
|
||||
}
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
public function queryMethods($builder)
|
||||
{
|
||||
$this->peerClassname = $builder->getStubPeerBuilder()->getClassname();
|
||||
$script = '';
|
||||
$this->addSetQueryKey($script);
|
||||
$this->addGetQueryKey($script);
|
||||
$this->addCacheContains($script);
|
||||
$this->addCacheFetch($script);
|
||||
$this->addCacheStore($script);
|
||||
$this->addGetSelectStatement($script);
|
||||
$this->addGetCountStatement($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addSetQueryKey(&$script)
|
||||
{
|
||||
$script .= "
|
||||
public function setQueryKey(\$key)
|
||||
{
|
||||
\$this->queryKey = \$key;
|
||||
return \$this;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addGetQueryKey(&$script)
|
||||
{
|
||||
$script .= "
|
||||
public function getQueryKey()
|
||||
{
|
||||
return \$this->queryKey;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addCacheContains(&$script)
|
||||
{
|
||||
$script .= "
|
||||
public function cacheContains(\$key)
|
||||
{";
|
||||
switch ($this->getParameter('backend')) {
|
||||
case 'apc':
|
||||
$script .= "
|
||||
return apc_fetch(\$key);";
|
||||
break;
|
||||
case 'array':
|
||||
$script .= "
|
||||
return isset(self::\$cacheBackend[\$key]);";
|
||||
break;
|
||||
case 'custom':
|
||||
default:
|
||||
$script .= "
|
||||
throw new PropelException('You must override the cacheContains(), cacheStore(), and cacheFetch() methods to enable query cache');";
|
||||
break;
|
||||
|
||||
}
|
||||
$script .= "
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addCacheStore(&$script)
|
||||
{
|
||||
$script .= "
|
||||
public function cacheStore(\$key, \$value, \$lifetime = " .$this->getParameter('lifetime') . ")
|
||||
{";
|
||||
switch ($this->getParameter('backend')) {
|
||||
case 'apc':
|
||||
$script .= "
|
||||
apc_store(\$key, \$value, \$lifetime);";
|
||||
break;
|
||||
case 'array':
|
||||
$script .= "
|
||||
self::\$cacheBackend[\$key] = \$value;";
|
||||
break;
|
||||
case 'custom':
|
||||
default:
|
||||
$script .= "
|
||||
throw new PropelException('You must override the cacheContains(), cacheStore(), and cacheFetch() methods to enable query cache');";
|
||||
break;
|
||||
}
|
||||
$script .= "
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addCacheFetch(&$script)
|
||||
{
|
||||
$script .= "
|
||||
public function cacheFetch(\$key)
|
||||
{";
|
||||
switch ($this->getParameter('backend')) {
|
||||
case 'apc':
|
||||
$script .= "
|
||||
return apc_fetch(\$key);";
|
||||
break;
|
||||
case 'array':
|
||||
$script .= "
|
||||
return isset(self::\$cacheBackend[\$key]) ? self::\$cacheBackend[\$key] : null;";
|
||||
break;
|
||||
case 'custom':
|
||||
default:
|
||||
$script .= "
|
||||
throw new PropelException('You must override the cacheContains(), cacheStore(), and cacheFetch() methods to enable query cache');";
|
||||
break;
|
||||
}
|
||||
$script .= "
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addGetSelectStatement(&$script)
|
||||
{
|
||||
$script .= "
|
||||
protected function getSelectStatement(\$con = null)
|
||||
{
|
||||
\$dbMap = Propel::getDatabaseMap(" . $this->peerClassname ."::DATABASE_NAME);
|
||||
\$db = Propel::getDB(" . $this->peerClassname ."::DATABASE_NAME);
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection(" . $this->peerClassname ."::DATABASE_NAME, Propel::CONNECTION_READ);
|
||||
}
|
||||
|
||||
if (!\$this->hasSelectClause()) {
|
||||
\$this->addSelfSelectColumns();
|
||||
}
|
||||
|
||||
\$con->beginTransaction();
|
||||
try {
|
||||
\$this->basePreSelect(\$con);
|
||||
\$key = \$this->getQueryKey();
|
||||
if (\$key && \$this->cacheContains(\$key)) {
|
||||
\$params = \$this->getParams();
|
||||
\$sql = \$this->cacheFetch(\$key);
|
||||
} else {
|
||||
\$params = array();
|
||||
\$sql = BasePeer::createSelectSql(\$this, \$params);
|
||||
if (\$key) {
|
||||
\$this->cacheStore(\$key, \$sql);
|
||||
}
|
||||
}
|
||||
\$stmt = \$con->prepare(\$sql);
|
||||
BasePeer::populateStmtValues(\$stmt, \$params, \$dbMap, \$db);
|
||||
\$stmt->execute();
|
||||
\$con->commit();
|
||||
} catch (PropelException \$e) {
|
||||
\$con->rollback();
|
||||
throw \$e;
|
||||
}
|
||||
|
||||
return \$stmt;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addGetCountStatement(&$script)
|
||||
{
|
||||
$script .= "
|
||||
protected function getCountStatement(\$con = null)
|
||||
{
|
||||
\$dbMap = Propel::getDatabaseMap(\$this->getDbName());
|
||||
\$db = Propel::getDB(\$this->getDbName());
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection(\$this->getDbName(), Propel::CONNECTION_READ);
|
||||
}
|
||||
|
||||
\$con->beginTransaction();
|
||||
try {
|
||||
\$this->basePreSelect(\$con);
|
||||
\$key = \$this->getQueryKey();
|
||||
if (\$key && \$this->cacheContains(\$key)) {
|
||||
\$params = \$this->getParams();
|
||||
\$sql = \$this->cacheFetch(\$key);
|
||||
} else {
|
||||
if (!\$this->hasSelectClause() && !\$this->getPrimaryCriteria()) {
|
||||
\$this->addSelfSelectColumns();
|
||||
}
|
||||
\$params = array();
|
||||
\$needsComplexCount = \$this->getGroupByColumns()
|
||||
|| \$this->getOffset()
|
||||
|| \$this->getLimit()
|
||||
|| \$this->getHaving()
|
||||
|| in_array(Criteria::DISTINCT, \$this->getSelectModifiers());
|
||||
if (\$needsComplexCount) {
|
||||
if (BasePeer::needsSelectAliases(\$this)) {
|
||||
if (\$this->getHaving()) {
|
||||
throw new PropelException('Propel cannot create a COUNT query when using HAVING and duplicate column names in the SELECT part');
|
||||
}
|
||||
BasePeer::turnSelectColumnsToAliases(\$this);
|
||||
}
|
||||
\$selectSql = BasePeer::createSelectSql(\$this, \$params);
|
||||
\$sql = 'SELECT COUNT(*) FROM (' . \$selectSql . ') propelmatch4cnt';
|
||||
} else {
|
||||
// Replace SELECT columns with COUNT(*)
|
||||
\$this->clearSelectColumns()->addSelectColumn('COUNT(*)');
|
||||
\$sql = BasePeer::createSelectSql(\$this, \$params);
|
||||
}
|
||||
if (\$key) {
|
||||
\$this->cacheStore(\$key, \$sql);
|
||||
}
|
||||
}
|
||||
\$stmt = \$con->prepare(\$sql);
|
||||
BasePeer::populateStmtValues(\$stmt, \$params, \$dbMap, \$db);
|
||||
\$stmt->execute();
|
||||
\$con->commit();
|
||||
} catch (PropelException \$e) {
|
||||
\$con->rollback();
|
||||
throw \$e;
|
||||
}
|
||||
|
||||
return \$stmt;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
}
|
|
@ -1,332 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Adds a slug column
|
||||
*
|
||||
* @author Francois Zaninotto
|
||||
* @author Massimiliano Arione
|
||||
* @version $Revision: 1629 $
|
||||
* @package propel.generator.behavior.sluggable
|
||||
*/
|
||||
class SluggableBehavior extends Behavior
|
||||
{
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'slug_column' => 'slug',
|
||||
'slug_pattern' => '',
|
||||
'replace_pattern' => '/\W+/', // Tip: use '/[^\\pL\\d]+/u' instead if you're in PHP5.3
|
||||
'replacement' => '-',
|
||||
'separator' => '-',
|
||||
'permanent' => 'false'
|
||||
);
|
||||
|
||||
/**
|
||||
* Add the slug_column to the current table
|
||||
*/
|
||||
public function modifyTable()
|
||||
{
|
||||
if(!$this->getTable()->containsColumn($this->getParameter('slug_column'))) {
|
||||
$this->getTable()->addColumn(array(
|
||||
'name' => $this->getParameter('slug_column'),
|
||||
'type' => 'VARCHAR',
|
||||
'size' => 255
|
||||
));
|
||||
// add a unique to column
|
||||
$unique = new Unique($this->getColumnForParameter('slug_column'));
|
||||
$unique->setName($this->getTable()->getName() . '_slug');
|
||||
$unique->addColumn($this->getTable()->getColumn($this->getParameter('slug_column')));
|
||||
$this->getTable()->addUnique($unique);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the getter of the column of the behavior
|
||||
*
|
||||
* @return string The related getter, e.g. 'getSlug'
|
||||
*/
|
||||
protected function getColumnGetter()
|
||||
{
|
||||
return 'get' . $this->getColumnForParameter('slug_column')->getPhpName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the setter of the column of the behavior
|
||||
*
|
||||
* @return string The related setter, e.g. 'setSlug'
|
||||
*/
|
||||
protected function getColumnSetter()
|
||||
{
|
||||
return 'set' . $this->getColumnForParameter('slug_column')->getPhpName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Add code in ObjectBuilder::preSave
|
||||
*
|
||||
* @return string The code to put at the hook
|
||||
*/
|
||||
public function preSave($builder)
|
||||
{
|
||||
$const = $builder->getColumnConstant($this->getColumnForParameter('slug_column'), $this->getTable()->getPhpName() . 'Peer');
|
||||
$script = "
|
||||
if (\$this->isColumnModified($const) && \$this->{$this->getColumnGetter()}()) {
|
||||
\$this->{$this->getColumnSetter()}(\$this->makeSlugUnique(\$this->{$this->getColumnGetter()}()));";
|
||||
if ($this->getParameter('permanent') == 'true') {
|
||||
$script .= "
|
||||
} elseif (!\$this->{$this->getColumnGetter()}()) {
|
||||
\$this->{$this->getColumnSetter()}(\$this->createSlug());
|
||||
}";
|
||||
} else {
|
||||
$script .= "
|
||||
} else {
|
||||
\$this->{$this->getColumnSetter()}(\$this->createSlug());
|
||||
}";
|
||||
}
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
public function objectMethods($builder)
|
||||
{
|
||||
$this->builder = $builder;
|
||||
$script = '';
|
||||
if ($this->getParameter('slug_column') != 'slug') {
|
||||
$this->addSlugSetter($script);
|
||||
$this->addSlugGetter($script);
|
||||
}
|
||||
$this->addCreateSlug($script);
|
||||
$this->addCreateRawSlug($script);
|
||||
$this->addCleanupSlugPart($script);
|
||||
$this->addLimitSlugSize($script);
|
||||
$this->addMakeSlugUnique($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addSlugSetter(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Wrap the setter for slug value
|
||||
*
|
||||
* @param string
|
||||
* @return " . $this->getTable()->getPhpName() . "
|
||||
*/
|
||||
public function setSlug(\$v)
|
||||
{
|
||||
return \$this->" . $this->getColumnSetter() . "(\$v);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addSlugGetter(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Wrap the getter for slug value
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getSlug()
|
||||
{
|
||||
return \$this->" . $this->getColumnGetter() . "();
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addCreateSlug(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Create a unique slug based on the object
|
||||
*
|
||||
* @return string The object slug
|
||||
*/
|
||||
protected function createSlug()
|
||||
{
|
||||
\$slug = \$this->createRawSlug();
|
||||
\$slug = \$this->limitSlugSize(\$slug);
|
||||
\$slug = \$this->makeSlugUnique(\$slug);
|
||||
|
||||
return \$slug;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addCreateRawSlug(&$script)
|
||||
{
|
||||
$pattern = $this->getParameter('slug_pattern');
|
||||
$script .= "
|
||||
/**
|
||||
* Create the slug from the appropriate columns
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function createRawSlug()
|
||||
{
|
||||
";
|
||||
if ($pattern) {
|
||||
$script .= "return '" . str_replace(array('{', '}'), array('\' . $this->cleanupSlugPart($this->get', '()) . \''), $pattern). "';";
|
||||
} else {
|
||||
$script .= "return \$this->cleanupSlugPart(\$this->__toString());";
|
||||
}
|
||||
$script .= "
|
||||
}
|
||||
";
|
||||
return $script;
|
||||
}
|
||||
|
||||
public function addCleanupSlugPart(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Cleanup a string to make a slug of it
|
||||
* Removes special characters, replaces blanks with a separator, and trim it
|
||||
*
|
||||
* @param string \$text the text to slugify
|
||||
* @param string \$separator the separator used by slug
|
||||
* @return string the slugified text
|
||||
*/
|
||||
protected static function cleanupSlugPart(\$slug, \$replacement = '" . $this->getParameter('replacement') . "')
|
||||
{
|
||||
// transliterate
|
||||
if (function_exists('iconv')) {
|
||||
\$slug = iconv('utf-8', 'us-ascii//TRANSLIT', \$slug);
|
||||
}
|
||||
|
||||
// lowercase
|
||||
if (function_exists('mb_strtolower')) {
|
||||
\$slug = mb_strtolower(\$slug);
|
||||
} else {
|
||||
\$slug = strtolower(\$slug);
|
||||
}
|
||||
|
||||
// remove accents resulting from OSX's iconv
|
||||
\$slug = str_replace(array('\'', '`', '^'), '', \$slug);
|
||||
|
||||
// replace non letter or digits with separator
|
||||
\$slug = preg_replace('" . $this->getParameter('replace_pattern') . "', \$replacement, \$slug);
|
||||
|
||||
// trim
|
||||
\$slug = trim(\$slug, \$replacement);
|
||||
|
||||
if (empty(\$slug)) {
|
||||
return 'n-a';
|
||||
}
|
||||
|
||||
return \$slug;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addLimitSlugSize(&$script)
|
||||
{
|
||||
$size = $this->getColumnForParameter('slug_column')->getSize();
|
||||
$script .= "
|
||||
|
||||
/**
|
||||
* Make sure the slug is short enough to accomodate the column size
|
||||
*
|
||||
* @param string \$slug the slug to check
|
||||
*
|
||||
* @return string the truncated slug
|
||||
*/
|
||||
protected static function limitSlugSize(\$slug, \$incrementReservedSpace = 3)
|
||||
{
|
||||
// check length, as suffix could put it over maximum
|
||||
if (strlen(\$slug) > ($size - \$incrementReservedSpace)) {
|
||||
\$slug = substr(\$slug, 0, $size - \$incrementReservedSpace);
|
||||
}
|
||||
return \$slug;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function addMakeSlugUnique(&$script)
|
||||
{
|
||||
$script .= "
|
||||
|
||||
/**
|
||||
* Get the slug, ensuring its uniqueness
|
||||
*
|
||||
* @param string \$slug the slug to check
|
||||
* @param string \$separator the separator used by slug
|
||||
* @return string the unique slug
|
||||
*/
|
||||
protected function makeSlugUnique(\$slug, \$separator = '" . $this->getParameter('separator') ."', \$increment = 0)
|
||||
{
|
||||
\$slug2 = empty(\$increment) ? \$slug : \$slug . \$separator . \$increment;
|
||||
\$slugAlreadyExists = " . $this->builder->getStubQueryBuilder()->getClassname() . "::create()
|
||||
->filterBySlug(\$slug2)
|
||||
->prune(\$this)";
|
||||
// watch out: some of the columns may be hidden by the soft_delete behavior
|
||||
if ($this->table->hasBehavior('soft_delete')) {
|
||||
$script .= "
|
||||
->includeDeleted()";
|
||||
}
|
||||
$script .= "
|
||||
->count();
|
||||
if (\$slugAlreadyExists) {
|
||||
return \$this->makeSlugUnique(\$slug, \$separator, ++\$increment);
|
||||
} else {
|
||||
return \$slug2;
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function queryMethods($builder)
|
||||
{
|
||||
$this->builder = $builder;
|
||||
$script = '';
|
||||
if ($this->getParameter('slug_column') != 'slug') {
|
||||
$this->addFilterBySlug($script);
|
||||
}
|
||||
$this->addFindOneBySlug($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addFilterBySlug(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Filter the query on the slug column
|
||||
*
|
||||
* @param string \$slug The value to use as filter.
|
||||
*
|
||||
* @return " . $this->builder->getStubQueryBuilder()->getClassname() . " The current query, for fluid interface
|
||||
*/
|
||||
public function filterBySlug(\$slug)
|
||||
{
|
||||
return \$this->addUsingAlias(" . $this->builder->getColumnConstant($this->getColumnForParameter('slug_column')) . ", \$slug, Criteria::EQUAL);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addFindOneBySlug(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Find one object based on its slug
|
||||
*
|
||||
* @param string \$slug The value to use as filter.
|
||||
* @param PropelPDO \$con The optional connection object
|
||||
*
|
||||
* @return " . $this->builder->getStubObjectBuilder()->getClassname() . " the result, formatted by the current formatter
|
||||
*/
|
||||
public function findOneBySlug(\$slug, \$con = null)
|
||||
{
|
||||
return \$this->filterBySlug(\$slug)->findOne(\$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
}
|
|
@ -1,83 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
require_once dirname(__FILE__) . '/SortableBehaviorObjectBuilderModifier.php';
|
||||
require_once dirname(__FILE__) . '/SortableBehaviorQueryBuilderModifier.php';
|
||||
require_once dirname(__FILE__) . '/SortableBehaviorPeerBuilderModifier.php';
|
||||
|
||||
/**
|
||||
* Gives a model class the ability to be ordered
|
||||
* Uses one additional column storing the rank
|
||||
*
|
||||
* @author Massimiliano Arione
|
||||
* @version $Revision: 1612 $
|
||||
* @package propel.generator.behavior.sortable
|
||||
*/
|
||||
class SortableBehavior extends Behavior
|
||||
{
|
||||
// default parameters value
|
||||
protected $parameters = array(
|
||||
'rank_column' => 'sortable_rank',
|
||||
'use_scope' => 'false',
|
||||
'scope_column' => 'sortable_scope',
|
||||
);
|
||||
|
||||
protected $objectBuilderModifier, $queryBuilderModifier, $peerBuilderModifier;
|
||||
|
||||
/**
|
||||
* Add the rank_column to the current table
|
||||
*/
|
||||
public function modifyTable()
|
||||
{
|
||||
if (!$this->getTable()->containsColumn($this->getParameter('rank_column'))) {
|
||||
$this->getTable()->addColumn(array(
|
||||
'name' => $this->getParameter('rank_column'),
|
||||
'type' => 'INTEGER'
|
||||
));
|
||||
}
|
||||
if ($this->getParameter('use_scope') == 'true' &&
|
||||
!$this->getTable()->containsColumn($this->getParameter('scope_column'))) {
|
||||
$this->getTable()->addColumn(array(
|
||||
'name' => $this->getParameter('scope_column'),
|
||||
'type' => 'INTEGER'
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
public function getObjectBuilderModifier()
|
||||
{
|
||||
if (is_null($this->objectBuilderModifier)) {
|
||||
$this->objectBuilderModifier = new SortableBehaviorObjectBuilderModifier($this);
|
||||
}
|
||||
return $this->objectBuilderModifier;
|
||||
}
|
||||
|
||||
public function getQueryBuilderModifier()
|
||||
{
|
||||
if (is_null($this->queryBuilderModifier)) {
|
||||
$this->queryBuilderModifier = new SortableBehaviorQueryBuilderModifier($this);
|
||||
}
|
||||
return $this->queryBuilderModifier;
|
||||
}
|
||||
|
||||
public function getPeerBuilderModifier()
|
||||
{
|
||||
if (is_null($this->peerBuilderModifier)) {
|
||||
$this->peerBuilderModifier = new SortableBehaviorPeerBuilderModifier($this);
|
||||
}
|
||||
return $this->peerBuilderModifier;
|
||||
}
|
||||
|
||||
public function useScope()
|
||||
{
|
||||
return $this->getParameter('use_scope') == 'true';
|
||||
}
|
||||
|
||||
}
|
|
@ -1,636 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Behavior to add sortable columns and abilities
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @author heltem <heltem@o2php.com>
|
||||
* @package propel.generator.behavior.sortable
|
||||
*/
|
||||
class SortableBehaviorObjectBuilderModifier
|
||||
{
|
||||
protected $behavior, $table, $builder, $objectClassname, $peerClassname;
|
||||
|
||||
public function __construct($behavior)
|
||||
{
|
||||
$this->behavior = $behavior;
|
||||
$this->table = $behavior->getTable();
|
||||
}
|
||||
|
||||
protected function getParameter($key)
|
||||
{
|
||||
return $this->behavior->getParameter($key);
|
||||
}
|
||||
|
||||
protected function getColumnAttribute($name)
|
||||
{
|
||||
return strtolower($this->behavior->getColumnForParameter($name)->getName());
|
||||
}
|
||||
|
||||
protected function getColumnPhpName($name)
|
||||
{
|
||||
return $this->behavior->getColumnForParameter($name)->getPhpName();
|
||||
}
|
||||
|
||||
protected function setBuilder($builder)
|
||||
{
|
||||
$this->builder = $builder;
|
||||
$this->objectClassname = $builder->getStubObjectBuilder()->getClassname();
|
||||
$this->queryClassname = $builder->getStubQueryBuilder()->getClassname();
|
||||
$this->peerClassname = $builder->getStubPeerBuilder()->getClassname();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the getter of the column of the behavior
|
||||
*
|
||||
* @return string The related getter, e.g. 'getRank'
|
||||
*/
|
||||
protected function getColumnGetter($columnName = 'rank_column')
|
||||
{
|
||||
return 'get' . $this->behavior->getColumnForParameter($columnName)->getPhpName();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the setter of the column of the behavior
|
||||
*
|
||||
* @return string The related setter, e.g. 'setRank'
|
||||
*/
|
||||
protected function getColumnSetter($columnName = 'rank_column')
|
||||
{
|
||||
return 'set' . $this->behavior->getColumnForParameter($columnName)->getPhpName();
|
||||
}
|
||||
|
||||
public function preSave($builder)
|
||||
{
|
||||
return "\$this->processSortableQueries(\$con);";
|
||||
}
|
||||
|
||||
public function preInsert($builder)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$this->setBuilder($builder);
|
||||
return "if (!\$this->isColumnModified({$this->peerClassname}::RANK_COL)) {
|
||||
\$this->{$this->getColumnSetter()}({$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con) + 1);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
public function preDelete($builder)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$this->setBuilder($builder);
|
||||
return "
|
||||
{$this->peerClassname}::shiftRank(-1, \$this->{$this->getColumnGetter()}() + 1, null, " . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con);
|
||||
{$this->peerClassname}::clearInstancePool();
|
||||
";
|
||||
}
|
||||
|
||||
public function objectAttributes($builder)
|
||||
{
|
||||
return "
|
||||
/**
|
||||
* Queries to be executed in the save transaction
|
||||
* @var array
|
||||
*/
|
||||
protected \$sortableQueries = array();
|
||||
";
|
||||
}
|
||||
|
||||
public function objectMethods($builder)
|
||||
{
|
||||
$this->setBuilder($builder);
|
||||
$script = '';
|
||||
if ($this->getParameter('rank_column') != 'rank') {
|
||||
$this->addRankAccessors($script);
|
||||
}
|
||||
if ($this->behavior->useScope() &&
|
||||
$this->getParameter('scope_column') != 'scope_value') {
|
||||
$this->addScopeAccessors($script);
|
||||
}
|
||||
$this->addIsFirst($script);
|
||||
$this->addIsLast($script);
|
||||
$this->addGetNext($script);
|
||||
$this->addGetPrevious($script);
|
||||
$this->addInsertAtRank($script);
|
||||
$this->addInsertAtBottom($script);
|
||||
$this->addInsertAtTop($script);
|
||||
$this->addMoveToRank($script);
|
||||
$this->addSwapWith($script);
|
||||
$this->addMoveUp($script);
|
||||
$this->addMoveDown($script);
|
||||
$this->addMoveToTop($script);
|
||||
$this->addMoveToBottom($script);
|
||||
$this->addRemoveFromList($script);
|
||||
$this->addProcessSortableQueries($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the wraps for getter/setter, if the rank column has not the default name
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function addRankAccessors(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Wrap the getter for rank value
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getRank()
|
||||
{
|
||||
return \$this->{$this->getColumnAttribute('rank_column')};
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap the setter for rank value
|
||||
*
|
||||
* @param int
|
||||
* @return {$this->objectClassname}
|
||||
*/
|
||||
public function setRank(\$v)
|
||||
{
|
||||
return \$this->{$this->getColumnSetter()}(\$v);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the wraps for getter/setter, if the scope column has not the default name
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected function addScopeAccessors(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Wrap the getter for scope value
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function getScopeValue()
|
||||
{
|
||||
return \$this->{$this->getColumnAttribute('scope_column')};
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap the setter for scope value
|
||||
*
|
||||
* @param int
|
||||
* @return {$this->objectClassname}
|
||||
*/
|
||||
public function setScopeValue(\$v)
|
||||
{
|
||||
return \$this->{$this->getColumnSetter('scope_column')}(\$v);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addIsFirst(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Check if the object is first in the list, i.e. if it has 1 for rank
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function isFirst()
|
||||
{
|
||||
return \$this->{$this->getColumnGetter()}() == 1;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addIsLast(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Check if the object is last in the list, i.e. if its rank is the highest rank
|
||||
*
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return boolean
|
||||
*/
|
||||
public function isLast(PropelPDO \$con = null)
|
||||
{
|
||||
return \$this->{$this->getColumnGetter()}() == {$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addGetNext(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Get the next item in the list, i.e. the one for which rank is immediately higher
|
||||
*
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return {$this->objectClassname}
|
||||
*/
|
||||
public function getNext(PropelPDO \$con = null)
|
||||
{";
|
||||
if ($this->behavior->getParameter('rank_column') == 'rank' && $useScope) {
|
||||
$script .= "
|
||||
return {$this->queryClassname}::create()
|
||||
->filterByRank(\$this->{$this->getColumnGetter()}() + 1)
|
||||
->inList(\$this->{$this->getColumnGetter('scope_column')}())
|
||||
->findOne(\$con);";
|
||||
} else {
|
||||
$script .= "
|
||||
return {$this->queryClassname}::create()->findOneByRank(\$this->{$this->getColumnGetter()}() + 1, " . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con);";
|
||||
}
|
||||
|
||||
$script .= "
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addGetPrevious(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Get the previous item in the list, i.e. the one for which rank is immediately lower
|
||||
*
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return {$this->objectClassname}
|
||||
*/
|
||||
public function getPrevious(PropelPDO \$con = null)
|
||||
{";
|
||||
if ($this->behavior->getParameter('rank_column') == 'rank' && $useScope) {
|
||||
$script .= "
|
||||
return {$this->queryClassname}::create()
|
||||
->filterByRank(\$this->{$this->getColumnGetter()}() - 1)
|
||||
->inList(\$this->{$this->getColumnGetter('scope_column')}())
|
||||
->findOne(\$con);";
|
||||
} else {
|
||||
$script .= "
|
||||
return {$this->queryClassname}::create()->findOneByRank(\$this->{$this->getColumnGetter()}() - 1, " . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con);";
|
||||
}
|
||||
$script .= "
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addInsertAtRank(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Insert at specified rank
|
||||
* The modifications are not persisted until the object is saved.
|
||||
*
|
||||
* @param integer \$rank rank value
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return {$this->objectClassname} the current object
|
||||
*
|
||||
* @throws PropelException
|
||||
*/
|
||||
public function insertAtRank(\$rank, PropelPDO \$con = null)
|
||||
{";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
if (null === \$this->{$this->getColumnGetter('scope_column')}()) {
|
||||
throw new PropelException('The scope must be defined before inserting an object in a suite');
|
||||
}";
|
||||
}
|
||||
$script .= "
|
||||
\$maxRank = {$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con);
|
||||
if (\$rank < 1 || \$rank > \$maxRank + 1) {
|
||||
throw new PropelException('Invalid rank ' . \$rank);
|
||||
}
|
||||
// move the object in the list, at the given rank
|
||||
\$this->{$this->getColumnSetter()}(\$rank);
|
||||
if (\$rank != \$maxRank + 1) {
|
||||
// Keep the list modification query for the save() transaction
|
||||
\$this->sortableQueries []= array(
|
||||
'callable' => array('$peerClassname', 'shiftRank'),
|
||||
'arguments' => array(1, \$rank, null, " . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}()" : '') . ")
|
||||
);
|
||||
}
|
||||
|
||||
return \$this;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addInsertAtBottom(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Insert in the last rank
|
||||
* The modifications are not persisted until the object is saved.
|
||||
*
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return {$this->objectClassname} the current object
|
||||
*
|
||||
* @throws PropelException
|
||||
*/
|
||||
public function insertAtBottom(PropelPDO \$con = null)
|
||||
{";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
if (null === \$this->{$this->getColumnGetter('scope_column')}()) {
|
||||
throw new PropelException('The scope must be defined before inserting an object in a suite');
|
||||
}";
|
||||
}
|
||||
$script .= "
|
||||
\$this->{$this->getColumnSetter()}({$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con) + 1);
|
||||
|
||||
return \$this;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addInsertAtTop(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Insert in the first rank
|
||||
* The modifications are not persisted until the object is saved.
|
||||
*
|
||||
* @return {$this->objectClassname} the current object
|
||||
*/
|
||||
public function insertAtTop()
|
||||
{
|
||||
return \$this->insertAtRank(1);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addMoveToRank(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Move the object to a new rank, and shifts the rank
|
||||
* Of the objects inbetween the old and new rank accordingly
|
||||
*
|
||||
* @param integer \$newRank rank value
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return {$this->objectClassname} the current object
|
||||
*
|
||||
* @throws PropelException
|
||||
*/
|
||||
public function moveToRank(\$newRank, PropelPDO \$con = null)
|
||||
{
|
||||
if (\$this->isNew()) {
|
||||
throw new PropelException('New objects cannot be moved. Please use insertAtRank() instead');
|
||||
}
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection($peerClassname::DATABASE_NAME);
|
||||
}
|
||||
if (\$newRank < 1 || \$newRank > {$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con)) {
|
||||
throw new PropelException('Invalid rank ' . \$newRank);
|
||||
}
|
||||
|
||||
\$oldRank = \$this->{$this->getColumnGetter()}();
|
||||
if (\$oldRank == \$newRank) {
|
||||
return \$this;
|
||||
}
|
||||
|
||||
\$con->beginTransaction();
|
||||
try {
|
||||
// shift the objects between the old and the new rank
|
||||
\$delta = (\$oldRank < \$newRank) ? -1 : 1;
|
||||
$peerClassname::shiftRank(\$delta, min(\$oldRank, \$newRank), max(\$oldRank, \$newRank), " . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con);
|
||||
|
||||
// move the object to its new rank
|
||||
\$this->{$this->getColumnSetter()}(\$newRank);
|
||||
\$this->save(\$con);
|
||||
|
||||
\$con->commit();
|
||||
return \$this;
|
||||
} catch (Exception \$e) {
|
||||
\$con->rollback();
|
||||
throw \$e;
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addSwapWith(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Exchange the rank of the object with the one passed as argument, and saves both objects
|
||||
*
|
||||
* @param {$this->objectClassname} \$object
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return {$this->objectClassname} the current object
|
||||
*
|
||||
* @throws Exception if the database cannot execute the two updates
|
||||
*/
|
||||
public function swapWith(\$object, PropelPDO \$con = null)
|
||||
{
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME);
|
||||
}
|
||||
\$con->beginTransaction();
|
||||
try {
|
||||
\$oldRank = \$this->{$this->getColumnGetter()}();
|
||||
\$newRank = \$object->{$this->getColumnGetter()}();
|
||||
\$this->{$this->getColumnSetter()}(\$newRank);
|
||||
\$this->save(\$con);
|
||||
\$object->{$this->getColumnSetter()}(\$oldRank);
|
||||
\$object->save(\$con);
|
||||
\$con->commit();
|
||||
|
||||
return \$this;
|
||||
} catch (Exception \$e) {
|
||||
\$con->rollback();
|
||||
throw \$e;
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addMoveUp(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Move the object higher in the list, i.e. exchanges its rank with the one of the previous object
|
||||
*
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return {$this->objectClassname} the current object
|
||||
*/
|
||||
public function moveUp(PropelPDO \$con = null)
|
||||
{
|
||||
if (\$this->isFirst()) {
|
||||
return \$this;
|
||||
}
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME);
|
||||
}
|
||||
\$con->beginTransaction();
|
||||
try {
|
||||
\$prev = \$this->getPrevious(\$con);
|
||||
\$this->swapWith(\$prev, \$con);
|
||||
\$con->commit();
|
||||
|
||||
return \$this;
|
||||
} catch (Exception \$e) {
|
||||
\$con->rollback();
|
||||
throw \$e;
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addMoveDown(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Move the object higher in the list, i.e. exchanges its rank with the one of the next object
|
||||
*
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return {$this->objectClassname} the current object
|
||||
*/
|
||||
public function moveDown(PropelPDO \$con = null)
|
||||
{
|
||||
if (\$this->isLast(\$con)) {
|
||||
return \$this;
|
||||
}
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME);
|
||||
}
|
||||
\$con->beginTransaction();
|
||||
try {
|
||||
\$next = \$this->getNext(\$con);
|
||||
\$this->swapWith(\$next, \$con);
|
||||
\$con->commit();
|
||||
|
||||
return \$this;
|
||||
} catch (Exception \$e) {
|
||||
\$con->rollback();
|
||||
throw \$e;
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addMoveToTop(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Move the object to the top of the list
|
||||
*
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return {$this->objectClassname} the current object
|
||||
*/
|
||||
public function moveToTop(PropelPDO \$con = null)
|
||||
{
|
||||
if (\$this->isFirst()) {
|
||||
return \$this;
|
||||
}
|
||||
return \$this->moveToRank(1, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addMoveToBottom(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Move the object to the bottom of the list
|
||||
*
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return integer the old object's rank
|
||||
*/
|
||||
public function moveToBottom(PropelPDO \$con = null)
|
||||
{
|
||||
if (\$this->isLast(\$con)) {
|
||||
return false;
|
||||
}
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME);
|
||||
}
|
||||
\$con->beginTransaction();
|
||||
try {
|
||||
\$bottom = {$this->queryClassname}::create()->getMaxRank(" . ($useScope ? "\$this->{$this->getColumnGetter('scope_column')}(), " : '') . "\$con);
|
||||
\$res = \$this->moveToRank(\$bottom, \$con);
|
||||
\$con->commit();
|
||||
|
||||
return \$res;
|
||||
} catch (Exception \$e) {
|
||||
\$con->rollback();
|
||||
throw \$e;
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addRemoveFromList(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Removes the current object from the list.
|
||||
* The modifications are not persisted until the object is saved.
|
||||
*
|
||||
* @return {$this->objectClassname} the current object
|
||||
*/
|
||||
public function removeFromList()
|
||||
{
|
||||
// Keep the list modification query for the save() transaction
|
||||
\$this->sortableQueries []= array(
|
||||
'callable' => array('$peerClassname', 'shiftRank'),
|
||||
'arguments' => array(-1, \$this->{$this->getColumnGetter()}() + 1, null" . ($useScope ? ", \$this->{$this->getColumnGetter('scope_column')}()" : '') . ")
|
||||
);
|
||||
// remove the object from the list
|
||||
\$this->{$this->getColumnSetter('rank_column')}(null);";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
\$this->{$this->getColumnSetter('scope_column')}(null);";
|
||||
}
|
||||
$script .= "
|
||||
|
||||
return \$this;
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addProcessSortableQueries(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Execute queries that were saved to be run inside the save transaction
|
||||
*/
|
||||
protected function processSortableQueries(\$con)
|
||||
{
|
||||
foreach (\$this->sortableQueries as \$query) {
|
||||
\$query['arguments'][]= \$con;
|
||||
call_user_func_array(\$query['callable'], \$query['arguments']);
|
||||
}
|
||||
\$this->sortableQueries = array();
|
||||
}
|
||||
";
|
||||
}
|
||||
}
|
|
@ -1,367 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Behavior to add sortable peer methods
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @author heltem <heltem@o2php.com>
|
||||
* @package propel.generator.behavior.sortable
|
||||
*/
|
||||
class SortableBehaviorPeerBuilderModifier
|
||||
{
|
||||
protected $behavior, $table, $builder, $objectClassname, $peerClassname;
|
||||
|
||||
public function __construct($behavior)
|
||||
{
|
||||
$this->behavior = $behavior;
|
||||
$this->table = $behavior->getTable();
|
||||
}
|
||||
|
||||
protected function getParameter($key)
|
||||
{
|
||||
return $this->behavior->getParameter($key);
|
||||
}
|
||||
|
||||
protected function getColumnAttribute($name)
|
||||
{
|
||||
return strtolower($this->behavior->getColumnForParameter($name)->getName());
|
||||
}
|
||||
|
||||
protected function getColumnConstant($name)
|
||||
{
|
||||
return strtoupper($this->behavior->getColumnForParameter($name)->getName());
|
||||
}
|
||||
|
||||
protected function getColumnPhpName($name)
|
||||
{
|
||||
return $this->behavior->getColumnForParameter($name)->getPhpName();
|
||||
}
|
||||
|
||||
protected function setBuilder($builder)
|
||||
{
|
||||
$this->builder = $builder;
|
||||
$this->objectClassname = $builder->getStubObjectBuilder()->getClassname();
|
||||
$this->peerClassname = $builder->getStubPeerBuilder()->getClassname();
|
||||
}
|
||||
|
||||
public function staticAttributes($builder)
|
||||
{
|
||||
$tableName = $this->table->getName();
|
||||
$script = "
|
||||
/**
|
||||
* rank column
|
||||
*/
|
||||
const RANK_COL = '" . $tableName . '.' . $this->getColumnConstant('rank_column') . "';
|
||||
";
|
||||
|
||||
if ($this->behavior->useScope()) {
|
||||
$script .= "
|
||||
/**
|
||||
* Scope column for the set
|
||||
*/
|
||||
const SCOPE_COL = '" . $tableName . '.' . $this->getColumnConstant('scope_column') . "';
|
||||
";
|
||||
}
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
/**
|
||||
* Static methods
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function staticMethods($builder)
|
||||
{
|
||||
$this->setBuilder($builder);
|
||||
$script = '';
|
||||
|
||||
$this->addGetMaxRank($script);
|
||||
$this->addRetrieveByRank($script);
|
||||
$this->addReorder($script);
|
||||
$this->addDoSelectOrderByRank($script);
|
||||
if ($this->behavior->useScope()) {
|
||||
$this->addRetrieveList($script);
|
||||
$this->addCountList($script);
|
||||
$this->addDeleteList($script);
|
||||
}
|
||||
$this->addShiftRank($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addGetMaxRank(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Get the highest rank
|
||||
* ";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to determine which suite to consider";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO optional connection
|
||||
*
|
||||
* @return integer highest position
|
||||
*/
|
||||
public static function getMaxRank(" . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null)
|
||||
{
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME);
|
||||
}
|
||||
// shift the objects with a position lower than the one of object
|
||||
\$c = new Criteria();
|
||||
\$c->addSelectColumn('MAX(' . {$this->peerClassname}::RANK_COL . ')');";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
\$c->add({$this->peerClassname}::SCOPE_COL, \$scope, Criteria::EQUAL);";
|
||||
}
|
||||
$script .= "
|
||||
\$stmt = {$this->peerClassname}::doSelectStmt(\$c, \$con);
|
||||
|
||||
return \$stmt->fetchColumn();
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addRetrieveByRank(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Get an item from the list based on its rank
|
||||
*
|
||||
* @param integer \$rank rank";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to determine which suite to consider";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return {$this->objectClassname}
|
||||
*/
|
||||
public static function retrieveByRank(\$rank, " . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null)
|
||||
{
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection($peerClassname::DATABASE_NAME);
|
||||
}
|
||||
|
||||
\$c = new Criteria;
|
||||
\$c->add($peerClassname::RANK_COL, \$rank);";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
\$c->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);";
|
||||
}
|
||||
$script .= "
|
||||
|
||||
return $peerClassname::doSelectOne(\$c, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addReorder(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$columnGetter = 'get' . $this->behavior->getColumnForParameter('rank_column')->getPhpName();
|
||||
$columnSetter = 'set' . $this->behavior->getColumnForParameter('rank_column')->getPhpName();
|
||||
$script .= "
|
||||
/**
|
||||
* Reorder a set of sortable objects based on a list of id/position
|
||||
* Beware that there is no check made on the positions passed
|
||||
* So incoherent positions will result in an incoherent list
|
||||
*
|
||||
* @param array \$order id => rank pairs
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return boolean true if the reordering took place, false if a database problem prevented it
|
||||
*/
|
||||
public static function reorder(array \$order, PropelPDO \$con = null)
|
||||
{
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection($peerClassname::DATABASE_NAME);
|
||||
}
|
||||
|
||||
\$con->beginTransaction();
|
||||
try {
|
||||
\$ids = array_keys(\$order);
|
||||
\$objects = $peerClassname::retrieveByPKs(\$ids);
|
||||
foreach (\$objects as \$object) {
|
||||
\$pk = \$object->getPrimaryKey();
|
||||
if (\$object->$columnGetter() != \$order[\$pk]) {
|
||||
\$object->$columnSetter(\$order[\$pk]);
|
||||
\$object->save(\$con);
|
||||
}
|
||||
}
|
||||
\$con->commit();
|
||||
|
||||
return true;
|
||||
} catch (PropelException \$e) {
|
||||
\$con->rollback();
|
||||
throw \$e;
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addDoSelectOrderByRank(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Return an array of sortable objects ordered by position
|
||||
*
|
||||
* @param Criteria \$criteria optional criteria object
|
||||
* @param string \$order sorting order, to be chosen between Criteria::ASC (default) and Criteria::DESC
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return array list of sortable objects
|
||||
*/
|
||||
public static function doSelectOrderByRank(Criteria \$criteria = null, \$order = Criteria::ASC, PropelPDO \$con = null)
|
||||
{
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection($peerClassname::DATABASE_NAME);
|
||||
}
|
||||
|
||||
if (\$criteria === null) {
|
||||
\$criteria = new Criteria();
|
||||
} elseif (\$criteria instanceof Criteria) {
|
||||
\$criteria = clone \$criteria;
|
||||
}
|
||||
|
||||
\$criteria->clearOrderByColumns();
|
||||
|
||||
if (\$order == Criteria::ASC) {
|
||||
\$criteria->addAscendingOrderByColumn($peerClassname::RANK_COL);
|
||||
} else {
|
||||
\$criteria->addDescendingOrderByColumn($peerClassname::RANK_COL);
|
||||
}
|
||||
|
||||
return $peerClassname::doSelect(\$criteria, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addRetrieveList(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Return an array of sortable objects in the given scope ordered by position
|
||||
*
|
||||
* @param int \$scope the scope of the list
|
||||
* @param string \$order sorting order, to be chosen between Criteria::ASC (default) and Criteria::DESC
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return array list of sortable objects
|
||||
*/
|
||||
public static function retrieveList(\$scope, \$order = Criteria::ASC, PropelPDO \$con = null)
|
||||
{
|
||||
\$c = new Criteria();
|
||||
\$c->add($peerClassname::SCOPE_COL, \$scope);
|
||||
|
||||
return $peerClassname::doSelectOrderByRank(\$c, \$order, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addCountList(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Return the number of sortable objects in the given scope
|
||||
*
|
||||
* @param int \$scope the scope of the list
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return array list of sortable objects
|
||||
*/
|
||||
public static function countList(\$scope, PropelPDO \$con = null)
|
||||
{
|
||||
\$c = new Criteria();
|
||||
\$c->add($peerClassname::SCOPE_COL, \$scope);
|
||||
|
||||
return $peerClassname::doCount(\$c, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addDeleteList(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Deletes the sortable objects in the given scope
|
||||
*
|
||||
* @param int \$scope the scope of the list
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return int number of deleted objects
|
||||
*/
|
||||
public static function deleteList(\$scope, PropelPDO \$con = null)
|
||||
{
|
||||
\$c = new Criteria();
|
||||
\$c->add($peerClassname::SCOPE_COL, \$scope);
|
||||
|
||||
return $peerClassname::doDelete(\$c, \$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
protected function addShiftRank(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Adds \$delta to all Rank values that are >= \$first and <= \$last.
|
||||
* '\$delta' can also be negative.
|
||||
*
|
||||
* @param int \$delta Value to be shifted by, can be negative
|
||||
* @param int \$first First node to be shifted
|
||||
* @param int \$last Last node to be shifted";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to use for the shift";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
*/
|
||||
public static function shiftRank(\$delta, \$first, \$last = null, " . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null)
|
||||
{
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection($peerClassname::DATABASE_NAME, Propel::CONNECTION_WRITE);
|
||||
}
|
||||
|
||||
\$whereCriteria = new Criteria($peerClassname::DATABASE_NAME);
|
||||
\$criterion = \$whereCriteria->getNewCriterion($peerClassname::RANK_COL, \$first, Criteria::GREATER_EQUAL);
|
||||
if (null !== \$last) {
|
||||
\$criterion->addAnd(\$whereCriteria->getNewCriterion($peerClassname::RANK_COL, \$last, Criteria::LESS_EQUAL));
|
||||
}
|
||||
\$whereCriteria->add(\$criterion);";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
\$whereCriteria->add($peerClassname::SCOPE_COL, \$scope, Criteria::EQUAL);";
|
||||
}
|
||||
$script .= "
|
||||
|
||||
\$valuesCriteria = new Criteria($peerClassname::DATABASE_NAME);
|
||||
\$valuesCriteria->add($peerClassname::RANK_COL, array('raw' => $peerClassname::RANK_COL . ' + ?', 'value' => \$delta), Criteria::CUSTOM_EQUAL);
|
||||
|
||||
{$this->builder->getPeerBuilder()->getBasePeerClassname()}::doUpdate(\$whereCriteria, \$valuesCriteria, \$con);
|
||||
$peerClassname::clearInstancePool();
|
||||
}
|
||||
";
|
||||
}
|
||||
}
|
|
@ -1,283 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Behavior to add sortable query methods
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @package propel.generator.behavior.sortable
|
||||
*/
|
||||
class SortableBehaviorQueryBuilderModifier
|
||||
{
|
||||
protected $behavior, $table, $builder, $objectClassname, $peerClassname;
|
||||
|
||||
public function __construct($behavior)
|
||||
{
|
||||
$this->behavior = $behavior;
|
||||
$this->table = $behavior->getTable();
|
||||
}
|
||||
|
||||
protected function getParameter($key)
|
||||
{
|
||||
return $this->behavior->getParameter($key);
|
||||
}
|
||||
|
||||
protected function getColumn($name)
|
||||
{
|
||||
return $this->behavior->getColumnForParameter($name);
|
||||
}
|
||||
|
||||
protected function setBuilder($builder)
|
||||
{
|
||||
$this->builder = $builder;
|
||||
$this->objectClassname = $builder->getStubObjectBuilder()->getClassname();
|
||||
$this->queryClassname = $builder->getStubQueryBuilder()->getClassname();
|
||||
$this->peerClassname = $builder->getStubPeerBuilder()->getClassname();
|
||||
}
|
||||
|
||||
public function queryMethods($builder)
|
||||
{
|
||||
$this->setBuilder($builder);
|
||||
$script = '';
|
||||
|
||||
// select filters
|
||||
if ($this->behavior->useScope()) {
|
||||
$this->addInList($script);
|
||||
}
|
||||
if ($this->getParameter('rank_column') != 'rank') {
|
||||
$this->addFilterByRank($script);
|
||||
$this->addOrderByRank($script);
|
||||
}
|
||||
|
||||
// select termination methods
|
||||
if ($this->getParameter('rank_column') != 'rank') {
|
||||
$this->addFindOneByRank($script);
|
||||
}
|
||||
$this->addFindList($script);
|
||||
|
||||
// utilities
|
||||
$this->addGetMaxRank($script);
|
||||
$this->addReorder($script);
|
||||
|
||||
return $script;
|
||||
}
|
||||
|
||||
protected function addInList(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Returns the objects in a certain list, from the list scope
|
||||
*
|
||||
* @param int \$scope Scope to determine which objects node to return
|
||||
*
|
||||
* @return {$this->queryClassname} The current query, for fuid interface
|
||||
*/
|
||||
public function inList(\$scope = null)
|
||||
{
|
||||
return \$this->addUsingAlias({$this->peerClassname}::SCOPE_COL, \$scope, Criteria::EQUAL);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addFilterByRank(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Filter the query based on a rank in the list
|
||||
*
|
||||
* @param integer \$rank rank";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to determine which suite to consider";
|
||||
}
|
||||
$script .= "
|
||||
*
|
||||
* @return " . $this->queryClassname . " The current query, for fluid interface
|
||||
*/
|
||||
public function filterByRank(\$rank" . ($useScope ? ", \$scope = null" : "") . ")
|
||||
{
|
||||
return \$this";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
->inList(\$scope)";
|
||||
}
|
||||
$script .= "
|
||||
->addUsingAlias($peerClassname::RANK_COL, \$rank, Criteria::EQUAL);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addOrderByRank(&$script)
|
||||
{
|
||||
$script .= "
|
||||
/**
|
||||
* Order the query based on the rank in the list.
|
||||
* Using the default \$order, returns the item with the lowest rank first
|
||||
*
|
||||
* @param string \$order either Criteria::ASC (default) or Criteria::DESC
|
||||
*
|
||||
* @return " . $this->queryClassname . " The current query, for fluid interface
|
||||
*/
|
||||
public function orderByRank(\$order = Criteria::ASC)
|
||||
{
|
||||
\$order = strtoupper(\$order);
|
||||
switch (\$order) {
|
||||
case Criteria::ASC:
|
||||
return \$this->addAscendingOrderByColumn(\$this->getAliasedColName(" . $this->peerClassname . "::RANK_COL));
|
||||
break;
|
||||
case Criteria::DESC:
|
||||
return \$this->addDescendingOrderByColumn(\$this->getAliasedColName(" . $this->peerClassname . "::RANK_COL));
|
||||
break;
|
||||
default:
|
||||
throw new PropelException('" . $this->queryClassname . "::orderBy() only accepts \"asc\" or \"desc\" as argument');
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addFindOneByRank(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$peerClassname = $this->peerClassname;
|
||||
$script .= "
|
||||
/**
|
||||
* Get an item from the list based on its rank
|
||||
*
|
||||
* @param integer \$rank rank";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to determine which suite to consider";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return {$this->objectClassname}
|
||||
*/
|
||||
public function findOneByRank(\$rank, " . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null)
|
||||
{
|
||||
return \$this
|
||||
->filterByRank(\$rank" . ($useScope ? ", \$scope" : "") . ")
|
||||
->findOne(\$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addFindList(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Returns " . ($useScope ? 'a' : 'the') ." list of objects
|
||||
*";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to determine which list to return";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO \$con Connection to use.
|
||||
*
|
||||
* @return mixed the list of results, formatted by the current formatter
|
||||
*/
|
||||
public function findList(" . ($useScope ? "\$scope = null, " : "") . "\$con = null)
|
||||
{
|
||||
return \$this";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
->inList(\$scope)";
|
||||
}
|
||||
$script .= "
|
||||
->orderByRank()
|
||||
->find(\$con);
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addGetMaxRank(&$script)
|
||||
{
|
||||
$useScope = $this->behavior->useScope();
|
||||
$script .= "
|
||||
/**
|
||||
* Get the highest rank
|
||||
* ";
|
||||
if($useScope) {
|
||||
$script .= "
|
||||
* @param int \$scope Scope to determine which suite to consider";
|
||||
}
|
||||
$script .= "
|
||||
* @param PropelPDO optional connection
|
||||
*
|
||||
* @return integer highest position
|
||||
*/
|
||||
public function getMaxRank(" . ($useScope ? "\$scope = null, " : "") . "PropelPDO \$con = null)
|
||||
{
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection({$this->peerClassname}::DATABASE_NAME);
|
||||
}
|
||||
// shift the objects with a position lower than the one of object
|
||||
\$this->addSelectColumn('MAX(' . {$this->peerClassname}::RANK_COL . ')');";
|
||||
if ($useScope) {
|
||||
$script .= "
|
||||
\$this->add({$this->peerClassname}::SCOPE_COL, \$scope, Criteria::EQUAL);";
|
||||
}
|
||||
$script .= "
|
||||
\$stmt = \$this->getSelectStatement(\$con);
|
||||
|
||||
return \$stmt->fetchColumn();
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
protected function addReorder(&$script)
|
||||
{
|
||||
$peerClassname = $this->peerClassname;
|
||||
$columnGetter = 'get' . $this->behavior->getColumnForParameter('rank_column')->getPhpName();
|
||||
$columnSetter = 'set' . $this->behavior->getColumnForParameter('rank_column')->getPhpName();
|
||||
$script .= "
|
||||
/**
|
||||
* Reorder a set of sortable objects based on a list of id/position
|
||||
* Beware that there is no check made on the positions passed
|
||||
* So incoherent positions will result in an incoherent list
|
||||
*
|
||||
* @param array \$order id => rank pairs
|
||||
* @param PropelPDO \$con optional connection
|
||||
*
|
||||
* @return boolean true if the reordering took place, false if a database problem prevented it
|
||||
*/
|
||||
public function reorder(array \$order, PropelPDO \$con = null)
|
||||
{
|
||||
if (\$con === null) {
|
||||
\$con = Propel::getConnection($peerClassname::DATABASE_NAME);
|
||||
}
|
||||
|
||||
\$con->beginTransaction();
|
||||
try {
|
||||
\$ids = array_keys(\$order);
|
||||
\$objects = \$this->findPks(\$ids, \$con);
|
||||
foreach (\$objects as \$object) {
|
||||
\$pk = \$object->getPrimaryKey();
|
||||
if (\$object->$columnGetter() != \$order[\$pk]) {
|
||||
\$object->$columnSetter(\$order[\$pk]);
|
||||
\$object->save(\$con);
|
||||
}
|
||||
}
|
||||
\$con->commit();
|
||||
|
||||
return true;
|
||||
} catch (PropelException \$e) {
|
||||
\$con->rollback();
|
||||
throw \$e;
|
||||
}
|
||||
}
|
||||
";
|
||||
}
|
||||
|
||||
}
|
|
@ -1,607 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* This is the base class for any builder class that is using the data model.
|
||||
*
|
||||
* This could be extended by classes that build SQL DDL, PHP classes, configuration
|
||||
* files, input forms, etc.
|
||||
*
|
||||
* The GeneratorConfig needs to be set on this class in order for the builders
|
||||
* to be able to access the propel generator build properties. You should be
|
||||
* safe if you always use the GeneratorConfig to get a configured builder class
|
||||
* anyway.
|
||||
*
|
||||
* @author Hans Lellelid <hans@xmpl.org>
|
||||
* @package propel.generator.builder
|
||||
*/
|
||||
abstract class DataModelBuilder
|
||||
{
|
||||
|
||||
/**
|
||||
* The current table.
|
||||
* @var Table
|
||||
*/
|
||||
private $table;
|
||||
|
||||
/**
|
||||
* The generator config object holding build properties, etc.
|
||||
*
|
||||
* @var GeneratorConfig
|
||||
*/
|
||||
private $generatorConfig;
|
||||
|
||||
/**
|
||||
* An array of warning messages that can be retrieved for display (e.g. as part of phing build process).
|
||||
* @var array string[]
|
||||
*/
|
||||
private $warnings = array();
|
||||
|
||||
/**
|
||||
* Peer builder class for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $peerBuilder;
|
||||
|
||||
/**
|
||||
* Stub Peer builder class for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $stubPeerBuilder;
|
||||
|
||||
/**
|
||||
* Object builder class for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $objectBuilder;
|
||||
|
||||
/**
|
||||
* Stub Object builder class for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $stubObjectBuilder;
|
||||
|
||||
/**
|
||||
* Query builder class for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $queryBuilder;
|
||||
|
||||
/**
|
||||
* Stub Query builder class for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $stubQueryBuilder;
|
||||
|
||||
/**
|
||||
* TableMap builder class for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
protected $tablemapBuilder;
|
||||
|
||||
/**
|
||||
* Stub Interface builder class for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $interfaceBuilder;
|
||||
|
||||
/**
|
||||
* Stub child object for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $multiExtendObjectBuilder;
|
||||
|
||||
/**
|
||||
* Node object builder for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $nodeBuilder;
|
||||
|
||||
/**
|
||||
* Node peer builder for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $nodePeerBuilder;
|
||||
|
||||
/**
|
||||
* Stub node object builder for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $stubNodeBuilder;
|
||||
|
||||
/**
|
||||
* Stub node peer builder for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $stubNodePeerBuilder;
|
||||
|
||||
/**
|
||||
* NestedSet object builder for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $nestedSetBuilder;
|
||||
|
||||
/**
|
||||
* NestedSet peer builder for current table.
|
||||
* @var DataModelBuilder
|
||||
*/
|
||||
private $nestedSetPeerBuilder;
|
||||
|
||||
/**
|
||||
* The DDL builder for current table.
|
||||
* @var DDLBuilder
|
||||
*/
|
||||
private $ddlBuilder;
|
||||
|
||||
/**
|
||||
* The Data-SQL builder for current table.
|
||||
* @var DataSQLBuilder
|
||||
*/
|
||||
private $dataSqlBuilder;
|
||||
|
||||
/**
|
||||
* The Pluralizer class to use.
|
||||
* @var Pluralizer
|
||||
*/
|
||||
private $pluralizer;
|
||||
|
||||
|
||||
/**
|
||||
* Creates new instance of DataModelBuilder subclass.
|
||||
* @param Table $table The Table which we are using to build [OM, DDL, etc.].
|
||||
*/
|
||||
public function __construct(Table $table)
|
||||
{
|
||||
$this->table = $table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing Peer builder class for this table.
|
||||
* @return PeerBuilder
|
||||
*/
|
||||
public function getPeerBuilder()
|
||||
{
|
||||
if (!isset($this->peerBuilder)) {
|
||||
$this->peerBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'peer');
|
||||
}
|
||||
return $this->peerBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing Pluralizer class.
|
||||
* @return Pluralizer
|
||||
*/
|
||||
public function getPluralizer()
|
||||
{
|
||||
if (!isset($this->pluralizer)) {
|
||||
$this->pluralizer = $this->getGeneratorConfig()->getConfiguredPluralizer();
|
||||
}
|
||||
return $this->pluralizer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing stub Peer builder class for this table.
|
||||
* @return PeerBuilder
|
||||
*/
|
||||
public function getStubPeerBuilder()
|
||||
{
|
||||
if (!isset($this->stubPeerBuilder)) {
|
||||
$this->stubPeerBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'peerstub');
|
||||
}
|
||||
return $this->stubPeerBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing Object builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getObjectBuilder()
|
||||
{
|
||||
if (!isset($this->objectBuilder)) {
|
||||
$this->objectBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'object');
|
||||
}
|
||||
return $this->objectBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing stub Object builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getStubObjectBuilder()
|
||||
{
|
||||
if (!isset($this->stubObjectBuilder)) {
|
||||
$this->stubObjectBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'objectstub');
|
||||
}
|
||||
return $this->stubObjectBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing Query builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getQueryBuilder()
|
||||
{
|
||||
if (!isset($this->queryBuilder)) {
|
||||
$this->queryBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'query');
|
||||
}
|
||||
return $this->queryBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing stub Query builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getStubQueryBuilder()
|
||||
{
|
||||
if (!isset($this->stubQueryBuilder)) {
|
||||
$this->stubQueryBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'querystub');
|
||||
}
|
||||
return $this->stubQueryBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing Object builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getTableMapBuilder()
|
||||
{
|
||||
if (!isset($this->tablemapBuilder)) {
|
||||
$this->tablemapBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'tablemap');
|
||||
}
|
||||
return $this->tablemapBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing stub Interface builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getInterfaceBuilder()
|
||||
{
|
||||
if (!isset($this->interfaceBuilder)) {
|
||||
$this->interfaceBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'interface');
|
||||
}
|
||||
return $this->interfaceBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing stub child object builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getMultiExtendObjectBuilder()
|
||||
{
|
||||
if (!isset($this->multiExtendObjectBuilder)) {
|
||||
$this->multiExtendObjectBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'objectmultiextend');
|
||||
}
|
||||
return $this->multiExtendObjectBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing node Object builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getNodeBuilder()
|
||||
{
|
||||
if (!isset($this->nodeBuilder)) {
|
||||
$this->nodeBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'node');
|
||||
}
|
||||
return $this->nodeBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing node Peer builder class for this table.
|
||||
* @return PeerBuilder
|
||||
*/
|
||||
public function getNodePeerBuilder()
|
||||
{
|
||||
if (!isset($this->nodePeerBuilder)) {
|
||||
$this->nodePeerBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'nodepeer');
|
||||
}
|
||||
return $this->nodePeerBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing stub node Object builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getStubNodeBuilder()
|
||||
{
|
||||
if (!isset($this->stubNodeBuilder)) {
|
||||
$this->stubNodeBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'nodestub');
|
||||
}
|
||||
return $this->stubNodeBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing stub node Peer builder class for this table.
|
||||
* @return PeerBuilder
|
||||
*/
|
||||
public function getStubNodePeerBuilder()
|
||||
{
|
||||
if (!isset($this->stubNodePeerBuilder)) {
|
||||
$this->stubNodePeerBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'nodepeerstub');
|
||||
}
|
||||
return $this->stubNodePeerBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing nested set object builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getNestedSetBuilder()
|
||||
{
|
||||
if (!isset($this->nestedSetBuilder)) {
|
||||
$this->nestedSetBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'nestedset');
|
||||
}
|
||||
return $this->nestedSetBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing nested set Peer builder class for this table.
|
||||
* @return PeerBuilder
|
||||
*/
|
||||
public function getNestedSetPeerBuilder()
|
||||
{
|
||||
if (!isset($this->nestedSetPeerBuilder)) {
|
||||
$this->nestedSetPeerBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'nestedsetpeer');
|
||||
}
|
||||
return $this->nestedSetPeerBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing ddl builder class for this table.
|
||||
* @return DDLBuilder
|
||||
*/
|
||||
public function getDDLBuilder()
|
||||
{
|
||||
if (!isset($this->ddlBuilder)) {
|
||||
$this->ddlBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'ddl');
|
||||
}
|
||||
return $this->ddlBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new or existing data sql builder class for this table.
|
||||
* @return DataSQLBuilder
|
||||
*/
|
||||
public function getDataSQLBuilder()
|
||||
{
|
||||
if (!isset($this->dataSqlBuilder)) {
|
||||
$this->dataSqlBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'datasql');
|
||||
}
|
||||
return $this->dataSqlBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to return a NEW Peer class builder instance.
|
||||
*
|
||||
* This is used very frequently from the peer and object builders to get
|
||||
* a peer builder for a RELATED table.
|
||||
*
|
||||
* @param Table $table
|
||||
* @return PeerBuilder
|
||||
*/
|
||||
public function getNewPeerBuilder(Table $table)
|
||||
{
|
||||
return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'peer');
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to return a NEW Peer stub class builder instance.
|
||||
*
|
||||
* This is used from the peer and object builders to get
|
||||
* a peer builder for a RELATED table.
|
||||
*
|
||||
* @param Table $table
|
||||
* @return PeerBuilder
|
||||
*/
|
||||
public function getNewStubPeerBuilder(Table $table)
|
||||
{
|
||||
return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'peerstub');
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to return a NEW Object class builder instance.
|
||||
*
|
||||
* This is used very frequently from the peer and object builders to get
|
||||
* an object builder for a RELATED table.
|
||||
*
|
||||
* @param Table $table
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getNewObjectBuilder(Table $table)
|
||||
{
|
||||
return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'object');
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to return a NEW Object stub class builder instance.
|
||||
*
|
||||
* This is used from the query builders to get
|
||||
* an object builder for a RELATED table.
|
||||
*
|
||||
* @param Table $table
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getNewStubObjectBuilder(Table $table)
|
||||
{
|
||||
return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'objectstub');
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to return a NEW query class builder instance.
|
||||
*
|
||||
* This is used from the query builders to get
|
||||
* a query builder for a RELATED table.
|
||||
*
|
||||
* @param Table $table
|
||||
* @return QueryBuilder
|
||||
*/
|
||||
public function getNewQueryBuilder(Table $table)
|
||||
{
|
||||
return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'query');
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to return a NEW query stub class builder instance.
|
||||
*
|
||||
* This is used from the query builders to get
|
||||
* a query builder for a RELATED table.
|
||||
*
|
||||
* @param Table $table
|
||||
* @return QueryBuilder
|
||||
*/
|
||||
public function getNewStubQueryBuilder(Table $table)
|
||||
{
|
||||
return $this->getGeneratorConfig()->getConfiguredBuilder($table, 'querystub');
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new Query Inheritance builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getNewQueryInheritanceBuilder($child)
|
||||
{
|
||||
$queryInheritanceBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'queryinheritance');
|
||||
$queryInheritanceBuilder->setChild($child);
|
||||
return $queryInheritanceBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns new stub Query Inheritance builder class for this table.
|
||||
* @return ObjectBuilder
|
||||
*/
|
||||
public function getNewStubQueryInheritanceBuilder($child)
|
||||
{
|
||||
$stubQueryInheritanceBuilder = $this->getGeneratorConfig()->getConfiguredBuilder($this->getTable(), 'queryinheritancestub');
|
||||
$stubQueryInheritanceBuilder->setChild($child);
|
||||
return $stubQueryInheritanceBuilder;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the GeneratorConfig object.
|
||||
*
|
||||
* @return GeneratorConfig
|
||||
*/
|
||||
public function getGeneratorConfig()
|
||||
{
|
||||
return $this->generatorConfig;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a specific [name transformed] build property.
|
||||
*
|
||||
* @param string $name
|
||||
* @return string
|
||||
*/
|
||||
public function getBuildProperty($name)
|
||||
{
|
||||
if ($this->getGeneratorConfig()) {
|
||||
return $this->getGeneratorConfig()->getBuildProperty($name);
|
||||
}
|
||||
return null; // just to be explicit
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the GeneratorConfig object.
|
||||
*
|
||||
* @param GeneratorConfig $v
|
||||
*/
|
||||
public function setGeneratorConfig(GeneratorConfig $v)
|
||||
{
|
||||
$this->generatorConfig = $v;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the table for this builder.
|
||||
* @param Table $table
|
||||
*/
|
||||
public function setTable(Table $table)
|
||||
{
|
||||
$this->table = $table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the current Table object.
|
||||
* @return Table
|
||||
*/
|
||||
public function getTable()
|
||||
{
|
||||
return $this->table;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to returns the Platform class for this table (database).
|
||||
* @return Platform
|
||||
*/
|
||||
public function getPlatform()
|
||||
{
|
||||
if ($this->getTable() && $this->getTable()->getDatabase()) {
|
||||
return $this->getTable()->getDatabase()->getPlatform();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to returns the database for current table.
|
||||
* @return Database
|
||||
*/
|
||||
public function getDatabase()
|
||||
{
|
||||
if ($this->getTable()) {
|
||||
return $this->getTable()->getDatabase();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pushes a message onto the stack of warnings.
|
||||
* @param string $msg The warning message.
|
||||
*/
|
||||
protected function warn($msg)
|
||||
{
|
||||
$this->warnings[] = $msg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets array of warning messages.
|
||||
* @return array string[]
|
||||
*/
|
||||
public function getWarnings()
|
||||
{
|
||||
return $this->warnings;
|
||||
}
|
||||
|
||||
/**
|
||||
* Wraps call to Platform->quoteIdentifier() with a check to see whether quoting is enabled.
|
||||
*
|
||||
* All subclasses should call this quoteIdentifier() method rather than calling the Platform
|
||||
* method directly. This method is used by both DataSQLBuilder and DDLBuilder, and potentially
|
||||
* in the OM builders also, which is why it is defined in this class.
|
||||
*
|
||||
* @param string $text The text to quote.
|
||||
* @return string Quoted text.
|
||||
*/
|
||||
public function quoteIdentifier($text)
|
||||
{
|
||||
if (!$this->getBuildProperty('disableIdentifierQuoting')) {
|
||||
return $this->getPlatform()->quoteIdentifier($text);
|
||||
}
|
||||
return $text;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the name of the current class being built, with a possible prefix.
|
||||
* @return string
|
||||
* @see OMBuilder#getClassname()
|
||||
*/
|
||||
public function prefixClassname($identifier)
|
||||
{
|
||||
return $this->getBuildProperty('classPrefix') . $identifier;
|
||||
}
|
||||
|
||||
}
|
|
@ -1,120 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Tools to support class & package inclusion and referencing.
|
||||
*
|
||||
* @author Hans Lellelid <hans@xmpl.org>
|
||||
* @version $Revision: 1612 $
|
||||
* @package propel.generator.builder.om
|
||||
*/
|
||||
class ClassTools
|
||||
{
|
||||
|
||||
/**
|
||||
* Gets just classname, given a dot-path to class.
|
||||
* @param string $qualifiedName
|
||||
* @return string
|
||||
*/
|
||||
public static function classname($qualifiedName)
|
||||
{
|
||||
$pos = strrpos($qualifiedName, '.');
|
||||
if ($pos === false) {
|
||||
return $qualifiedName; // there is no '.' in the qualifed name
|
||||
} else {
|
||||
return substr($qualifiedName, $pos + 1); // start just after '.'
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the path to be used in include()/require() statement.
|
||||
*
|
||||
* Supports multiple function signatures:
|
||||
*
|
||||
* (1) getFilePath($dotPathClass);
|
||||
* (2) getFilePath($dotPathPrefix, $className);
|
||||
* (3) getFilePath($dotPathPrefix, $className, $extension);
|
||||
*
|
||||
* @param string $path dot-path to class or to package prefix.
|
||||
* @param string $classname class name
|
||||
* @param string $extension The extension to use on the file.
|
||||
* @return string The constructed file path.
|
||||
*/
|
||||
public static function getFilePath($path, $classname = null, $extension = '.php')
|
||||
{
|
||||
$path = strtr(ltrim($path, '.'), '.', '/');
|
||||
if ($classname !== null) {
|
||||
if ($path !== "") { $path .= '/'; }
|
||||
return $path . $classname . $extension;
|
||||
} else {
|
||||
return $path . $extension;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the basePeer path if specified for table/db.
|
||||
* If not, will return 'propel.util.BasePeer'
|
||||
* @return string
|
||||
*/
|
||||
public static function getBasePeer(Table $table) {
|
||||
$class = $table->getBasePeer();
|
||||
if ($class === null) {
|
||||
$class = "propel.util.BasePeer";
|
||||
}
|
||||
return $class;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the baseClass path if specified for table/db.
|
||||
* If not, will return 'propel.om.BaseObject'
|
||||
* @return string
|
||||
*/
|
||||
public static function getBaseClass(Table $table) {
|
||||
$class = $table->getBaseClass();
|
||||
if ($class === null) {
|
||||
$class = "propel.om.BaseObject";
|
||||
}
|
||||
return $class;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the interface path if specified for table.
|
||||
* If not, will return 'propel.om.Persistent'.
|
||||
* @return string
|
||||
*/
|
||||
public static function getInterface(Table $table) {
|
||||
$interface = $table->getInterface();
|
||||
if ($interface === null && !$table->isReadOnly()) {
|
||||
$interface = "propel.om.Persistent";
|
||||
}
|
||||
return $interface;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a list of PHP reserved words.
|
||||
*
|
||||
* @return array string[]
|
||||
*/
|
||||
public static function getPhpReservedWords()
|
||||
{
|
||||
return array(
|
||||
'and', 'or', 'xor', 'exception', '__FILE__', '__LINE__',
|
||||
'array', 'as', 'break', 'case', 'class', 'const', 'continue',
|
||||
'declare', 'default', 'die', 'do', 'echo', 'else', 'elseif', 'empty',
|
||||
'enddeclare', 'endfor', 'endforeach', 'endif', 'endswitch', 'endwhile',
|
||||
'eval', 'exit', 'extends', 'for', 'foreach', 'function', 'global',
|
||||
'if', 'include', 'include_once', 'isset', 'list', 'new', 'print', 'require',
|
||||
'require_once', 'return', 'static', 'switch', 'unset', 'use', 'var', 'while',
|
||||
'__FUNCTION__', '__CLASS__', '__METHOD__', 'final', 'php_user_filter', 'interface',
|
||||
'implements', 'extends', 'public', 'protected', 'private', 'abstract', 'clone', 'try', 'catch',
|
||||
'throw', 'this', 'namespace'
|
||||
);
|
||||
}
|
||||
}
|
|
@ -1,139 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
require_once 'builder/om/OMBuilder.php';
|
||||
|
||||
/**
|
||||
* Generates the empty PHP5 stub class for object query
|
||||
*
|
||||
* This class produces the empty stub class that can be customized with application
|
||||
* business logic, custom behavior, etc.
|
||||
*
|
||||
* @author Francois Zaninotto
|
||||
* @package propel.generator.builder.om
|
||||
*/
|
||||
class ExtensionQueryBuilder extends OMBuilder
|
||||
{
|
||||
|
||||
/**
|
||||
* Returns the name of the current class being built.
|
||||
* @return string
|
||||
*/
|
||||
public function getUnprefixedClassname()
|
||||
{
|
||||
return $this->getTable()->getPhpName() . 'Query';
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the include() statements for files that this class depends on or utilizes.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addIncludes(&$script)
|
||||
{
|
||||
$requiredClassFilePath = $this->getQueryBuilder()->getClassFilePath();
|
||||
|
||||
$script .="
|
||||
require '".$requiredClassFilePath."';
|
||||
";
|
||||
} // addIncludes()
|
||||
|
||||
/**
|
||||
* Adds class phpdoc comment and openning of class.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addClassOpen(&$script)
|
||||
{
|
||||
$table = $this->getTable();
|
||||
$this->declareClassFromBuilder($this->getQueryBuilder());
|
||||
$tableName = $table->getName();
|
||||
$tableDesc = $table->getDescription();
|
||||
$baseClassname = $this->getQueryBuilder()->getClassname();
|
||||
|
||||
$script .= "
|
||||
|
||||
/**
|
||||
* Skeleton subclass for performing query and update operations on the '$tableName' table.
|
||||
*
|
||||
* $tableDesc
|
||||
*";
|
||||
if ($this->getBuildProperty('addTimeStamp')) {
|
||||
$now = strftime('%c');
|
||||
$script .= "
|
||||
* This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on:
|
||||
*
|
||||
* $now
|
||||
*";
|
||||
}
|
||||
$script .= "
|
||||
* You should add additional methods to this class to meet the
|
||||
* application requirements. This class will only be generated as
|
||||
* long as it does not already exist in the output directory.
|
||||
*
|
||||
* @package propel.generator.".$this->getPackage()."
|
||||
*/
|
||||
class ".$this->getClassname()." extends $baseClassname {
|
||||
";
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the methods that are added as part of the stub query class.
|
||||
*
|
||||
* By default there are no methods for the empty stub classes; override this method
|
||||
* if you want to change that behavior.
|
||||
*
|
||||
* @see QueryBuilder::addClassBody()
|
||||
*/
|
||||
|
||||
protected function addClassBody(&$script)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes class.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addClassClose(&$script)
|
||||
{
|
||||
$script .= "
|
||||
} // " . $this->getClassname() . "
|
||||
";
|
||||
$this->applyBehaviorModifier('extensionQueryFilter', $script, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether any registered behavior on that table has a modifier for a hook
|
||||
* @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave"
|
||||
* @return boolean
|
||||
*/
|
||||
public function hasBehaviorModifier($hookName, $modifier = null)
|
||||
{
|
||||
return parent::hasBehaviorModifier($hookName, 'QueryBuilderModifier');
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether any registered behavior on that table has a modifier for a hook
|
||||
* @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave"
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
public function applyBehaviorModifier($hookName, &$script, $tab = " ")
|
||||
{
|
||||
return $this->applyBehaviorModifierBase($hookName, 'QueryBuilderModifier', $script, $tab);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether any registered behavior content creator on that table exists a contentName
|
||||
* @param string $contentName The name of the content as called from one of this class methods, e.g. "parentClassname"
|
||||
*/
|
||||
public function getBehaviorContent($contentName)
|
||||
{
|
||||
return $this->getBehaviorContentBase($contentName, 'QueryBuilderModifier');
|
||||
}
|
||||
|
||||
}
|
|
@ -1,138 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
require_once 'builder/om/OMBuilder.php';
|
||||
|
||||
/**
|
||||
* Generates the empty PHP5 stub query class for use with single table inheritance.
|
||||
*
|
||||
* This class produces the empty stub class that can be customized with application
|
||||
* business logic, custom behavior, etc.
|
||||
*
|
||||
*
|
||||
* @author François Zaninotto
|
||||
* @package propel.generator.builder.om
|
||||
*/
|
||||
class ExtensionQueryInheritanceBuilder extends OMBuilder
|
||||
{
|
||||
|
||||
/**
|
||||
* The current child "object" we are operating on.
|
||||
*/
|
||||
protected $child;
|
||||
|
||||
/**
|
||||
* Returns the name of the current class being built.
|
||||
* @return string
|
||||
*/
|
||||
public function getUnprefixedClassname()
|
||||
{
|
||||
return $this->getChild()->getClassName() . 'Query';
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the child object that we're operating on currrently.
|
||||
* @param $child Inheritance
|
||||
*/
|
||||
public function setChild(Inheritance $child)
|
||||
{
|
||||
$this->child = $child;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the child object we're operating on currently.
|
||||
* @return Inheritance
|
||||
* @throws BuildException - if child was not set.
|
||||
*/
|
||||
public function getChild()
|
||||
{
|
||||
if (!$this->child) {
|
||||
throw new BuildException("The PHP5MultiExtendObjectBuilder needs to be told which child class to build (via setChild() method) before it can build the stub class.");
|
||||
}
|
||||
return $this->child;
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the include() statements for files that this class depends on or utilizes.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addIncludes(&$script)
|
||||
{
|
||||
$requiredClassFilePath = $this->getStubQueryBuilder()->getClassFilePath();
|
||||
|
||||
$script .="
|
||||
require '".$requiredClassFilePath."';
|
||||
";
|
||||
} // addIncludes()
|
||||
|
||||
/**
|
||||
* Adds class phpdoc comment and openning of class.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addClassOpen(&$script)
|
||||
{
|
||||
$table = $this->getTable();
|
||||
$tableName = $table->getName();
|
||||
$tableDesc = $table->getDescription();
|
||||
|
||||
$baseBuilder = $this->getNewQueryInheritanceBuilder($this->getChild());
|
||||
$this->declareClassFromBuilder($baseBuilder);
|
||||
$baseClassname = $baseBuilder->getClassname();
|
||||
|
||||
$script .= "
|
||||
|
||||
/**
|
||||
* Skeleton subclass for representing a query for one of the subclasses of the '$tableName' table.
|
||||
*
|
||||
* $tableDesc
|
||||
*";
|
||||
if ($this->getBuildProperty('addTimeStamp')) {
|
||||
$now = strftime('%c');
|
||||
$script .= "
|
||||
* This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on:
|
||||
*
|
||||
* $now
|
||||
*";
|
||||
}
|
||||
$script .= "
|
||||
* You should add additional methods to this class to meet the
|
||||
* application requirements. This class will only be generated as
|
||||
* long as it does not already exist in the output directory.
|
||||
*
|
||||
* @package propel.generator.".$this->getPackage()."
|
||||
*/
|
||||
class " .$this->getClassname() . " extends " . $baseClassname . " {
|
||||
";
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the methods that are added as part of the stub object class.
|
||||
*
|
||||
* By default there are no methods for the empty stub classes; override this method
|
||||
* if you want to change that behavior.
|
||||
*
|
||||
* @see ObjectBuilder::addClassBody()
|
||||
*/
|
||||
protected function addClassBody(&$script)
|
||||
{
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes class.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addClassClose(&$script)
|
||||
{
|
||||
$script .= "
|
||||
} // " . $this->getClassname() . "
|
||||
";
|
||||
}
|
||||
|
||||
} // MultiExtensionQueryBuilder
|
|
@ -1,526 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
require_once 'builder/DataModelBuilder.php';
|
||||
|
||||
/**
|
||||
* Baseclass for OM-building classes.
|
||||
*
|
||||
* OM-building classes are those that build a PHP (or other) class to service
|
||||
* a single table. This includes Peer classes, Entity classes, Map classes,
|
||||
* Node classes, Nested Set classes, etc.
|
||||
*
|
||||
* @author Hans Lellelid <hans@xmpl.org>
|
||||
* @package propel.generator.builder.om
|
||||
*/
|
||||
abstract class OMBuilder extends DataModelBuilder
|
||||
{
|
||||
/**
|
||||
* Declared fully qualified classnames, to build the 'namespace' statements
|
||||
* according to this table's namespace.
|
||||
* @var array
|
||||
*/
|
||||
protected $declaredClasses = array();
|
||||
|
||||
/**
|
||||
* Builds the PHP source for current class and returns it as a string.
|
||||
*
|
||||
* This is the main entry point and defines a basic structure that classes should follow.
|
||||
* In most cases this method will not need to be overridden by subclasses. This method
|
||||
* does assume that the output language is PHP code, so it will need to be overridden if
|
||||
* this is not the case.
|
||||
*
|
||||
* @return string The resulting PHP sourcecode.
|
||||
*/
|
||||
public function build()
|
||||
{
|
||||
$this->validateModel();
|
||||
|
||||
$script = '';
|
||||
if ($this->isAddIncludes()) {
|
||||
$this->addIncludes($script);
|
||||
}
|
||||
$this->addClassOpen($script);
|
||||
$this->addClassBody($script);
|
||||
$this->addClassClose($script);
|
||||
|
||||
if($useStatements = $this->getUseStatements($ignoredNamespace = $this->getNamespace())) {
|
||||
$script = $useStatements . $script;
|
||||
}
|
||||
if($namespaceStatement = $this->getNamespaceStatement()) {
|
||||
$script = $namespaceStatement . $script;
|
||||
}
|
||||
//if($this->getTable()->getName() == 'book_club_list') die($ignoredNamespace);
|
||||
|
||||
return "<" . "?php
|
||||
|
||||
" . $script;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates the current table to make sure that it won't
|
||||
* result in generated code that will not parse.
|
||||
*
|
||||
* This method may emit warnings for code which may cause problems
|
||||
* and will throw exceptions for errors that will definitely cause
|
||||
* problems.
|
||||
*/
|
||||
protected function validateModel()
|
||||
{
|
||||
// Validation is currently only implemented in the subclasses.
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a $obj = new Book(); code snippet. Can be used by frameworks, for instance, to
|
||||
* extend this behavior, e.g. initialize the object after creating the instance or so.
|
||||
*
|
||||
* @return string Some code
|
||||
*/
|
||||
public function buildObjectInstanceCreationCode($objName, $clsName)
|
||||
{
|
||||
return "$objName = new $clsName();";
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the qualified (prefixed) classname that is being built by the current class.
|
||||
* This method must be implemented by child classes.
|
||||
* @return string
|
||||
*/
|
||||
abstract public function getUnprefixedClassname();
|
||||
|
||||
/**
|
||||
* Returns the prefixed classname that is being built by the current class.
|
||||
* @return string
|
||||
* @see DataModelBuilder#prefixClassname()
|
||||
*/
|
||||
public function getClassname()
|
||||
{
|
||||
return $this->prefixClassname($this->getUnprefixedClassname());
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the namespaced classname if there is a namespace, and the raw classname otherwise
|
||||
* @return string
|
||||
*/
|
||||
public function getFullyQualifiedClassname()
|
||||
{
|
||||
if ($namespace = $this->getNamespace()) {
|
||||
return $namespace . '\\' . $this->getClassname();
|
||||
} else {
|
||||
return $this->getClassname();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the dot-path representation of current class being built.
|
||||
* @return string
|
||||
*/
|
||||
public function getClasspath()
|
||||
{
|
||||
if ($this->getPackage()) {
|
||||
$path = $this->getPackage() . '.' . $this->getClassname();
|
||||
} else {
|
||||
$path = $this->getClassname();
|
||||
}
|
||||
return $path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the full path to the file for the current class.
|
||||
* @return string
|
||||
*/
|
||||
public function getClassFilePath()
|
||||
{
|
||||
return ClassTools::getFilePath($this->getPackage(), $this->getClassname());
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets package name for this table.
|
||||
* This is overridden by child classes that have different packages.
|
||||
* @return string
|
||||
*/
|
||||
public function getPackage()
|
||||
{
|
||||
$pkg = ($this->getTable()->getPackage() ? $this->getTable()->getPackage() : $this->getDatabase()->getPackage());
|
||||
if (!$pkg) {
|
||||
$pkg = $this->getBuildProperty('targetPackage');
|
||||
}
|
||||
return $pkg;
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns filesystem path for current package.
|
||||
* @return string
|
||||
*/
|
||||
public function getPackagePath()
|
||||
{
|
||||
return strtr($this->getPackage(), '.', '/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the user-defined namespace for this table,
|
||||
* or the database namespace otherwise.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
public function getNamespace()
|
||||
{
|
||||
return $this->getTable()->getNamespace();
|
||||
}
|
||||
|
||||
public function declareClassNamespace($class, $namespace = '')
|
||||
{
|
||||
if (isset($this->declaredClasses[$namespace])
|
||||
&& in_array($class, $this->declaredClasses[$namespace])) {
|
||||
return;
|
||||
}
|
||||
$this->declaredClasses[$namespace][] = $class;
|
||||
}
|
||||
|
||||
public function declareClass($fullyQualifiedClassName)
|
||||
{
|
||||
$fullyQualifiedClassName = trim($fullyQualifiedClassName, '\\');
|
||||
if (($pos = strrpos($fullyQualifiedClassName, '\\')) !== false) {
|
||||
$this->declareClassNamespace(substr($fullyQualifiedClassName, $pos + 1), substr($fullyQualifiedClassName, 0, $pos));
|
||||
} else {
|
||||
// root namespace
|
||||
$this->declareClassNamespace($fullyQualifiedClassName);
|
||||
}
|
||||
}
|
||||
|
||||
public function declareClassFromBuilder($builder)
|
||||
{
|
||||
$this->declareClassNamespace($builder->getClassname(), $builder->getNamespace());
|
||||
}
|
||||
|
||||
public function declareClasses()
|
||||
{
|
||||
$args = func_get_args();
|
||||
foreach ($args as $class) {
|
||||
$this->declareClass($class);
|
||||
}
|
||||
}
|
||||
|
||||
public function getDeclaredClasses($namespace = null)
|
||||
{
|
||||
if (null !== $namespace && isset($this->declaredClasses[$namespace])) {
|
||||
return $this->declaredClasses[$namespace];
|
||||
} else {
|
||||
return $this->declaredClasses;
|
||||
}
|
||||
}
|
||||
|
||||
public function getNamespaceStatement()
|
||||
{
|
||||
$namespace = $this->getNamespace();
|
||||
if ($namespace != '') {
|
||||
return sprintf("namespace %s;
|
||||
|
||||
", $namespace);
|
||||
}
|
||||
}
|
||||
|
||||
public function getUseStatements($ignoredNamespace = null)
|
||||
{
|
||||
$declaredClasses = $this->declaredClasses;
|
||||
unset($declaredClasses[$ignoredNamespace]);
|
||||
ksort($declaredClasses);
|
||||
foreach ($declaredClasses as $namespace => $classes) {
|
||||
sort($classes);
|
||||
foreach ($classes as $class) {
|
||||
$script .= sprintf("use %s\\%s;
|
||||
", $namespace, $class);
|
||||
}
|
||||
}
|
||||
return $script;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shortcut method to return the [stub] peer classname for current table.
|
||||
* This is the classname that is used whenever object or peer classes want
|
||||
* to invoke methods of the peer classes.
|
||||
* @return string (e.g. 'MyPeer')
|
||||
* @see StubPeerBuilder::getClassname()
|
||||
*/
|
||||
public function getPeerClassname() {
|
||||
return $this->getStubPeerBuilder()->getClassname();
|
||||
}
|
||||
|
||||
/**
|
||||
* Shortcut method to return the [stub] query classname for current table.
|
||||
* This is the classname that is used whenever object or peer classes want
|
||||
* to invoke methods of the query classes.
|
||||
* @return string (e.g. 'Myquery')
|
||||
* @see StubQueryBuilder::getClassname()
|
||||
*/
|
||||
public function getQueryClassname() {
|
||||
return $this->getStubQueryBuilder()->getClassname();
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the object classname for current table.
|
||||
* This is the classname that is used whenever object or peer classes want
|
||||
* to invoke methods of the object classes.
|
||||
* @return string (e.g. 'My')
|
||||
* @see StubPeerBuilder::getClassname()
|
||||
*/
|
||||
public function getObjectClassname() {
|
||||
return $this->getStubObjectBuilder()->getClassname();
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the column constant name (e.g. PeerName::COLUMN_NAME).
|
||||
*
|
||||
* @param Column $col The column we need a name for.
|
||||
* @param string $classname The Peer classname to use.
|
||||
*
|
||||
* @return string If $classname is provided, then will return $classname::COLUMN_NAME; if not, then the peername is looked up for current table to yield $currTablePeer::COLUMN_NAME.
|
||||
*/
|
||||
public function getColumnConstant($col, $classname = null)
|
||||
{
|
||||
if ($col === null) {
|
||||
$e = new Exception("No col specified.");
|
||||
print $e;
|
||||
throw $e;
|
||||
}
|
||||
if ($classname === null) {
|
||||
return $this->getBuildProperty('classPrefix') . $col->getConstantName();
|
||||
}
|
||||
// was it overridden in schema.xml ?
|
||||
if ($col->getPeerName()) {
|
||||
$const = strtoupper($col->getPeerName());
|
||||
} else {
|
||||
$const = strtoupper($col->getName());
|
||||
}
|
||||
return $classname.'::'.$const;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the basePeer path if specified for table/db.
|
||||
* If not, will return 'propel.util.BasePeer'
|
||||
* @return string
|
||||
*/
|
||||
public function getBasePeer(Table $table) {
|
||||
$class = $table->getBasePeer();
|
||||
if ($class === null) {
|
||||
$class = "propel.util.BasePeer";
|
||||
}
|
||||
return $class;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to get the foreign Table object for an fkey.
|
||||
* @deprecated use ForeignKey::getForeignTable() instead
|
||||
* @return Table
|
||||
*/
|
||||
protected function getForeignTable(ForeignKey $fk)
|
||||
{
|
||||
return $this->getTable()->getDatabase()->getTable($fk->getForeignTableName());
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience method to get the default Join Type for a relation.
|
||||
* If the key is required, an INNER JOIN will be returned, else a LEFT JOIN will be suggested,
|
||||
* unless the schema is provided with the DefaultJoin attribute, which overrules the default Join Type
|
||||
*
|
||||
* @param ForeignKey $fk
|
||||
* @return string
|
||||
*/
|
||||
protected function getJoinType(ForeignKey $fk)
|
||||
{
|
||||
return $fk->getDefaultJoin() ?
|
||||
"'".$fk->getDefaultJoin()."'" :
|
||||
($fk->isLocalColumnsRequired() ? 'Criteria::INNER_JOIN' : 'Criteria::LEFT_JOIN');
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the PHP method name affix to be used for fkeys for the current table (not referrers to this table).
|
||||
*
|
||||
* The difference between this method and the getRefFKPhpNameAffix() method is that in this method the
|
||||
* classname in the affix is the foreign table classname.
|
||||
*
|
||||
* @param ForeignKey $fk The local FK that we need a name for.
|
||||
* @param boolean $plural Whether the php name should be plural (e.g. initRelatedObjs() vs. addRelatedObj()
|
||||
* @return string
|
||||
*/
|
||||
public function getFKPhpNameAffix(ForeignKey $fk, $plural = false)
|
||||
{
|
||||
if ($fk->getPhpName()) {
|
||||
if ($plural) {
|
||||
return $this->getPluralizer()->getPluralForm($fk->getPhpName());
|
||||
} else {
|
||||
return $fk->getPhpName();
|
||||
}
|
||||
} else {
|
||||
$className = $fk->getForeignTable()->getPhpName();
|
||||
if ($plural) {
|
||||
$className = $this->getPluralizer()->getPluralForm($className);
|
||||
}
|
||||
return $className . $this->getRelatedBySuffix($fk);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the "RelatedBy*" suffix (if needed) that is attached to method and variable names.
|
||||
*
|
||||
* The related by suffix is based on the local columns of the foreign key. If there is more than
|
||||
* one column in a table that points to the same foreign table, then a 'RelatedByLocalColName' suffix
|
||||
* will be appended.
|
||||
*
|
||||
* @return string
|
||||
*/
|
||||
protected static function getRelatedBySuffix(ForeignKey $fk)
|
||||
{
|
||||
$relCol = '';
|
||||
foreach ($fk->getLocalForeignMapping() as $localColumnName => $foreignColumnName) {
|
||||
$localTable = $fk->getTable();
|
||||
$localColumn = $localTable->getColumn($localColumnName);
|
||||
if (!$localColumn) {
|
||||
throw new Exception("Could not fetch column: $columnName in table " . $localTable->getName());
|
||||
}
|
||||
if (count($localTable->getForeignKeysReferencingTable($fk->getForeignTableName())) > 1
|
||||
|| count($fk->getForeignTable()->getForeignKeysReferencingTable($fk->getTableName())) > 0
|
||||
|| $fk->getForeignTableName() == $fk->getTableName()) {
|
||||
// self referential foreign key, or several foreign keys to the same table, or cross-reference fkey
|
||||
$relCol .= $localColumn->getPhpName();
|
||||
}
|
||||
}
|
||||
|
||||
if ($relCol != '') {
|
||||
$relCol = 'RelatedBy' . $relCol;
|
||||
}
|
||||
|
||||
return $relCol;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the PHP method name affix to be used for referencing foreign key methods and variable names (e.g. set????(), $coll???).
|
||||
*
|
||||
* The difference between this method and the getFKPhpNameAffix() method is that in this method the
|
||||
* classname in the affix is the classname of the local fkey table.
|
||||
*
|
||||
* @param ForeignKey $fk The referrer FK that we need a name for.
|
||||
* @param boolean $plural Whether the php name should be plural (e.g. initRelatedObjs() vs. addRelatedObj()
|
||||
* @return string
|
||||
*/
|
||||
public function getRefFKPhpNameAffix(ForeignKey $fk, $plural = false)
|
||||
{
|
||||
if ($fk->getRefPhpName()) {
|
||||
if ($plural) {
|
||||
return $this->getPluralizer()->getPluralForm($fk->getRefPhpName());
|
||||
} else {
|
||||
return $fk->getRefPhpName();
|
||||
}
|
||||
} else {
|
||||
$className = $fk->getTable()->getPhpName();
|
||||
if ($plural) {
|
||||
$className = $this->getPluralizer()->getPluralForm($className);
|
||||
}
|
||||
return $className . $this->getRefRelatedBySuffix($fk);
|
||||
}
|
||||
}
|
||||
|
||||
protected static function getRefRelatedBySuffix(ForeignKey $fk)
|
||||
{
|
||||
$relCol = '';
|
||||
foreach ($fk->getLocalForeignMapping() as $localColumnName => $foreignColumnName) {
|
||||
$localTable = $fk->getTable();
|
||||
$localColumn = $localTable->getColumn($localColumnName);
|
||||
if (!$localColumn) {
|
||||
throw new Exception("Could not fetch column: $columnName in table " . $localTable->getName());
|
||||
}
|
||||
$foreignKeysToForeignTable = $localTable->getForeignKeysReferencingTable($fk->getForeignTableName());
|
||||
if ($fk->getForeignTableName() == $fk->getTableName()) {
|
||||
// self referential foreign key
|
||||
$relCol .= $fk->getForeignTable()->getColumn($foreignColumnName)->getPhpName();
|
||||
if (count($foreignKeysToForeignTable) > 1) {
|
||||
// several self-referential foreign keys
|
||||
$relCol .= array_search($fk, $foreignKeysToForeignTable);
|
||||
}
|
||||
} elseif (count($foreignKeysToForeignTable) > 1 || count($fk->getForeignTable()->getForeignKeysReferencingTable($fk->getTableName())) > 0) {
|
||||
// several foreign keys to the same table, or symmetrical foreign key in foreign table
|
||||
$relCol .= $localColumn->getPhpName();
|
||||
}
|
||||
}
|
||||
|
||||
if ($relCol != '') {
|
||||
$relCol = 'RelatedBy' . $relCol;
|
||||
}
|
||||
|
||||
return $relCol;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to add the include statements.
|
||||
* This is based on the build property propel.addIncludes
|
||||
*/
|
||||
protected function isAddIncludes()
|
||||
{
|
||||
return $this->getBuildProperty('addIncludes');
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether any registered behavior on that table has a modifier for a hook
|
||||
* @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave"
|
||||
* @param string $modifier The name of the modifier object providing the method in the behavior
|
||||
* @return boolean
|
||||
*/
|
||||
public function hasBehaviorModifier($hookName, $modifier)
|
||||
{
|
||||
$modifierGetter = 'get' . $modifier;
|
||||
foreach ($this->getTable()->getBehaviors() as $behavior) {
|
||||
if(method_exists($behavior->$modifierGetter(), $hookName)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether any registered behavior on that table has a modifier for a hook
|
||||
* @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave"
|
||||
* @param string $modifier The name of the modifier object providing the method in the behavior
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
public function applyBehaviorModifierBase($hookName, $modifier, &$script, $tab = " ")
|
||||
{
|
||||
$modifierGetter = 'get' . $modifier;
|
||||
foreach ($this->getTable()->getBehaviors() as $behavior) {
|
||||
$modifier = $behavior->$modifierGetter();
|
||||
if(method_exists($modifier, $hookName)) {
|
||||
if (strpos($hookName, 'Filter') !== false) {
|
||||
// filter hook: the script string will be modified by the behavior
|
||||
$modifier->$hookName($script, $this);
|
||||
} else {
|
||||
// regular hook: the behavior returns a string to append to the script string
|
||||
$script .= "\n" . $tab . '// ' . $behavior->getName() . " behavior\n";
|
||||
$script .= preg_replace('/^/m', $tab, $modifier->$hookName($this));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether any registered behavior content creator on that table exists a contentName
|
||||
* @param string $contentName The name of the content as called from one of this class methods, e.g. "parentClassname"
|
||||
* @param string $modifier The name of the modifier object providing the method in the behavior
|
||||
*/
|
||||
public function getBehaviorContentBase($contentName, $modifier)
|
||||
{
|
||||
$modifierGetter = 'get' . $modifier;
|
||||
foreach ($this->getTable()->getBehaviors() as $behavior) {
|
||||
$modifier = $behavior->$modifierGetter();
|
||||
if(method_exists($modifier, $contentName)) {
|
||||
return $modifier->$contentName($this);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
|
@ -1,186 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
require_once 'builder/om/OMBuilder.php';
|
||||
|
||||
/**
|
||||
* Base class for Peer-building classes.
|
||||
*
|
||||
* This class is designed so that it can be extended by a PHP4PeerBuilder in addition
|
||||
* to the "standard" PHP5PeerBuilder and PHP5ComplexOMPeerBuilder. Hence, this class
|
||||
* should not have any actual template code in it -- simply basic logic & utility
|
||||
* methods.
|
||||
*
|
||||
* @author Hans Lellelid <hans@xmpl.org>
|
||||
* @package propel.generator.builder.om
|
||||
*/
|
||||
abstract class ObjectBuilder extends OMBuilder
|
||||
{
|
||||
|
||||
/**
|
||||
* Constructs a new PeerBuilder subclass.
|
||||
*/
|
||||
public function __construct(Table $table) {
|
||||
parent::__construct($table);
|
||||
}
|
||||
|
||||
/**
|
||||
* This method adds the contents of the generated class to the script.
|
||||
*
|
||||
* This method is abstract and should be overridden by the subclasses.
|
||||
*
|
||||
* Hint: Override this method in your subclass if you want to reorganize or
|
||||
* drastically change the contents of the generated peer class.
|
||||
*
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
abstract protected function addClassBody(&$script);
|
||||
|
||||
/**
|
||||
* Adds the getter methods for the column values.
|
||||
* This is here because it is probably generic enough to apply to templates being generated
|
||||
* in different langauges (e.g. PHP4 and PHP5).
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addColumnAccessorMethods(&$script)
|
||||
{
|
||||
$table = $this->getTable();
|
||||
|
||||
foreach ($table->getColumns() as $col) {
|
||||
|
||||
// if they're not using the DateTime class than we will generate "compatibility" accessor method
|
||||
if ($col->getType() === PropelTypes::DATE || $col->getType() === PropelTypes::TIME || $col->getType() === PropelTypes::TIMESTAMP) {
|
||||
$this->addTemporalAccessor($script, $col);
|
||||
} else {
|
||||
$this->addDefaultAccessor($script, $col);
|
||||
}
|
||||
|
||||
if ($col->isLazyLoad()) {
|
||||
$this->addLazyLoader($script, $col);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the mutator (setter) methods for setting column values.
|
||||
* This is here because it is probably generic enough to apply to templates being generated
|
||||
* in different langauges (e.g. PHP4 and PHP5).
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addColumnMutatorMethods(&$script)
|
||||
{
|
||||
foreach ($this->getTable()->getColumns() as $col) {
|
||||
|
||||
if ($col->isLobType()) {
|
||||
$this->addLobMutator($script, $col);
|
||||
} elseif ($col->getType() === PropelTypes::DATE || $col->getType() === PropelTypes::TIME || $col->getType() === PropelTypes::TIMESTAMP) {
|
||||
$this->addTemporalMutator($script, $col);
|
||||
} else {
|
||||
$this->addDefaultMutator($script, $col);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Gets the baseClass path if specified for table/db.
|
||||
* If not, will return 'propel.om.BaseObject'
|
||||
* @return string
|
||||
*/
|
||||
protected function getBaseClass() {
|
||||
$class = $this->getTable()->getBaseClass();
|
||||
if ($class === null) {
|
||||
$class = "propel.om.BaseObject";
|
||||
}
|
||||
return $class;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the interface path if specified for current table.
|
||||
* If not, will return 'propel.om.Persistent'.
|
||||
* @return string
|
||||
*/
|
||||
protected function getInterface() {
|
||||
$interface = $this->getTable()->getInterface();
|
||||
if ($interface === null && !$this->getTable()->isReadOnly()) {
|
||||
$interface = "propel.om.Persistent";
|
||||
}
|
||||
return $interface;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to add the generic mutator methods (setByName(), setByPosition(), fromArray()).
|
||||
* This is based on the build property propel.addGenericMutators, and also whether the
|
||||
* table is read-only or an alias.
|
||||
*/
|
||||
protected function isAddGenericMutators()
|
||||
{
|
||||
$table = $this->getTable();
|
||||
return (!$table->isAlias() && $this->getBuildProperty('addGenericMutators') && !$table->isReadOnly());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to add the generic accessor methods (getByName(), getByPosition(), toArray()).
|
||||
* This is based on the build property propel.addGenericAccessors, and also whether the
|
||||
* table is an alias.
|
||||
*/
|
||||
protected function isAddGenericAccessors()
|
||||
{
|
||||
$table = $this->getTable();
|
||||
return (!$table->isAlias() && $this->getBuildProperty('addGenericAccessors'));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether to add the validate() method.
|
||||
* This is based on the build property propel.addValidateMethod
|
||||
*/
|
||||
protected function isAddValidateMethod()
|
||||
{
|
||||
return $this->getBuildProperty('addValidateMethod');
|
||||
}
|
||||
|
||||
protected function hasDefaultValues()
|
||||
{
|
||||
foreach ($this->getTable()->getColumns() as $col) {
|
||||
if($col->getDefaultValue() !== null) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether any registered behavior on that table has a modifier for a hook
|
||||
* @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave"
|
||||
* @return boolean
|
||||
*/
|
||||
public function hasBehaviorModifier($hookName, $modifier = null)
|
||||
{
|
||||
return parent::hasBehaviorModifier($hookName, 'ObjectBuilderModifier');
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether any registered behavior on that table has a modifier for a hook
|
||||
* @param string $hookName The name of the hook as called from one of this class methods, e.g. "preSave"
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
public function applyBehaviorModifier($hookName, &$script, $tab = " ")
|
||||
{
|
||||
return $this->applyBehaviorModifierBase($hookName, 'ObjectBuilderModifier', $script, $tab);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks whether any registered behavior content creator on that table exists a contentName
|
||||
* @param string $contentName The name of the content as called from one of this class methods, e.g. "parentClassname"
|
||||
*/
|
||||
public function getBehaviorContent($contentName)
|
||||
{
|
||||
return $this->getBehaviorContentBase($contentName, 'ObjectBuilderModifier');
|
||||
}
|
||||
|
||||
}
|
|
@ -1,111 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
require_once 'builder/om/ObjectBuilder.php';
|
||||
|
||||
/**
|
||||
* Generates the empty PHP5 stub node object class for user object model (OM).
|
||||
*
|
||||
* This class produces the empty stub class that can be customized with application
|
||||
* business logic, custom behavior, etc.
|
||||
*
|
||||
* This class replaces the ExtensionNode.tpl, with the intent of being easier for users
|
||||
* to customize (through extending & overriding).
|
||||
*
|
||||
* @author Hans Lellelid <hans@xmpl.org>
|
||||
* @package propel.generator.builder.om
|
||||
*/
|
||||
class PHP5ExtensionNodeBuilder extends ObjectBuilder
|
||||
{
|
||||
|
||||
/**
|
||||
* Returns the name of the current class being built.
|
||||
* @return string
|
||||
*/
|
||||
public function getUnprefixedClassname()
|
||||
{
|
||||
return $this->getTable()->getPhpName() . 'Node';
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the include() statements for files that this class depends on or utilizes.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addIncludes(&$script)
|
||||
{
|
||||
$script .= "
|
||||
require '".$this->getNodeBuilder()->getClassFilePath()."';
|
||||
";
|
||||
} // addIncludes()
|
||||
|
||||
/**
|
||||
* Adds class phpdoc comment and openning of class.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addClassOpen(&$script)
|
||||
{
|
||||
|
||||
$table = $this->getTable();
|
||||
$tableName = $table->getName();
|
||||
$tableDesc = $table->getDescription();
|
||||
|
||||
$baseClassname = $this->getNodeBuilder()->getClassname();
|
||||
|
||||
$script .= "
|
||||
|
||||
/**
|
||||
* Skeleton subclass for representing a node from the '$tableName' table.
|
||||
*
|
||||
* $tableDesc
|
||||
*";
|
||||
if ($this->getBuildProperty('addTimeStamp')) {
|
||||
$now = strftime('%c');
|
||||
$script .= "
|
||||
* This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on:
|
||||
*
|
||||
* $now
|
||||
*";
|
||||
}
|
||||
$script .= "
|
||||
* You should add additional methods to this class to meet the
|
||||
* application requirements. This class will only be generated as
|
||||
* long as it does not already exist in the output directory.
|
||||
*
|
||||
* @package propel.generator.".$this->getPackage()."
|
||||
*/
|
||||
class ".$this->getClassname()." extends $baseClassname {
|
||||
";
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the methods that are added as part of the stub object class.
|
||||
*
|
||||
* By default there are no methods for the empty stub classes; override this method
|
||||
* if you want to change that behavior.
|
||||
*
|
||||
* @see ObjectBuilder::addClassBody()
|
||||
*/
|
||||
protected function addClassBody(&$script)
|
||||
{
|
||||
// there is no class body
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes class.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addClassClose(&$script)
|
||||
{
|
||||
$script .= "
|
||||
} // " . $this->getClassname() . "
|
||||
";
|
||||
}
|
||||
|
||||
} // PHP5ExtensionObjectBuilder
|
|
@ -1,112 +0,0 @@
|
|||
<?php
|
||||
|
||||
/**
|
||||
* This file is part of the Propel package.
|
||||
* For the full copyright and license information, please view the LICENSE
|
||||
* file that was distributed with this source code.
|
||||
*
|
||||
* @license MIT License
|
||||
*/
|
||||
|
||||
require_once 'builder/om/PeerBuilder.php';
|
||||
|
||||
/**
|
||||
* Generates the empty PHP5 stub node peer class for user object model (OM).
|
||||
*
|
||||
* This class produces the empty stub class that can be customized with application
|
||||
* business logic, custom behavior, etc.
|
||||
*
|
||||
* This class replaces the ExtensionNodePeer.tpl, with the intent of being easier for users
|
||||
* to customize (through extending & overriding).
|
||||
*
|
||||
* @author Hans Lellelid <hans@xmpl.org>
|
||||
* @package propel.generator.builder.om
|
||||
*/
|
||||
class PHP5ExtensionNodePeerBuilder extends PeerBuilder
|
||||
{
|
||||
|
||||
/**
|
||||
* Returns the name of the current class being built.
|
||||
* @return string
|
||||
*/
|
||||
public function getUnprefixedClassname()
|
||||
{
|
||||
return $this->getStubNodeBuilder()->getClassname() . 'Peer';
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds the include() statements for files that this class depends on or utilizes.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addIncludes(&$script)
|
||||
{
|
||||
$script .="
|
||||
require '".$this->getNodePeerBuilder()->getClassFilePath()."';
|
||||
";
|
||||
} // addIncludes()
|
||||
|
||||
/**
|
||||
* Adds class phpdoc comment and openning of class.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addClassOpen(&$script)
|
||||
{
|
||||
|
||||
$table = $this->getTable();
|
||||
$tableName = $table->getName();
|
||||
$tableDesc = $table->getDescription();
|
||||
|
||||
$baseClassname = $this->getNodePeerBuilder()->getClassname();
|
||||
|
||||
$script .= "
|
||||
|
||||
/**
|
||||
* Skeleton subclass for performing query and update operations on nodes of the '$tableName' table.
|
||||
*
|
||||
* $tableDesc
|
||||
*";
|
||||
if ($this->getBuildProperty('addTimeStamp')) {
|
||||
$now = strftime('%c');
|
||||
$script .= "
|
||||
* This class was autogenerated by Propel " . $this->getBuildProperty('version') . " on:
|
||||
*
|
||||
* $now
|
||||
*";
|
||||
}
|
||||
$script .= "
|
||||
* You should add additional methods to this class to meet the
|
||||
* application requirements. This class will only be generated as
|
||||
* long as it does not already exist in the output directory.
|
||||
*
|
||||
* @package propel.generator.".$this->getPackage()."
|
||||
*/
|
||||
class ".$this->getClassname()." extends $baseClassname {
|
||||
";
|
||||
}
|
||||
|
||||
/**
|
||||
* Specifies the methods that are added as part of the stub peer class.
|
||||
*
|
||||
* By default there are no methods for the empty stub classes; override this method
|
||||
* if you want to change that behavior.
|
||||
*
|
||||
* @see ObjectBuilder::addClassBody()
|
||||
*/
|
||||
|
||||
protected function addClassBody(&$script)
|
||||
{
|
||||
// there is no class body
|
||||
}
|
||||
|
||||
/**
|
||||
* Closes class.
|
||||
* @param string &$script The script will be modified in this method.
|
||||
*/
|
||||
protected function addClassClose(&$script)
|
||||
{
|
||||
$script .= "
|
||||
} // " . $this->getClassname() . "
|
||||
";
|
||||
}
|
||||
|
||||
} // PHP5ExtensionPeerBuilder
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
Reference in New Issue