sfDoctrineTablePlugin - 2.0.2

Custom base tables for Symfony models

You are currently browsing
the website for symfony 1

Visit the Symfony2 website


« Back to the Plugins Home

Signin


Forgot your password?
Create an account

Tools

Stats

advanced search
Information Readme Releases Changelog Contribute
Show source

sfDoctrineTablePlugin

The sfDoctrineTablePlugin generates feature packed base tables for models. Base table contains PHPDocs of available pre-generated WHERE, COUNT and JOIN methods, considering table relations and its depth. List of pre-generated PHPDoc methods are accessed through the @method annotation and is suitable for IDE users only (perfect implementation in NetBeans since v7.1)

Table of contents

  1. Description
  2. Screen-shot
  3. Installation
  4. Uninstall
  5. Setup
  6. Task
  7. How it works
  8. Extending the generator
  9. Known problem
  10. TDD
  11. Misc

Release notes

Plugin version v2.X.X has new API and is not compatible with v1.X.X. To install new major version you must uninstall current version. How to correctly uninstall plugin you can find in v1.X.X's README file.

1. Description

Plugin helps you not to keep in mind table relation aliases and escape from the constructing left and/or inner joins. It gives you ability to use pre-generated methods with IDE code-completion to speed-up your coding. Also, you can easy add your owns methods to the generator's template by extending it (see 8. Extending the generator).

2. Screenshot

Auto-completion in NetBeans

3. Installation

As symfony plugin

Installing

./symfony plugin:install sfDoctrineTablePlugin

Upgrading

cd plugins/sfDoctrineTablePlugin
git pull origin master
cd ../..

As GIT submodule (in general for plugin-developers - contains test suit)

Installation

git submodule add git://github.com/fruit/sfDoctrineTablePlugin.git plugins/sfDoctrineTablePlugin
git submodule init plugins/sfDoctrineTablePlugin

Upgrading

cd plugins/sfDoctrineTablePlugin
git pull origin master
cd ../..

4. Uninstall

Unusual uninstall process! First of all you should rollback your base table class inheritance and remove generated base table classes for models. All that you can make by executing:

./symfony doctrine:build-table --uninstall

In case, you had your own-custom table class (e.g. My_Doctrine_Table), you need to revert back it inherited by Doctrine_Table.

Then usual uninstall process:

./symfony plugin:uninstall sfDoctrineTablePlugin

Then, re-build your models, to be sure, all is O.K.

./symfony doctrine:build-model

5. Setup

5.1. Make sure plugin is enabled

<?php
 
class ProjectConfiguration extends sfProjectConfiguration
{
  public function setup ()
  {
    // … other plugins
    $this->enablePlugins('sfDoctrineTablePlugin');
  }
}

5.2. Configure

5.2.1 Plugin

In case you have your own-custom Doctrine_Table class (e.g. My_Doctrine_Table), then you need to make it inherited from class Doctrine_Table_Scoped, not from Doctrine_Table class. It can be done inside config/ProjectConfiguration.class.php:

<?php
 
class ProjectConfiguration extends sfProjectConfiguration
{
  // ...
 
  public function configureDoctrine (Doctrine_Manager $manager)
  {
    $manager->setAttribute(Doctrine_Core::ATTR_TABLE_CLASS, 'My_Doctrine_Table');
  }
}

Here is a default plugin configuration. All the configuration options are used to find all PHP files where you keep a business logic.

---
all:
  sfDoctrineTablePlugin:
    # Given below finder_* options used to find which methods
    # are used in your project and further remove then in production environment
    finder_search_in: [%SF_APPS_DIR%, %SF_LIB_DIR%]   # List of directories where business logic are located
    finder_prune_folders: [base, vendor]              # List of folders to prune
    finder_discard_folders: []                        # List of folders to discard
    finder_name: ["*.php"]                            # List of file-names to add
    finder_not_name: []                               # List of file-names to skip

5.2.1 Model

