1
0
mirror of synced 2024-12-13 06:46:03 +03:00

Reorganized utilities chapter. Moved pagination chapter to utilities. Created advanced layouts with pager and defined basic schema of extending customizing pager layout

This commit is contained in:
guilhermeblanco 2007-12-22 18:56:12 +00:00
parent 44929d5391
commit 091acf6a8e
10 changed files with 217 additions and 423 deletions

View File

@ -3,7 +3,6 @@
+ Basic schema mapping
+ Relations
+ Working with objects
+ Pagination
+ Component overview
+ Hierarchical data
+ Configuration

View File

@ -1,5 +0,0 @@
++ Introduction
++ Working with pager
++ Controlling range styles
++ Advanced layouts with pager
++ Customizing pager layout

View File

@ -1,34 +0,0 @@
TBD
Basic pager layout usage:
<code type="php">
// Creating pager layout
$pager_layout = new Doctrine_Pager_Layout(
new Doctrine_Pager(
Doctrine_Query::create()
->from( 'User u' )
->leftJoin( 'u.Group g' )
->orderby( 'u.username ASC' ),
$currentPage,
$resultsPerPage
),
new Doctrine_Pager_Range_Sliding(array(
'chunk' => 5
)),
'http://wwww.domain.com/app/User/list/page,{%page}'
);
// Assigning templates for page links creation
$pager_layout->setTemplate('[<a href="{%url}">{%page}</a>]');
$pager_layout->setSelectedTemplate('[{%page}]');
// Retireving Doctrine_Pager instance
$pager = $pager_layout->getPager();
// Fetching users
$users = $pager->execute();
// Displaying page links
echo $pager_layout->display();
</code>

View File

@ -1,78 +0,0 @@
There are some cases where simple paginations are not enough. One example situation is when you want to write page links listings.
To enable a more powerful control over pager, there is a small subset of pager package that allows you to create ranges.
Currently, Doctrine implements two types (or styles) of ranges: Sliding ({{Doctrine_Pager_Range_Sliding}}) and Jumping ({{Doctrine_Pager_Range_Jumping}}).
+++ Sliding
Sliding page range style, the page range moves smoothly with the current page. The current page is always in the middle, except in the first and last pages of the range.
Check out how does it work with a chunk length of 5 items:
<code>
Listing 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Page 1: o-------|
Page 2: |-o-----|
Page 3: |---o---|
Page 4: |---o---|
Page 5: |---o---|
Page 6: |---o---|
Page 7: |---o---|
Page 8: |---o---|
</code>
+++ Jumping
In Jumping page range style, the range of page links is always one of a fixed set of "frames": 1-5, 6-10, 11-15, and so on.
<code>
Listing 1 2 3 4 5 6 7 8 9 10 11 12 13 14
Page 1: o-------|
Page 2: |-o-----|
Page 3: |---o---|
Page 4: |-----o-|
Page 5: |-------o
Page 6: o---------|
Page 7: |-o-------|
Page 8: |---o-----|
</code>
Now that we know how the different of styles of pager range works, it's time to learn how to use them:
<code type="php">
$pager_range = new Doctrine_Pager_Range_Sliding(
array(
'chunk' => 5 // Chunk length
),
$pager // Doctrine_Pager object we learned how to create in previous topic
);
</code>
What is the advantage to use this object, instead of the {{Doctrine_Pager}}? Just one; it allows you to retrieve ranges around the current page.
Look at the example:
<code type="php">
// Retrieves the range around the current page
// In our example, we are using sliding style and we are at page 1
$pages = $pager_range->rangeAroundPage();
// Outputs: [1][2][3][4][5]
echo '['. implode('][', $pages) .']';
</code>
If you build your {{Doctrine_Pager}} inside the range object, the API gives you enough power to retrieve information related to {{Doctrine_Pager_Range}} subclass instance:
<code type="php">
// Return the Pager associated to this Pager_Range
$pager_range->getPager();
// Defines a new Doctrine_Pager (automatically call _initialize protected method)
$pager_range->setPager($pager);
// Return the options assigned to the current Pager_Range
$pager_range->getOptions();
// Return the range around the current page (obtained from Doctrine_Pager
// associated to the $pager_range instance)
$pager_range->rangeAroundPage();
</code>

View File