By the default base tables will be generated for all models and to for only enabled plugins that contains schema files. Occasionally, you won't use all models to query its data. Only some of them will be used to save data. In such cases is reasonable to disable such models from generating base tables. How to do that please refer to 6.5. Turning off base table generation for specific models.

According to my own experience, the most profit you will get in case you disable automatic relation detection (detect_relations: false) and setup only important to you relations by hand. Advantages to the solutions are clear and good-looking method names.

Here is a small schema.yml example:

---
detect_relations: false
 
Country:
  columns:
    id: { type: integer(4), primary: true, autoincrement: true }
    capital_city_id: { type: integer(4) }
    title: string(255)
  relations:
    Capital:
      class: City
      local: capital_city_id
      foreign: id
      type: one
      foreignType: one
      foreignAlias: CapitalOfTheCountry
 
City:
  columns:
    id: { type: integer(4), primary: true, autoincrement: true }
    country_id: { type: integer(4) }
    title: string(255)
  relations:
    Country:
      foreignAlias: Cities

After executing doctrine:build-tables you can see following methods beside other methods:

<?php
 
$q = CityTable::getInstance()->createQuery('ci');
CityTable::getInstance()
  ->withInnerJoinOnCountry($q)
  ->withLeftJoinOnCapitalViaCountry($q)
  ->withLeftJoinOnCapitalOfTheCountryViaCountryAndCapital($q);

The generated SQL ($q->getSqlQuery()) will looks like:

SELECT
  c.id AS c__id, c.country_id AS c__country_id, c.title AS c__title,
  c2.id AS c2__id, c2.capital_city_id AS c2__capital_city_id, c2.title AS c2__title,
  c3.id AS c3__id, c3.country_id AS c3__country_id, c3.title AS c3__title,
  c4.id AS c4__id, c4.capital_city_id AS c4__capital_city_id, c4.title AS c4__title
FROM city c
  INNER JOIN country c2 ON c.country_id = c2.id
  LEFT JOIN city c3 ON c2.capital_city_id = c3.id
  LEFT JOIN country c4 ON c3.id = c4.capital_city_id

And DQL ($q->getDql()) will looks like:

FROM City ci
  INNER JOIN ci.Country c
  LEFT JOIN c.Capital c_c
  LEFT JOIN c_c.CapitalOfTheCountry c_c_cotc

6. Task

6.1 Usage

./symfony doctrine:build-table [model1] ... [modelN] \
    [--application[="..."]] \
    [--env="..."] \
    [--generator-class="..."] \
    [-d|--depth="..."] \
    [-m|--minified] \
    [-n|--no-phpdoc] \
    [-u|--uninstall] \
    [-f|--no-confirmation]

For full task details, please refer to the task help block:

./symfony help doctrine:build-table

6.2 Build base tables

Run this task each time you update the schema.yml file and rebuild the models:

./symfony doctrine:build-table

6.3 Customize JOIN's deepness

By the default JOIN's deepness is set to 3 (superfluously enough), but you can adjust it by passing flag --depth. The level of depth does not affects on speed in production environment (see Optimize tables for production):

./symfony doctrine:build-table --depth=4

6.4 Optimize tables for production