@ -1,4 +0,0 @@
In real world applications, display content from database tables is a commom task. Also, imagine that this content is a search result containing thousands of items. Undoubtely, it will be a huge listing, memory expensive and hard for users to find the right item. That is where some organization of this content display is needed and pagination comes in rescue.
Doctrine implements a highly flexible pager package, allowing you to not only split listing in pages, but also enabling you to control the layout of page links.
In this chapter, we'll learn how to create pager objects, control pager styles and at the end, overview the pager layout object - a powerful page links displayer of Doctrine.

View File

@ -1,69 +0,0 @@
Paginating queries is as simple as effectively do the queries itself. {{Doctrine_Pager}} is the responsible to process queries and paginate them. Check out this small piece of code:
<code type="php">
// Defining initial variables
$currentPage = 1;
$resultsPerPage = 50;
// Creating pager object
$pager = new Doctrine_Pager(
Doctrine_Query::create()
->from( 'User u' )
->leftJoin( 'u.Group g' )
->orderby( 'u.username ASC' ),
$currentPage, // Current page of request
$resultsPerPage // (Optional) Number of results per page. Default is 25
);
</code>
Until this place, the source you have is the same as the old {{Doctrine_Query}} object. The only difference is that now you have 2 new arguments. Your old query object plus these 2 arguments are now encapsulated by the {{Doctrine_Pager}} object.
At this stage, {{Doctrine_Pager}} already sent a dummy query to database to collect useful information to allow you to access them before even execute the real query. Let's say for example you want to know how many matches were found:
<code type="php">
echo 'Total of items found: ' . $pager->getNumResults();
</code>
There are a couple of other interesting information that can be retrieved from pager before you execute the query. The API usage is listed at the end of this topic.
To run the query, the process is similar to the current existent {{Doctrine_Query}} execute call. It even allow arguments the way you usually do it. Here is the PHP complete syntax, including the syntax of optional parameters:
<code type="php">
$pager->execute([$args = array() [, $fetchType = Doctrine::FETCH_RECORD]]);
</code>
If you need access the other functionalities that {{Doctrine_Pager}} provides, you can access them through the API:
<code type="php">
// Return the total number of itens found on query search
$pager->getNumResults();
// Return the first page (always 1)
$pager->getFirstPage();
// Return the total number of pages
$pager->getLastPage();
// Return the current page
$pager->getPage();
// Defines a new current page (automatically adjust offsets and values)
$pager->setPage($page);
// Return the next page
$pager->getNextPage();
// Return the previous page
$pager->getPreviousPage();
// Return true if it's necessary to paginate or false if not
$pager->haveToPaginate();
// Return the maximum number of records per page
$pager->getMaxPerPage();
// Defined a new maximum number of records per page (automatically adjust offset and values)
$pager->setMaxPerPage($maxPerPage);
// Return the Doctrine_Query object
$pager->getQuery();
</code>

View File

@ -1,235 +1,7 @@
++ Pagination
++ Facade
+++ Creating & Dropping Databases
Doctrine offers the ability to create and drop your databases from your defined Doctrine connections. The only trick to using it is that the name of your Doctrine connection must be the name of your database. This is required due to the fact that PDO does not offer a method for retrieving the name of the database you are connected to. So in order to create and drop the database Doctrine itself must be aware of the name of the database.
+++ Convenience Methods
Doctrine offers static convenience methods available in the main Doctrine class. These methods perform some of the most used functionality of Doctrine with one method. Most of these methods are using in the Doctrine_Task system. These tasks are also what are executed from the Doctrine_Cli.
<code type="php">
// Turn debug on/off and check for whether it is on/off
Doctrine::debug(true);
if (Doctrine::debug()) {
echo 'debugging is on';
} else {
echo 'debugging is off';
}
// Get the path to your Doctrine libraries
$path = Doctrine::getPath();
// Load your models so that they are present and loaded for Doctrine to work with
// Returns an array of the Doctrine_Records that were found and loaded
$models = Doctrine::loadModels('/path/to/models');
print_r($models);
// Get array of all the models loaded and present to Doctrine
$models = Doctrine::getLoadedModels();
// Pass an array of classes to the above method and it will filter out the ones that are not Doctrine_Records
$models = Doctrine::getLoadedModels(array('User', 'Formatter', 'Doctrine_Record'));
print_r($models); // would return array('User') because Formatter and Doctrine_Record are not Doctrine_Records
// Get Doctrine_Connection object for an actual table name
$conn = Doctrine::getConnectionByTableName('user'); // returns the connection object that the table name is associated with
// Generate your models from an existing database
Doctrine::generateModelsFromDb('/path/to/generate/models');
// Generate YAML schema from an existing database
Doctrine::generateYamlFromDb('/path/to/dump/schema.yml');
// Generate your models from YAML schema
Doctrine::generateModelsFromYaml('/path/to/schema.yml', '/path/to/generate/models');
// Create all your tables from an existing set of models
Doctrine::createTablesFromModels('/path/to/models');
// Create the tables supplied in the array
Doctrine::createTablesFromArray(array('User', 'Phoneumber'));
// Generate string of sql commands from an existing set of models
Doctrine::generateSqlFromModels('/path/to/models');
// Generate YAML schema from an existing set of models
Doctrine::generateYamlFromModels('/path/to/schema.yml', '/path/to/models');
// It is required your connection name to be the same as your database name in order for the drop/create functionality below to work.
// Create all databases for connections.
Doctrine::createDatabases();
// Drop all databases for connections
Doctrine::dropDatabases();
// Dump all data for your models to a yaml fixtures file
// 2nd argument is a bool value for whether or not to generate individual fixture files for each model. If true you need to specify a folder instead of a file.
Doctrine::dumpData('/path/to/dump/data.yml', true);
// Load data from yaml fixtures files
// 2nd argument is a bool value for whether or not to append the data when loading or delete all data first before loading
Doctrine::loadData('/path/to/fixture/files', true);
// Run a migration process for a set of migration classes
$num = 5; // migrate to version #5
Doctrine::migration('/path/to/migrations', $num);
// Generate a blank migration class template
Doctrine::generateMigrationClass('ClassName', '/path/to/migrations');
// Generate all migration classes for an existing database
Doctrine::generateMigrationsFromDb('/path/to/migrations');
// Generate all migration classes for an existing set of models
// 2nd argument is optional if you have already loaded your models using loadModels()
Doctrine::generateMigrationsFromModels('/path/to/migrations', '/path/to/models');
// Get Doctrine_Table instance for a model
$userTable = Doctrine::getTable('User');
// Compile doctrine in to a single php file
$drivers = array('mysql'); // specify the array of drivers you want to include in this compiled version
Doctrine::compile('/path/to/write/compiled/doctrine', $drivers);
// Dump doctrine objects for debugging
$conn = Doctrine_Manager::connection();
Doctrine::dump($conn);
</code>
+++ Tasks
Tasks are classes which bundle some of the core convenience methods in to tasks that can be easily executed by setting the required arguments. These tasks are directly used in the Doctrine command line interface.
<code>
BuildAll
BuildAllLoad
BuildAllReload
Compile
CreateDb
CreateTables
Dql
DropDb
DumpData
Exception
GenerateMigration
GenerateMigrationsDb
GenerateMigrationsModels
GenerateModelsDb
GenerateModelsYaml
GenerateSql
GenerateYamlDb
GenerateYamlModels
LoadData
LoadDummyData
Migrate
RebuildDb
</code>
You can read below about how to execute Doctrine Tasks standalone in your own scripts.
++ Command Line Interface
+++ Introduction
The Doctrine Cli is a collection of tasks that help you with your day to do development and testing with your Doctrine implementation. Typically with the examples in this manual, you setup php scripts to perform whatever tasks you may need. This Cli tool is aimed at providing an out of the box solution for those tasks.
+++ Tasks
Below is a list of available tasks for managing your Doctrine implementation.
<code>
./cli build-all
./cli build-all-load
./cli build-all-reload
./cli compile
./cli create-db
./cli create-tables
./cli dql
./cli drop-db
./cli dump-data
./cli generate-migration
./cli generate-migrations-from-db
./cli generate-migrations-from-models
./cli generate-models-from-db
./cli generate-models-from-yaml
./cli generate-sql
./cli generate-yaml-from-db
./cli generate-yaml-from-models
./cli load-data
./cli load-dummy-data
./cli migrate
./cli rebuild-db
</code>
The tasks for the CLI are separate from the CLI and can be used standalone. Below is an example.
<code type="php">
$task = new Doctrine_Task_GenerateModelsFromYaml();
$args = array('yaml_schema_path' => '/path/to/schema',
'models_path' => '/path/to/models');
$task->setArguments($args);
try {
if ($task->validate()) {
$task->execute();
}
} catch (Exception $e) {
throw new Doctrine_Exception($e->getMessage());
}
</code>
+++ Usage
File named "cli" that is set to executable
<code>
#!/usr/bin/env php
<?php
chdir(dirname(__FILE__));
include('cli.php');
</code>
Actual php file named "cli.php" that implements the Doctrine_Cli.
<code type="php">
// Include your Doctrine configuration/setup here, your connections, models, etc.
// Configure Doctrine Cli
// Normally these are arguments to the cli tasks but if they are set here the arguments will be auto-filled and are not required for you to enter them.
$config = array('data_fixtures_path' => '/path/to/data/fixtures',
'models_path' => '/path/to/models',
'migrations_path' => '/path/to/migrations',
'sql_path' => '/path/to/data/sql',
'yaml_schema_path' => '/path/to/schema');
$cli = new Doctrine_Cli($config);
$cli->run($_SERVER['argv']);
</code>
Now you can begin executing commands.
<code>
./cli generate-models-from-yaml
./cli create-tables
</code>
++ Sandbox
+++ Installation
Currently the only way you can install and use the sandbox is by svn. It is available by checking out the trunk of Doctrine. The sandbox comes loaded with generated models, sample schema files, data fixtures and a portable sqlite database to play with.
<code>
svn co http://doctrine.pengus.net/svn/trunk doctrine_trunk
cd doctrine_trunk/tools/sandbox
chmod 0777 cli
./cli
</code>
The above steps should give you a functioning sandbox. Execute the ./cli command without specifying a task will show you an index of all the available cli tasks in Doctrine.
++ Sandbox