When you deploy your code to production server, you can minimize generated base table file size by passing flag --no-phpdoc (e.i. base tables without @method hints) and combining with --minified (e.i. do not generate methods, that aren't used in project).

./symfony doctrine:build-table --env=prod --minified --no-phpdoc

6.5. Turning off base table generation for specific models

By the default doctrine:build-model task will generate base tables for each existing-active model, unless you disable it. To disable model you need to set table value to be false: table: false for specific model in schema.yml file:

---
Book:
  options:
    symfony: { table: false }

Then rebuild models by executing:

./symfony doctrine:build-model

And then, generate an updated version of base tables:

./symfony doctrine:build-table

There are some nuances to keep in mind. When you disable model(-s), which base table(-s) was generated before, task doctrine:build-table will uninstall disabled base table automatically.

6.6. Base tables generation for a specific models

Now you can pass manually a list of models you would like to generate the base tables

./symfony doctrine:build-table City Country

The same principle to uninstall a specific models:

./symfony doctrine:build-table --uninstall City Country

7. How it works

All is very tricky. Each available method for code-completion does not contains code at all. That is - no extra code, smallest file size. Things are done by implementing PHPDoc annotation @method.

Here is code sample of generated base table for model City - file BaseCityTable.class.php preview on http://pastie.org/private/gvwhdvyyakiofbtskuog3w

As you can observe, file contains additional @c annotations:

<?php
 
/**
 * ...
 * @c(m=withLeftJoinOnSection,o=s,f=^,ra=Section,c=buildLeft)
 * @c(m=withInnerJoinOnSection,o=s,f=^,ra=Section,c=buildInner)
 * ...
 * @c(m=withLeftJoinOnPostMediaImageViaImagesAndTranslations,o=is_ts_pmi,f=is_ts,ra=PostMediaImage,c=buildLeft)
 * @c(m=withInnerJoinOnPostMediaImageViaImagesAndTranslations,o=is_ts_pmi,f=is_ts,ra=PostMediaImage,c=buildInner)
 * ...
 **/

This information helps to build requested method on the fly by implementing magic method __call. Parsing PHPDoc on the fly is fast (< 0.003 sec) even the base table is not minified and contains @method hints (about 700kb).

Minified base tables (see Optimize tables for production) are much smaller (about < 4kb) and parsing is much faster (< 0.0001 sec).

8. Extending the generator

Copy the default generator skeleton folder to your project:

cp -R plugins/sfDoctrineTablePlugin/data/generator/ data/.

Then, create a new generator class (e.g. MyDoctrineTableGenerator) by extending it from sfDoctrineTableGenerator class. And use it when you run doctrine:build-table task by passing --generator-class option:

./symfony doctrine:build-table --depth=2 --generator-class=MyDoctrineTableGenerator

That's all.

9. Known problem

Joined table aliases may change when existing relation is removed or new relations are added before existing one. It happens due to aliases are generated based on component name.

For example model owns 2 relations "Company" and "Category":

---
Article:
  relations:
    Company:
      class: Company
      local: article_id
    Category:
      class: Category
      local: category_id

Assume we need to join both tables "Company" and "Category" from the table "Article".

<?php
 
$q = ArticeTable::getInstance()->createQuery('a');
ArticeTable::getInstance()
  ->withInnerJoinOnCompany($q)
  ->withInnerJoinOnCategory($q)
;
 
$q->select('a.*, c.title, ca.slug')->execute();

All relations starts with "C", this mean that joined "Company" table maps to "c" and "Category" maps to the "ca" (due to "c" is used).

You have made a database re-factoring and relation "Company" was removed. Next step is to fix the query given above by removing all things related to a "Company":

<?php
 
$q = ArticeTable::getInstance()->createQuery('a');
ArticeTable::getInstance()
  ->withInnerJoinOnCategory($q)
;
 
$q->select('a.*, ca.slug')->execute();

Code will be erroneous, because the new generated alias for table "Category" maps to the letter "c". So, to fix code sample, you need to replace "ca.slug" with "c.slug".

<?php
 
$q->select('a.*, c.slug')->execute();

If anybody can elegantly help me to solve this issue - I will be pleasantly thankful.

10. TDD

The basic functionality is tested.

[sfDoctrineTable] functional/backend/MethodExistanceTest.............ok
[sfDoctrineTable] functional/backend/MethodWhereTest.................ok
[sfDoctrineTable] functional/backend/TaskDepthTest...................ok
[sfDoctrineTable] functional/backend/TaskGeneratorTest...............ok
[sfDoctrineTable] functional/backend/TaskInvalidArgumentsTest........ok
[sfDoctrineTable] functional/backend/TaskMinifiedTest................ok
[sfDoctrineTable] functional/backend/TaskNoPhpDocTest................ok
[sfDoctrineTable] functional/backend/TaskUninstallTest...............ok
 All tests successful.
 Files=8, Tests=149

11. Misc

Requirements

Contacts

  • @: Ilya Sabelnikov <fruit dot dev at gmail dot com>
  • skype: ilya_roll