View File

@ -0,0 +1,85 @@
+++ Introduction
The Doctrine Cli is a collection of tasks that help you with your day to do development and testing with your Doctrine implementation. Typically with the examples in this manual, you setup php scripts to perform whatever tasks you may need. This Cli tool is aimed at providing an out of the box solution for those tasks.
+++ Tasks
Below is a list of available tasks for managing your Doctrine implementation.
<code>
./cli build-all
./cli build-all-load
./cli build-all-reload
./cli compile
./cli create-db
./cli create-tables
./cli dql
./cli drop-db
./cli dump-data
./cli generate-migration
./cli generate-migrations-from-db
./cli generate-migrations-from-models
./cli generate-models-from-db
./cli generate-models-from-yaml
./cli generate-sql
./cli generate-yaml-from-db
./cli generate-yaml-from-models
./cli load-data
./cli load-dummy-data
./cli migrate
./cli rebuild-db
</code>
The tasks for the CLI are separate from the CLI and can be used standalone. Below is an example.
<code type="php">
$task = new Doctrine_Task_GenerateModelsFromYaml();
$args = array('yaml_schema_path' => '/path/to/schema',
'models_path' => '/path/to/models');
$task->setArguments($args);
try {
if ($task->validate()) {
$task->execute();
}
} catch (Exception $e) {
throw new Doctrine_Exception($e->getMessage());
}
</code>
+++ Usage
File named "cli" that is set to executable
<code>
#!/usr/bin/env php
<?php
chdir(dirname(__FILE__));
include('cli.php');
</code>
Actual php file named "cli.php" that implements the Doctrine_Cli.
<code type="php">
// Include your Doctrine configuration/setup here, your connections, models, etc.
// Configure Doctrine Cli
// Normally these are arguments to the cli tasks but if they are set here the arguments will be auto-filled and are not required for you to enter them.
$config = array('data_fixtures_path' => '/path/to/data/fixtures',
'models_path' => '/path/to/models',
'migrations_path' => '/path/to/migrations',
'sql_path' => '/path/to/data/sql',
'yaml_schema_path' => '/path/to/schema');
$cli = new Doctrine_Cli($config);
$cli->run($_SERVER['argv']);
</code>
Now you can begin executing commands.
<code>
./cli generate-models-from-yaml
./cli create-tables
</code>

View File

@ -0,0 +1,129 @@
+++ Creating & Dropping Databases
Doctrine offers the ability to create and drop your databases from your defined Doctrine connections. The only trick to using it is that the name of your Doctrine connection must be the name of your database. This is required due to the fact that PDO does not offer a method for retrieving the name of the database you are connected to. So in order to create and drop the database Doctrine itself must be aware of the name of the database.
+++ Convenience Methods
Doctrine offers static convenience methods available in the main Doctrine class. These methods perform some of the most used functionality of Doctrine with one method. Most of these methods are using in the Doctrine_Task system. These tasks are also what are executed from the Doctrine_Cli.
<code type="php">
// Turn debug on/off and check for whether it is on/off
Doctrine::debug(true);
if (Doctrine::debug()) {
echo 'debugging is on';
} else {
echo 'debugging is off';
}
// Get the path to your Doctrine libraries
$path = Doctrine::getPath();
// Load your models so that they are present and loaded for Doctrine to work with
// Returns an array of the Doctrine_Records that were found and loaded
$models = Doctrine::loadModels('/path/to/models');
print_r($models);
// Get array of all the models loaded and present to Doctrine
$models = Doctrine::getLoadedModels();
// Pass an array of classes to the above method and it will filter out the ones that are not Doctrine_Records
$models = Doctrine::getLoadedModels(array('User', 'Formatter', 'Doctrine_Record'));
print_r($models); // would return array('User') because Formatter and Doctrine_Record are not Doctrine_Records
// Get Doctrine_Connection object for an actual table name
$conn = Doctrine::getConnectionByTableName('user'); // returns the connection object that the table name is associated with
// Generate your models from an existing database
Doctrine::generateModelsFromDb('/path/to/generate/models');
// Generate YAML schema from an existing database
Doctrine::generateYamlFromDb('/path/to/dump/schema.yml');
// Generate your models from YAML schema
Doctrine::generateModelsFromYaml('/path/to/schema.yml', '/path/to/generate/models');
// Create all your tables from an existing set of models
Doctrine::createTablesFromModels('/path/to/models');
// Create the tables supplied in the array
Doctrine::createTablesFromArray(array('User', 'Phoneumber'));
// Generate string of sql commands from an existing set of models
Doctrine::generateSqlFromModels('/path/to/models');
// Generate YAML schema from an existing set of models
Doctrine::generateYamlFromModels('/path/to/schema.yml', '/path/to/models');
// It is required your connection name to be the same as your database name in order for the drop/create functionality below to work.
// Create all databases for connections.
Doctrine::createDatabases();
// Drop all databases for connections
Doctrine::dropDatabases();
// Dump all data for your models to a yaml fixtures file
// 2nd argument is a bool value for whether or not to generate individual fixture files for each model. If true you need to specify a folder instead of a file.
Doctrine::dumpData('/path/to/dump/data.yml', true);
// Load data from yaml fixtures files
// 2nd argument is a bool value for whether or not to append the data when loading or delete all data first before loading
Doctrine::loadData('/path/to/fixture/files', true);
// Run a migration process for a set of migration classes
$num = 5; // migrate to version #5
Doctrine::migration('/path/to/migrations', $num);
// Generate a blank migration class template
Doctrine::generateMigrationClass('ClassName', '/path/to/migrations');
// Generate all migration classes for an existing database
Doctrine::generateMigrationsFromDb('/path/to/migrations');
// Generate all migration classes for an existing set of models
// 2nd argument is optional if you have already loaded your models using loadModels()
Doctrine::generateMigrationsFromModels('/path/to/migrations', '/path/to/models');
// Get Doctrine_Table instance for a model
$userTable = Doctrine::getTable('User');
// Compile doctrine in to a single php file
$drivers = array('mysql'); // specify the array of drivers you want to include in this compiled version
Doctrine::compile('/path/to/write/compiled/doctrine', $drivers);
// Dump doctrine objects for debugging
$conn = Doctrine_Manager::connection();
Doctrine::dump($conn);
</code>
+++ Tasks
Tasks are classes which bundle some of the core convenience methods in to tasks that can be easily executed by setting the required arguments. These tasks are directly used in the Doctrine command line interface.
<code>
BuildAll
BuildAllLoad
BuildAllReload
Compile
CreateDb
CreateTables
Dql
DropDb
DumpData
Exception
GenerateMigration
GenerateMigrationsDb
GenerateMigrationsModels
GenerateModelsDb
GenerateModelsYaml
GenerateSql
GenerateYamlDb
GenerateYamlModels
LoadData
LoadDummyData
Migrate
RebuildDb
</code>
You can read below about how to execute Doctrine Tasks standalone in your own scripts.