Commit 2f66d604 authored by Jonathan.Wage's avatar Jonathan.Wage

Initial entry of sfDoctrinePlugin.

parent 9fbde039
Copyright (c) 2004-2006 Fabien Potencier
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.
sfDoctrine symfony plugin
=========================
Overview
--------
The sfDoctrine plugin allows you to totally replace propel with doctrine (http://www.phpdoctrine.com/) which is a powerful and easy-to-use ORM.
Contents
--------
This plugin contains:
- necessary tools to use doctrine: the main tool is sfDoctrine::getTable() which will allow you to send queries
- pake tasks that convert between doctrine and propel schema formats and build doctrine model classes automatically
- an admin generator: to use it just specify sfDoctrineAdmin as the main class in your generator.yml config
You will find more information in the wiki page dedicated to sfDoctrine: http://www.symfony-project.com/trac/wiki/sfDoctrine.
License
-------
For the full copyright and license information, please view the LICENSE
file that was distributed with this source code.
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineDatabaseSchema.class.php 3455 2007-02-14 16:17:48Z chtito $
*/
/*
- class: contains a bunch of columns, toMany relationships, inheritance
information, i18n information
- table: a special class that is actually a table
- column: contains the doctrine properties (name, type, size) and the toOne relation information
*/
class sfDoctrineDatabaseSchema
{
// the class descriptions
protected $classes = array();
// a subset of the array above: classes which are also tables
protected $tables = array();
public function getClasses()
{
return $this->classes;
}
protected function getClass($className)
{
if (isset($this->classes[$className]))
return $this->classes[$className];
throw new sfDoctrineSchemaException(sprintf('The class "%s" has no description', $className));
}
// retrieves a class object from its table name
protected function findClassByTableName($tableName)
{
foreach ($this->tables as $table)
if ($table->getName() == $tableName)
{
$tableClasses = $table->getClasses();
if (count($tableClasses) != 1)
throw new sfDoctrineSchemaException(sprintf('No unique class is associated to table "%s"', $tableName));
return array_pop($tableClasses);
}
throw new sfDoctrineSchemaException(sprintf('Table "%s" not found', $tableName));
}
// set the one to many and many to many relationships
// finds out what are the foreign classes or foreign tables
protected function fixRelationships()
{
foreach ($this->classes as $className => $class)
{
foreach ($class->getColumns() as $relCol)
if ($relation = $relCol->getRelation())
{
// if no foreignClass was specified (import from propel) we find it out
if (!$relation->get('foreignClass'))
{
$foreignClass = $this->findClassByTableName($relation->get('foreignTable'));
$relation->set('foreignClass', $foreignClass->getPhpName());
}
// if foreignTable was not set (only used for export to propel)
// we figure it out
if (!$relation->get('foreignTable'))
{
$className = $relation->get('foreignClass');
$relation->set('foreignTable', $this->getClass($className)->getTableName());
}
// the relation is a many2many
if ($relation->get('counterpart'))
{
$counterpartRel = $class->getRelation($relation->get('counterpart'));
$relation->set('otherClass', $counterpartRel->get('foreignClass'));
}
// we copy all the toOne relations to the corresponding
// foreign class
$rel = $relCol->getRelation();
$this->getClass($rel->get('foreignClass'))->addToMany($rel); // FIXME: don't copy here
}
}
}
// exports the current schema as a propel xml file
public function asPropelXml()
{
$xml = new SimpleXmlElement(sprintf('<?xml version="1.0" encoding="UTF-8" ?>
<database name="%s" defaultIdMethod="native"></database>', 'connection'));
foreach ($this->tables as $table)
{
$table->addPropelXmlClasses($xml);
}
return array('source'=>$xml->asXml());
}
// exports the current schema in a sfDoctrine yml file
public function asDoctrineYml()
{
$ymlClasses = array();
foreach ($this->classes as $class)
{
$ymlClasses[$class->getPhpName()] = $class->asDoctrineYml();
}
return array('source'=>sfYaml::dump($ymlClasses));
}
public function debug()
{
$debug = array();
foreach ($this->classes as $class)
{
$debug[$class->getPhpName()] = $class->debug();
}
return $debug;
}
}
class sfDoctrineSchemaException extends sfException
{
public function __construct($message = null, $code = 0)
{
$this->setName('sfDoctrineSchemaException');
parent::__construct($message, $code);
}
}
\ No newline at end of file
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineRelationSchema.class.php 4705 2007-07-24 20:45:46Z Jonathan.Wage $
*/
class sfDoctrineRelationSchema
{
protected $relationInfo = array();
public function __construct($relationInfo)
{
foreach ($relationInfo as $key => $value)
{
$this->set($key, $value);
}
}
public function set($key, $value)
{
// we set the default foreign name
if ($key == 'foreignClass')
{
if (!isset($this->relationInfo['foreignName']))
{
$this->relationInfo['foreignName'] = $value;
}
}
$this->relationInfo[$key] = $value;
}
public function get($key)
{
if (isset($this->relationInfo[$key]))
{
return $this->relationInfo[$key];
}
else if (isset($this->relationInfo['options']))
{
if ($option = $this->relationInfo['options']->get($key))
{
return $option;
}
}
return null;
}
public function asDoctrineYml()
{
$output = array();
foreach(array('foreignClass', 'foreignReference', 'localName', 'foreignName', 'cascadeDelete', 'unique') as $key)
{
if ($value = $this->get($key))
{
$output[$key] = $value;
}
}
// FIXME: this is clumsy: change the schema syntax?
if ($verb == 'owns')
{
$output['cascadeDelete'] = true;
}
return $output;
}
public function asPhpArray($array)
{
$phpArray = 'array(';
if( !empty($array) )
{
foreach($array AS $key => $value)
{
$phpArray .= "'{$key}' => '{$value}', ";
}
$phpArray = substr($phpArray, 0, strlen($phpArray) - 2);
}
$phpArray .= ')';
return $phpArray;
}
public function asOnePhp()
{
// special behaviour for xref tables with cascade delete
$verb = ($this->get('cascadeDelete') && ($this->get('counterpart') || $this->get('unique'))) ? 'owns' : 'has';
$options['local'] = $this->get('localReference');
$options['foreign'] = $this->get('foreignReference');
//support old and new cascade declarations
if ($verb == 'owns' || $this->get('cascadeDelete') === true)
{
$options['onDelete'] = 'CASCADE';
}
if ($this->get('onDelete'))
{
$options['onDelete'] = strtoupper($this->get('onDelete'));
}
$phpOptions = $this->asPhpArray($options);
return "\$this->$verb"."One('{$this->get('foreignClass')} as {$this->get('foreignName')}', $phpOptions);";
}
public function asManyPhp()
{
$quantity = $this->get('unique') ? 'One':'Many';
// using "owns" for cascade delete except in xref table
$verb = ($this->get('cascadeDelete') && !$this->get('counterpart')) ? 'has':'has';
$otherClass = $this->get('localClass');
if ($quantity == 'Many' && $this->get('counterpart'))
{
$localReference = $this->relationInfo['localReference'];
$foreignReference = $this->relationInfo['options']->get('counterpart');
$otherClass = $this->get('otherClass');
} else {
$localReference = $this->get('foreignReference');
$foreignReference = $this->get('localReference');
}
$localClass = $this->get('localClass');
// Set refClass to localClass if it is a Many-Many relationship
if ($quantity == 'Many' && $this->get('counterpart'))
{
$refClass = $this->get('localClass');
}
if (isset($refClass) && $refClass)
{
$options['refClass'] = $refClass;
}
if ($localReference)
{
$options['local'] = $localReference;
}
if ($foreignReference)
{
$options['foreign'] = $foreignReference;
}
$phpOptions = $this->asPhpArray($options);
return "\$this->$verb$quantity('$otherClass as {$this->get('localName')}', $phpOptions);";
}
public function debug()
{
return $this->relationInfo;
}
}
\ No newline at end of file
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineSchemaDoctrineLoader.class.php 3455 2007-02-14 16:17:48Z chtito $
*/
class sfDoctrineSchemaDoctrineLoader extends sfDoctrineDatabaseSchema
{
// recursively finds out what a class table is
// FIXME: check for infinite loop?
protected function parentTable($class)
{
if ($class->hasTable())
return $class->getTable();
return $this->parentTable($this->getClass($class->getParentClassName()));
}
// associate a table to each class
protected function fixTables()
{
foreach ($this->classes as $className => $class)
{
$table = $this->parentTable($class);
$table->addClass($class);
}
}
// set up the necessary fields in the i18n table: culture, id
protected function addI18nFields()
{
foreach ($this->classes as $className => $class)
{
if (!$class->hasI18n())
continue;
$i18nClass = $this->getClass($class->getI18n('class'));
$cultureColumn = new sfDoctrineColumnSchema($class->getI18n('cultureField'), array('type'=> 'string', 'size'=> 100, 'primary'=> true));
$i18nClass->addColumn($cultureColumn);
// add the foreign key to the main table
$idDesc = array('foreignClass'=>$className, 'localName'=>$i18nClass->getPhpName(), 'onDelete'=>'cascade', 'primary'=>true);
$i18nClass->addColumn(new sfDoctrineColumnSchema('id', $idDesc));
}
}
// adds the class key fields
protected function addInheritanceFields()
{
foreach ($this->classes as $className => $class)
if ($class->hasOneTableInheritance())
{
$inh = $class->getInheritance();
$class->getTable()->addColumn(new sfDoctrineColumnSchema($inh['keyField'], array('type'=>'integer')));
}
}
public function load($file, $package = null)
{
$schema = sfYaml::load($file);
foreach ($schema as $className => $cd)
{
if (!isset($cd['tableName']) && !isset($cd['inheritance']))
throw new sfDoctrineSchemaException(sprintf('Class "%s" must have either a table or a parent', $className));
$class = new sfDoctrineClassSchema($className, $cd);
// add a table if necessary
if (isset($cd['tableName']))
{
// this top class is actually a table
$table = new sfDoctrineTableSchema($cd['tableName'], $package);
$table->addClass($class);
$this->tables[$cd['tableName']] = $table;
}
$this->classes[$className] = $class;
}
}
public function process()
{
$this->fixTables();
$this->addI18nFields();
$this->fixRelationships();
$this->addInheritanceFields();
}
}
\ No newline at end of file
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineSchemaPropelLoader.class.php 3455 2007-02-14 16:17:48Z chtito $
*/
class sfDoctrineSchemaPropelLoader extends sfDoctrineDatabaseSchema
{
// get the attributes parsed by the sfPropelDatabaseSchema class
protected function getAttribute($tag, $attribute)
{
return isset($tag['_attributes'][$attribute]) ? $tag['_attributes'][$attribute] : null;
}
public function load($file, $package = null)
{
// we figure out what kind of file we are given
$type = array_pop(explode('.', $file));
$type2method = array('yml'=>'loadYAML', 'xml'=>'loadXML');
if (isset($type2method[$type]))
$method = $type2method[$type];
else
throw new sfDoctrineSchemaException(sprintf('Unkwnown method for extension "%s"', $type));
$propelDatabaseSchema = new sfPropelDatabaseSchema();
$propelDatabaseSchema->$method($file);
$data = $propelDatabaseSchema->asArray();
foreach ($propelDatabaseSchema->getTables() as $tb_name => $tableDesc)
{
// special table class
// propel has only such classes (no inheritance support)
$table = new sfDoctrineTableSchema($tb_name, $package);
$this->tables[$tb_name] = $table;
if (!($className = $this->getAttribute($tableDesc, 'phpName')))
$className = sfInflector::camelize($tb_name); // wild guess
$class = new sfDoctrineClassSchema($className);
$table->addClass($class);
// columns
foreach ($propelDatabaseSchema->getChildren($tableDesc) as $col_name => $columnDescription)
{
if (($col_name == 'id')) // id is automatically generated in doctrine
continue;
$docCol = new sfDoctrineColumnSchema($col_name, $columnDescription, true);
$class->addColumn($docCol);
}
$this->classes[$class->getPhpName()] = $class;
}
}
public function process()
{
$this->fixRelationships();
}
}
\ No newline at end of file
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineTableSchema.class.php 3455 2007-02-14 16:17:48Z chtito $
*/
class sfDoctrineTableSchema extends sfDoctrineClassSchema
{
// the classes associated to that table
protected $classes;
// table name
protected $name;
// package of that table (usually either a plugin name, or a propel schema name)
protected $package;
public function getName()
{
return $this->name;
}
public function setName($name)
{
$this->name = $name;
}
public function __construct($tableName, $package)
{
$this->setName($tableName);
$this->package = $package;
}
public function addClass($class)
{
// we add the class and try to avoid duplication
$this->classes[$class->getPhpName()] = $class;
$class->setTable($this);
}
public function getClasses()
{
return $this->classes;
}
// exports this table in propel xml format
public function addPropelXmlClasses(&$node)
{
$t = $node->addChild('table');
$t->addAttribute('name', $this->getName());
$t->addAttribute('phpName', $this->getPhpName());
foreach($this->classes as $class)
{
$class->addPropelXmlColumns($t);
}
}
public function getPackage()
{
return $this->package;
}
}
autoload:
# Doctrine:
# name: Doctrine classes
# ext: .php
# path: %SF_PLUGINS_DIR%/sfDoctrine/doctrine
# recursive: on
doctrine_model_classes:
name: Doctrine model classes
ext: .class.php
path: %SF_LIB_DIR%/model/doctrine
\ No newline at end of file
config/doctrine.yml:
class: sfDoctrineConfigHandler
config/schemas.yml:
class: sfDoctrineSchemasConfigHandler
all:
#doctrine attributes
attributes:
#automatic table creation (none, tables, constraints, all)
export: all
#default fetch mode (immediate, batch, lazy, offset, lazy_offset)
# fetchmode: immediate
#collection limit (integer 1+)
# coll_limit: 5
#global event listener
# listener: sfDoctrineEventListener
#enable doctrine side validation (true, false)
validate: false
# enable quoting
quote_identifier: false
all:
orm: doctrine
# default_database: <your default connection here>
\ No newline at end of file
<?php
/**
* ##MODULE_NAME## actions.
*
* @package ##PROJECT_NAME##
* @subpackage ##MODULE_NAME##
* @author ##AUTHOR_NAME##
* @version SVN: $Id: actions.class.php,v 1.1 2006/12/08 18:49:35 nathanael Exp $
*/
class ##MODULE_NAME##Actions extends auto##MODULE_NAME##Actions
{
}
generator:
class: sfDoctrineAdminGenerator
param:
model_class: ##MODEL_CLASS##
theme: crud
[?php
/**
* <?php echo $this->getGeneratedModuleName() ?> actions.
*
* @package ##PROJECT_NAME##
* @subpackage <?php echo $this->getGeneratedModuleName() ?>
* @author Fabien Potencier <fabien.potencier@symfony-project.com>
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: actions.class.php 3923 2007-05-03 19:42:33Z gnat $
*/
class <?php echo $this->getGeneratedModuleName() ?>Actions extends sfActions
{
public function executeIndex ()
{
return $this->forward('<?php echo $this->getModuleName() ?>', 'list');
}
public function executeList ()
{
$this-><?php echo $this->getPluralName() ?> = sfDoctrine::getTable('<?php echo $this->getClassName() ?>')->findAll();
}
public function executeShow ()
{
$this-><?php echo $this->getSingularName() ?> = sfDoctrine::getTable('<?php echo $this->getClassName() ?>')->find(<?php echo $this->getRetrieveByPkParamsForAction('') ?>);
$this->forward404Unless($this-><?php echo $this->getSingularName() ?>);
}
public function executeCreate ()
{
$this-><?php echo $this->getSingularName() ?> = new <?php echo $this->getClassName() ?>();
$this->setTemplate('edit');
}
public function executeEdit ()
{
$this-><?php echo $this->getSingularName() ?> = sfDoctrine::getTable('<?php echo $this->getClassName() ?>')->find(<?php echo $this->getRetrieveByPkParamsForAction('') ?>);
$this->forward404Unless($this-><?php echo $this->getSingularName() ?>);
}
public function executeDelete ()
{
$this-><?php echo $this->getSingularName() ?> = sfDoctrine::getTable('<?php echo $this->getClassName() ?>')->find(<?php echo $this->getRetrieveByPkParamsForAction('') ?>);
$this->forward404Unless($this-><?php echo $this->getSingularName() ?>);
try
{
$this-><?php echo $this->getSingularName() ?>->delete();
$this->redirect('<?php echo $this->getModuleName() ?>/list');
}
catch (Doctrine_Exception $e)
{
$this->getRequest()->setError('delete', 'Could not delete the selected <?php echo sfInflector::humanize($this->getSingularName()) ?>. Make sure it does not have any associated items.');
return $this->forward('<?php echo $this->getModuleName() ?>', 'list');
}
}
public function executeUpdate ()
{
if (<?php echo $this->getTestPksForGetOrCreate(false) ?>)
{
$<?php echo $this->getSingularName() ?> = new <?php echo $this->getClassName() ?>();
}
else
{
$<?php echo $this->getSingularName() ?> = sfDoctrine::getTable('<?php echo $this->getClassName() ?>')->find(<?php echo $this->getRetrieveByPkParamsForAction('') ?>);
$this->forward404Unless($<?php echo $this->getSingularName() ?>);
}
$formData = $this->getRequestParameter('<?php echo $this->getSingularName() ?>');
<?php foreach ($this->getColumns('') as $index => $column):
$type = $column->getDoctrineType();
$name = $column->getName(); ?>
<?php if($column->isPrimaryKey()) continue ?>
<?php if ($name == 'created_at' || $name == 'updated_at') continue ?>
<?php if ($type == 'boolean'): ?>
<?php $boolVar = "\$formData['$name']";
echo $this->getColumnSetter($column, "isset($boolVar) ? $boolVar : 0", false, '')?>;
<?php continue; ?>
<?php endif; // boolean case ?>
if ($newValue = $formData['<?php echo $name ?>'])
{
<?php if ($type == 'date' || $type == 'timestamp'): ?>
<?php $inputPattern = ($type == 'date' ? 'd' : 'g');
$outputPattern = ($type == 'date' ? 'i' : 'I'); ?>
$dateFormat = new sfDateFormat($this->getUser()->getCulture());
<?php echo $this->getColumnSetter($column, sprintf('$dateFormat->format($newValue, \'%s\', $dateFormat->getInputPattern(\'%s\'))', $outputPattern, $inputPattern), false, '');?>;
<?php elseif ($column->isForeignKey()): ?>
$<?php echo $this->getSingularName()?>->set('<?php echo $column->getColumnName()?>', (empty($newValue) ? null : $newValue));
<?php else: ?>
<?php echo $this->getColumnSetter($column, '$newValue', false, '');?>;
<?php endif; ?>
}
<?php endforeach; ?>
$<?php echo $this->getSingularName() ?>->save();
return $this->redirect('<?php echo $this->getModuleName() ?>/show?<?php echo $this->getPrimaryKeyUrlParams() ?>);
<?php //' ?>
}
}
[?php use_helper('ObjectDoctrineAdmin', 'Object', 'Date') ?]
[?php echo form_tag('<?php echo $this->getModuleName() ?>/update', 'multipart=true') ?]
<?php foreach ($this->getPrimaryKey() as $pk): ?>
[?php echo object_input_hidden_tag($<?php echo $this->getSingularName() ?>, 'get<?php echo $pk->getPhpName() ?>') ?]
<?php endforeach; ?>
<table>
<tbody>
<?php foreach ($this->getColumns('') as $index => $column): ?>
<?php if ($column->isPrimaryKey()) continue ?>
<?php if ($column->getName() == 'created_at' || $column->getName() == 'updated_at') continue ?>
<tr>
<th><?php echo sfInflector::humanize(sfInflector::underscore($column->getPhpName())) ?>: </th>
<td>[?php echo <?php echo $this->getColumnEditTag($column) ?> ?]</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<hr />
[?php echo submit_tag('save') ?]
[?php if (<?php echo $this->getPrimaryKeyIsSet() ?>): ?]
&nbsp;[?php echo link_to('delete', '<?php echo $this->getModuleName() ?>/delete?<?php echo $this->getPrimaryKeyUrlParams() ?>, 'post=true&confirm=Are you sure?') ?]
&nbsp;[?php echo link_to('cancel', '<?php echo $this->getModuleName() ?>/show?<?php echo $this->getPrimaryKeyUrlParams() ?>) ?]
[?php else: ?]
&nbsp;[?php echo link_to('cancel', '<?php echo $this->getModuleName() ?>/list') ?]
[?php endif; ?]
</form>
<h1><?php echo $this->getModuleName() ?></h1>
<table>
<thead>
<tr>
<?php foreach ($this->getColumns('') as $column): ?>
<th><?php echo sfInflector::humanize($column->getName()) ?></th>
<?php endforeach; ?>
</tr>
</thead>
<tbody>
[?php foreach ($<?php echo $this->getPluralName() ?> as $<?php echo $this->getSingularName() ?>): ?]
<tr>
<?php foreach ($this->getColumns('') as $column): ?>
<?php if ($column->isPrimaryKey()): ?>
<td>[?php echo link_to($<?php echo $this->getSingularName() ?>->get('<?php echo $column->getPhpName() ?>'), '<?php echo $this->getModuleName() ?>/show?<?php echo $this->getPrimaryKeyUrlParams() ?>); ?]</td>
<?php else: ?>
<td>[?php echo $<?php echo $this->getSingularName() ?>->get('<?php echo $column->getPhpName() ?>'); ?]</td>
<?php endif; ?>
<?php endforeach; ?>
</tr>
[?php endforeach; ?]
<tr><td>Number of <?php echo $this->getPluralName() ?>: [?php echo count($<?php echo $this->getPluralName()?>) ?]</td></tr>
</tbody>
</table>
[?php echo link_to ('create', '<?php echo $this->getModuleName() ?>/create') ?]
<table>
<tbody>
<?php foreach ($this->getAllColumns() as $column): ?>
<tr>
<th><?php echo sfInflector::humanize(sfInflector::underscore($column->getPhpName())) ?>: </th>
<td>[?= $<?php echo $this->getSingularName() ?>->get<?php echo $column->getPhpName() ?>() ?]</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<hr />
[?php echo link_to('edit', '<?php echo $this->getModuleName() ?>/edit?<?php echo $this->getPrimaryKeyUrlParams() ?>) ?]
&nbsp;[?php echo link_to('list', '<?php echo $this->getModuleName() ?>/list') ?]
<?php
/**
* ##MODULE_NAME## actions.
*
* @package ##PROJECT_NAME##
* @subpackage ##MODULE_NAME##
* @author Your name here
* @version SVN: $Id: actions.class.php 1415 2006-06-11 08:33:51Z fabien $
*/
class ##MODULE_NAME##Actions extends auto##MODULE_NAME##Actions
{
}
generator:
class: sfDoctrineAdminGenerator
param:
model_class: ##MODEL_CLASS##
theme: default
<ul class="sf_admin_actions">
<?php $editActions = $this->getParameterValue('edit.actions') ?>
<?php if (null !== $editActions): ?>
<?php foreach ((array) $editActions as $actionName => $params): ?>
<?php if ($actionName == '_delete') continue ?>
<?php echo $this->addCredentialCondition($this->getButtonToAction($actionName, $params, true), $params) ?>
<?php endforeach; ?>
<?php else: ?>
<?php echo $this->getButtonToAction('_list', array(), true) ?>
<?php echo $this->getButtonToAction('_save', array(), true) ?>
<?php echo $this->getButtonToAction('_save_and_add', array(), true) ?>
<?php endif; ?>
</ul>
[?php echo form_tag('<?php echo $this->getModuleName() ?>/save', array(
'id' => 'sf_admin_edit_form',
'name' => 'sf_admin_edit_form',
'multipart' => true,
<?php foreach ($this->getColumnCategories('edit.display') as $category): ?>
<?php foreach ($this->getColumns('edit.display', $category) as $name => $column): ?>
<?php if (false !== strpos($this->getParameterValue('edit.fields.'.$column->getName().'.type'), 'admin_double_list')): ?>
'onsubmit' => 'double_list_submit(); return true;'
<?php break 2; ?>
<?php endif; ?>
<?php endforeach; ?>
<?php endforeach; ?>
)) ?]
<?php foreach ($this->getPrimaryKey() as $pk): ?>
[?php echo object_input_hidden_tag($<?php echo $this->getSingularName() ?>, 'get<?php echo $pk->getPhpName() ?>') ?]
<?php endforeach; ?>
<?php $first = true ?>
<?php foreach ($this->getColumnCategories('edit.display') as $category): ?>
<?php
if ($category[0] == '-')
{
$category_name = substr($category, 1);
$collapse = true;
if ($first)
{
$first = false;
echo "[?php use_javascript(sfConfig::get('sf_prototype_web_dir').'/js/prototype') ?]\n";
echo "[?php use_javascript(sfConfig::get('sf_admin_web_dir').'/js/collapse') ?]\n";
}
}
else
{
$category_name = $category;
$collapse = false;
}
?>
<fieldset id="sf_fieldset_<?php echo preg_replace('/[^a-z0-9_]/', '_', strtolower($category_name)) ?>" class="<?php if ($collapse): ?> collapse<?php endif; ?>">
<?php if ($category != 'NONE'): ?><h2>[?php echo __('<?php echo $category_name ?>') ?]</h2>
<?php endif; ?>
<?php $hides = $this->getParameterValue('edit.hide', array()) ?>
<?php foreach ($this->getColumns('edit.display', $category) as $name => $column): ?>
<?php if (in_array($column->getName(), $hides)) continue ?>
<?php if ($column->isPrimaryKey()) continue ?>
<?php $credentials = $this->getParameterValue('edit.fields.'.$column->getName().'.credentials') ?>
<?php if ($credentials): $credentials = str_replace("\n", ' ', var_export($credentials, true)) ?>
[?php if ($sf_user->hasCredential(<?php echo $credentials ?>)): ?]
<?php endif; ?>
<div class="form-row">
[?php echo label_for('<?php echo $this->getParameterValue("edit.fields.".$column->getName().".label_for", $this->getSingularName()."[".$column->getName()."]") ?>', __($labels['<?php echo $this->getSingularName() ?>{<?php echo $column->getName() ?>}']), '<?php if ($column->isNotNull()): ?>class="required" <?php endif; ?>') ?]
<div class="content[?php if ($sf_request->hasError('<?php echo $this->getSingularName() ?>{<?php echo $column->getName() ?>}')): ?] form-error[?php endif; ?]">
[?php if ($sf_request->hasError('<?php echo $this->getSingularName() ?>{<?php echo $column->getName() ?>}')): ?]
[?php echo form_error('<?php echo $this->getSingularName() ?>{<?php echo $column->getName() ?>}', array('class' => 'form-error-msg')) ?]
[?php endif; ?]
[?php $value = <?php echo $this->getColumnEditTag($column); ?>; echo $value ? $value : '&nbsp;' ?]
<?php echo $this->getHelp($column, 'edit') ?>
</div>
</div>
<?php if ($credentials): ?>
[?php endif; ?]
<?php endif; ?>
<?php endforeach; ?>
</fieldset>
<?php endforeach; ?>
[?php include_partial('edit_actions', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>)) ?]
</form>
<ul class="sf_admin_actions">
<?php
/*
* WARNING: delete is a form, it must be outside the main form
*/
$editActions = $this->getParameterValue('edit.actions');
?>
<?php if (null === $editActions || (null !== $editActions && array_key_exists('_delete', $editActions))): ?>
<?php echo $this->addCredentialCondition($this->getButtonToAction('_delete', $editActions['_delete'], true), $editActions['_delete']) ?>
<?php endif; ?>
</ul>
[?php if ($sf_request->hasErrors()): ?]
<div class="form-errors">
<h2>[?php echo __('There are some errors that prevent the form to validate') ?]</h2>
<dl>
[?php foreach ($sf_request->getErrorNames() as $name): ?]
<dt>[?php echo __($labels[$name]) ?]</dt>
<dd>[?php echo $sf_request->getError($name) ?]</dd>
[?php endforeach; ?]
</dl>
</div>
[?php elseif ($sf_flash->has('notice')): ?]
<div class="save-ok">
<h2>[?php echo __($sf_flash->get('notice')) ?]</h2>
</div>
[?php endif; ?]
[?php use_helper('Object') ?]
<?php if ($this->getParameterValue('list.filters')): ?>
<div class="sf_admin_filters">
[?php echo form_tag('<?php echo $this->getModuleName() ?>/list', array('method' => 'get')) ?]
<fieldset>
<h2>[?php echo __('filters') ?]</h2>
<?php foreach ($this->getColumns('list.filters') as $column): $type = $column->getCreoleType() ?>
<?php $credentials = $this->getParameterValue('list.fields.'.$column->getName().'.credentials') ?>
<?php if ($credentials): $credentials = str_replace("\n", ' ', var_export($credentials, true)) ?>
[?php if ($sf_user->hasCredential(<?php echo $credentials ?>)): ?]
<?php endif; ?>
<div class="form-row">
<label for="<?php echo $column->getName() ?>">[?php echo __('<?php echo str_replace("'", "\\'", $this->getParameterValue('list.fields.'.$column->getName().'.name')) ?>:') ?]</label>
<div class="content">
[?php echo <?php echo $this->getColumnFilterTag($column) ?> ?]
<?php if ($this->getParameterValue('list.fields.'.$column->getName().'.filter_is_empty')): ?>
<div>[?php echo checkbox_tag('filters[<?php echo $column->getName() ?>_is_empty]', 1, isset($filters['<?php echo $column->getName() ?>_is_empty']) ? $filters['<?php echo $column->getName() ?>_is_empty'] : null) ?]&nbsp;<label for="filters[<?php echo $column->getName() ?>_is_empty]">[?php echo __('is empty') ?]</label></div>
<?php endif; ?>
</div>
</div>
<?php if ($credentials): ?>
[?php endif; ?]
<?php endif; ?>
<?php endforeach; ?>
</fieldset>
<ul class="sf_admin_actions">
<li>[?php echo button_to(__('reset'), '<?php echo $this->getModuleName() ?>/list?filter=filter', 'class=sf_admin_action_reset_filter') ?]</li>
<li>[?php echo submit_tag(__('filter'), 'name=filter class=sf_admin_action_filter') ?]</li>
</ul>
</form>
</div>
<?php endif; ?>
<table cellspacing="0" class="sf_admin_list">
<thead>
<tr>
[?php include_partial('list_th_<?php echo $this->getParameterValue('list.layout', 'tabular') ?>') ?]
<?php if ($this->getParameterValue('list.object_actions')): ?>
<th id="sf_admin_list_th_sf_actions">[?php echo __('Actions') ?]</th>
<?php endif; ?>
</tr>
</thead>
<tbody>
[?php $i = 1; foreach ($pager->getResults() as $<?php echo $this->getSingularName() ?>): $odd = fmod(++$i, 2) ?]
<tr class="sf_admin_row_[?php echo $odd ?]">
[?php include_partial('list_td_<?php echo $this->getParameterValue('list.layout', 'tabular') ?>', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>)) ?]
[?php include_partial('list_td_actions', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>)) ?]
</tr>
[?php endforeach; ?]
</tbody>
<tfoot>
<tr><th colspan="<?php echo $this->getParameterValue('list.object_actions') ? count($this->getColumns('list.display')) + 1 : count($this->getColumns('list.display')) ?>">
<div class="float-right">
[?php if ($pager->haveToPaginate()): ?]
[?php echo link_to(image_tag(sfConfig::get('sf_admin_web_dir').'/images/first.png', array('align' => 'absmiddle', 'alt' => __('First'), 'title' => __('First'))), '<?php echo $this->getModuleName() ?>/list?page=1') ?]
[?php echo link_to(image_tag(sfConfig::get('sf_admin_web_dir').'/images/previous.png', array('align' => 'absmiddle', 'alt' => __('Previous'), 'title' => __('Previous'))), '<?php echo $this->getModuleName() ?>/list?page='.$pager->getPreviousPage()) ?]
[?php foreach ($pager->getLinks() as $page): ?]
[?php echo link_to_unless($page == $pager->getPage(), $page, '<?php echo $this->getModuleName() ?>/list?page='.$page) ?]
[?php endforeach; ?]
[?php echo link_to(image_tag(sfConfig::get('sf_admin_web_dir').'/images/next.png', array('align' => 'absmiddle', 'alt' => __('Next'), 'title' => __('Next'))), '<?php echo $this->getModuleName() ?>/list?page='.$pager->getNextPage()) ?]
[?php echo link_to(image_tag(sfConfig::get('sf_admin_web_dir').'/images/last.png', array('align' => 'absmiddle', 'alt' => __('Last'), 'title' => __('Last'))), '<?php echo $this->getModuleName() ?>/list?page='.$pager->getLastPage()) ?]
[?php endif; ?]
</div>
[?php echo format_number_choice('[0] no result|[1] 1 result|(1,+Inf] %1% results', array('%1%' => $pager->getNbResults()), $pager->getNbResults()) ?]
</th></tr>
</tfoot>
</table>
<ul class="sf_admin_actions">
<?php $listActions = $this->getParameterValue('list.actions') ?>
<?php if (null !== $listActions): ?>
<?php foreach ((array) $listActions as $actionName => $params): ?>
<?php echo $this->addCredentialCondition($this->getButtonToAction($actionName, $params, false), $params) ?>
<?php endforeach; ?>
<?php else: ?>
<?php echo $this->getButtonToAction('_create', array(), false) ?>
<?php endif; ?>
</ul>
[?php if ($sf_request->getError('delete')): ?]
<div class="form-errors">
<h2>[?php echo __('Could not delete the selected %name%', array('%name%' => '<?php echo sfInflector::humanize($this->getSingularName()) ?>')) ?]</h2>
<ul>
<li>[?php echo $sf_request->getError('delete') ?]</li>
</ul>
</div>
[?php endif; ?]
<?php if ($this->getParameterValue('list.object_actions')): ?>
<td>
<ul class="sf_admin_td_actions">
<?php foreach ($this->getParameterValue('list.object_actions') as $actionName => $params): ?>
<?php echo $this->addCredentialCondition($this->getLinkToAction($actionName, $params, true), $params) ?>
<?php endforeach; ?>
</ul>
</td>
<?php endif; ?>
<td colspan="<?php echo count($this->getColumns('list.display')) ?>">
<?php if ($this->getParameterValue('list.params')): ?>
<?php echo $this->getI18NString('list.params') ?>
<?php else: ?>
<?php $hides = $this->getParameterValue('list.hide', array()) ?>
<?php foreach ($this->getColumns('list.display') as $column): ?>
<?php if (in_array($column->getName(), $hides)) continue ?>
<?php if ($column->isLink()): ?>
[?php echo link_to(<?php echo $this->getColumnListTag($column) ?> ? <?php echo $this->getColumnListTag($column) ?> : __('-'), '<?php echo $this->getModuleName() ?>/edit?<?php echo $this->getPrimaryKeyUrlParams() ?>) ?]
<?php else: ?>
[?php echo <?php echo $this->getColumnListTag($column) ?> ?]
<?php endif; ?>
-
<?php endforeach; ?>
<?php endif; ?>
</td>
\ No newline at end of file
<?php $hs = $this->getParameterValue('list.hide', array()) ?>
<?php foreach ($this->getColumns('list.display') as $column): ?>
<?php if (in_array($column->getName(), $hs)) continue ?>
<?php $credentials = $this->getParameterValue('list.fields.'.$column->getName().'.credentials') ?>
<?php if ($credentials): $credentials = str_replace("\n", ' ', var_export($credentials, true)) ?>
[?php if ($sf_user->hasCredential(<?php echo $credentials ?>)): ?]
<?php endif; ?>
<?php if ($column->isLink()): ?>
<td>[?php echo link_to(<?php echo $this->getColumnListTag($column) ?> ? <?php echo $this->getColumnListTag($column) ?> : __('-'), '<?php echo $this->getModuleName() ?>/edit?<?php echo $this->getPrimaryKeyUrlParams() ?>) ?]</td>
<?php else: ?>
<td>[?php echo <?php echo $this->getColumnListTag($column) ?> ?]</td>
<?php endif; ?>
<?php if ($credentials): ?>
[?php endif; ?]
<?php endif; ?>
<?php endforeach; ?>
<?php $hides = $this->getParameterValue('list.hide', array()) ?>
<?php foreach ($this->getColumns('list.display') as $column): ?>
<?php if (in_array($column->getName(), $hides)) continue ?>
<?php $credentials = $this->getParameterValue('list.fields.'.$column->getName().'.credentials') ?>
<?php if ($credentials): $credentials = str_replace("\n", ' ', var_export($credentials, true)) ?>
[?php if ($sf_user->hasCredential(<?php echo $credentials ?>)): ?]
<?php endif; ?>
<th id="sf_admin_list_th_<?php echo $column->getName() ?>">
<?php if ($column->isReal()): ?>
[?php if ($sf_user->getAttribute('sort', null, 'sf_admin/<?php echo $this->getSingularName() ?>/sort') == '<?php echo $column->getName() ?>'): ?]
[?php echo link_to(__('<?php echo str_replace("'", "\\'", $this->getParameterValue('list.fields.'.$column->getName().'.name')) ?>'), '<?php echo $this->getModuleName() ?>/list?sort=<?php echo $column->getName() ?>&type='.($sf_user->getAttribute('type', 'asc', 'sf_admin/<?php echo $this->getSingularName() ?>/sort') == 'asc' ? 'desc' : 'asc')) ?]
([?php echo __($sf_user->getAttribute('type', 'asc', 'sf_admin/<?php echo $this->getSingularName() ?>/sort')) ?])
[?php else: ?]
[?php echo link_to(__('<?php echo str_replace("'", "\\'", $this->getParameterValue('list.fields.'.$column->getName().'.name')) ?>'), '<?php echo $this->getModuleName() ?>/list?sort=<?php echo $column->getName() ?>&type=asc') ?]
[?php endif; ?]
<?php else: ?>
[?php echo __('<?php echo str_replace("'", "\\'", $this->getParameterValue('list.fields.'.$column->getName().'.name')) ?>') ?]
<?php endif; ?>
<?php echo $this->getHelpAsIcon($column, 'list') ?>
</th>
<?php if ($credentials): ?>
[?php endif; ?]
<?php endif; ?>
<?php endforeach; ?>
[?php use_helper('Object', 'Validation', 'ObjectAdmin', 'I18N', 'Date') ?]
[?php use_stylesheet('<?php echo $this->getParameterValue('css', sfConfig::get('sf_admin_web_dir').'/css/main') ?>') ?]
<div id="sf_admin_container">
<h1><?php echo $this->getI18NString('edit.title', 'edit '.$this->getModuleName()) ?></h1>
<div id="sf_admin_header">
[?php include_partial('<?php echo $this->getModuleName() ?>/edit_header', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>)) ?]
</div>
<div id="sf_admin_content">
[?php include_partial('<?php echo $this->getModuleName() ?>/edit_messages', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>, 'labels' => $labels)) ?]
[?php include_partial('<?php echo $this->getModuleName() ?>/edit_form', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>, 'labels' => $labels)) ?]
</div>
<div id="sf_admin_footer">
[?php include_partial('<?php echo $this->getModuleName() ?>/edit_footer', array('<?php echo $this->getSingularName() ?>' => $<?php echo $this->getSingularName() ?>)) ?]
</div>
</div>
[?php use_helper('I18N', 'Date') ?]
[?php use_stylesheet('<?php echo $this->getParameterValue('css', sfConfig::get('sf_admin_web_dir').'/css/main') ?>') ?]
<div id="sf_admin_container">
<h1><?php echo $this->getI18NString('list.title', $this->getModuleName().' list') ?></h1>
<div id="sf_admin_header">
[?php include_partial('<?php echo $this->getModuleName() ?>/list_header', array('pager' => $pager)) ?]
[?php include_partial('<?php echo $this->getModuleName() ?>/list_messages', array('pager' => $pager)) ?]
</div>
<div id="sf_admin_bar">
<?php if ($this->getParameterValue('list.filters')): ?>
[?php include_partial('filters', array('filters' => $filters)) ?]
<?php endif; ?>
</div>
<div id="sf_admin_content">
[?php if (!$pager->getNbResults()): ?]
[?php echo __('no result') ?]
[?php else: ?]
[?php include_partial('<?php echo $this->getModuleName() ?>/list', array('pager' => $pager)) ?]
[?php endif; ?]
[?php include_partial('list_actions') ?]
</div>
<div id="sf_admin_footer">
[?php include_partial('<?php echo $this->getModuleName() ?>/list_footer', array('pager' => $pager)) ?]
</div>
</div>
This diff is collapsed.
../../../../lib/
\ No newline at end of file
<?php
use_helper('ObjectAdmin');
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* ObjectHelper for doctrine admin generator.
*
* @package symfony
* @subpackage helper
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: ObjectDoctrineAdminHelper.php 3339 2007-01-28 09:47:52Z chtito $
*/
function object_doctrine_admin_double_list($object, $method, $options = array())
{
return object_admin_double_list($object, $method, $options, '_get_doctrine_object_list');
}
function object_doctrine_admin_select_list($object, $method, $options = array())
{
return object_admin_select_list($object, $method, $options, '_get_doctrine_object_list');
}
function object_doctrine_admin_check_list($object, $method, $options = array())
{
return object_admin_check_list($object, $method, $options, '_get_doctrine_object_list');
}
function _get_doctrine_object_list($object, $method, $options)
{
$foreignTable = $object->getTable()->getRelation($method[1][0])->getTable();
$foreignClass = $foreignTable->getComponentName();
$allObjects = $foreignTable->findAll();
$associatedObjects = $object->get($method[1][0]);
$ids = array();
foreach ($associatedObjects as $associatedObject)
{
$ids[] = $associatedObject->obtainIdentifier();
}
// fix due to the fact that an empty doctrine collection $c (count == 0)
// will return true on: if ($c)
// if (!empty($c)) won't work either...
// the if($c) test is in _get_options_from_objects
if (count($associatedObjects) == 0)
$associatedObjects = null;
return array($allObjects, $associatedObjects, $ids);
}
function object_enum_tag($object, $method, $options)
{
$enumValues = _get_option($options, 'enumValues', array());
$currentValue = _get_object_value($object, $method);
$enumValues = array_combine($enumValues, $enumValues);
return select_tag(_convert_method_to_name($method, $options), options_for_select($enumValues, $currentValue), $options);
}
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @version SVN: $Id: sfDoctrine.class.php 4092 2007-05-23 17:37:26Z chtito $
*/
class sfDoctrine
{
// uses the default connection if none is given
static public function connection($connection = null)
{
if ($connection === null)
{
return Doctrine_Manager::getInstance()->getCurrentConnection();
}
return Doctrine_Manager::getInstance()->getConnection($connection);
}
// returns either the connection connectionName or uses the doctrine manager
// to find out the connection bound to the class (or the current one)
public static function connectionForClass($className, $connectionName = null)
{
if (isset($connectionName))
{
return Doctrine_Manager::getInstance()->getConnection($connectionName);
}
return Doctrine_Manager::getInstance()->getConnectionForComponent($className);
}
public static function getTable($className)
{
return Doctrine_Manager::getInstance()->getTable($className);
}
public static function queryFrom($className)
{
sfContext::getInstance()->getLogger()->err('The sfDoctrine::queryFrom() method is deprecated; use "Doctrine_Query::create()->from($className)" instead.');
return self::getTable($className)->createQuery();
}
}
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineAdminGenerator.class.php 4533 2007-07-03 23:36:10Z gnat $
*/
class sfDoctrineAdminGenerator extends sfAdminGenerator
{
protected $table;
public function initialize($generatorManager)
{
// otherwise the class never gets loaded... don't ask me why...
include_once(sfConfig::get('sf_symfony_lib_dir').'/vendor/creole/CreoleTypes.php');
parent::initialize($generatorManager);
$this->setGeneratorClass('sfDoctrineAdmin');
}
protected function loadMapBuilderClasses()
{
$conn = Doctrine_Manager::getInstance()->openConnection('mock://no-one@localhost/empty', null, false);
$this->table = $conn->getTable($this->getClassName());
}
protected function getTable()
{
return $this->table;
}
protected function loadPrimaryKeys()
{
foreach ($this->getTable()->getPrimaryKeys() as $primaryKey)
$this->primaryKey[] = new sfDoctrineAdminColumn($primaryKey);
// FIXME: check that there is at least one primary key
}
public function getColumns($paramName, $category='NONE')
{
$columns = parent::getColumns($paramName, $category);
// set the foreign key indicator
$relations = $this->getTable()->getRelations();
$cols = $this->getTable()->getColumns();
foreach ($columns as $index => $column)
{
if (isset($relations[$column->getName()]))
{
$fkcolumn = $relations[$column->getName()];
$columnName = $relations[$column->getName()]->getLocal();
if ($columnName != 'id') // i don't know why this is necessary
{
$column->setRelatedClassName($fkcolumn->getTable()->getComponentName());
$column->setColumnName($columnName);
if (isset($cols[$columnName])) // if it is not a many2many
$column->setColumnInfo($cols[$columnName]);
$columns[$index] = $column;
}
}
}
return $columns;
}
function getAllColumns()
{
$cols = $this->getTable()->getColumns();
$rels = $this->getTable()->getRelations();
$columns = array();
foreach ($cols as $name => $col)
{
// we set out to replace the foreign key to their corresponding aliases
$found = null;
foreach ($rels as $alias=>$rel)
{
$relType = $rel->getType();
if ($rel->getLocal() == $name && $relType != Doctrine_Relation::MANY_AGGREGATE && $relType != Doctrine_Relation::MANY_COMPOSITE)
$found = $alias;
}
if ($found)
{
$name = $found;
}
$columns[] = new sfDoctrineAdminColumn($name, $col);
}
return $columns;
}
function getAdminColumnForField($field, $flag = null)
{
$cols = $this->getTable()->getColumns(); // put this in an internal variable?
return new sfDoctrineAdminColumn($field, (isset($cols[$field]) ? $cols[$field] : null), $flag);
}
function getPHPObjectHelper($helperName, $column, $params, $localParams = array())
{
$params = $this->getObjectTagParams($params, $localParams);
// special treatment for object_select_tag:
if ($helperName == 'select_tag')
{
$column = new sfDoctrineAdminColumn($column->getColumnName(), null, null);
}
return sprintf ('object_%s($%s, %s, %s)', $helperName, $this->getSingularName(), var_export($this->getColumnGetter($column), true), $params);
}
function getColumnGetter($column, $developed = false, $prefix = '')
{
if ($developed)
return sprintf("$%s%s->get('%s')", $prefix, $this->getSingularName(), $column->getName());
// no parenthesis, we return a method+parameters array
return array('get', array($column->getName()));
}
function getColumnSetter($column, $value, $singleQuotes = false, $prefix = 'this->')
{
if ($singleQuotes)
$value = sprintf("'%s'", $value);
return sprintf('$%s%s->set(\'%s\', %s)', $prefix, $this->getSingularName(), $column->getName(), $value);
}
function getRelatedClassName($column)
{
return $column->getRelatedClassName();
}
public function getColumnEditTag($column, $params = array())
{
if ($column->getDoctrineType() == 'enum')
{
// FIXME: this is called already in the sfAdminGenerator class!!!
$params = array_merge(array('control_name' => $this->getSingularName().'['.$column->getName().']'), $params);
$values = $this->getTable()->getEnumValues($column->getName());
$params = array_merge(array('enumValues'=>$values), $params);
return $this->getPHPObjectHelper('enum_tag', $column, $params);
}
return parent::getColumnEditTag($column, $params);
}
}
class sfDoctrineAdminColumn extends sfAdminColumn
{
// doctrine to creole type conversion
static $docToCreole = array(
'boolean' => CreoleTypes::BOOLEAN,
'string' => CreoleTypes::TEXT,
'integer' => CreoleTypes::INTEGER,
'date' => CreoleTypes::DATE,
'timestamp' => CreoleTypes::TIMESTAMP,
'time' => CreoleTypes::TIME,
'enum' => CreoleTypes::TINYINT,
'float' => CreoleTypes::FLOAT,
'double' => CreoleTypes::FLOAT,
'clob' => CreoleTypes::CLOB,
'blob' => CreoleTypes::BLOB,
'object' => CreoleTypes::VARCHAR,
'array' => CreoleTypes::VARCHAR,
'decimal' => CreoleTypes::DECIMAL,
);
protected $relatedClassName = null;
protected $name = null;
protected $columnName; // stores the real foreign id column
function getDoctrineType()
{
return isset($this->column['type']) ? $this->column['type'] : null;
}
function getCreoleType()
{
$dType = $this->getDoctrineType();
// we simulate the CHAR/VARCHAR types to generate input_tags
if(($dType == 'string') and ($this->getSize() < 256))
{
return CreoleTypes::VARCHAR;
}
return $dType ? self::$docToCreole[$dType] : CreoleTypes::OTHER;
}
function getSize()
{
return $this->column['length'];
}
function isNotNull()
{
//FIXME THIS NEEDS TO BE UPDATE-but I don't know the format for the column array
if (isset($this->column[2]['notnull']))
return $this->column[2]['notnull'];
return false;
}
function isPrimaryKey()
{
if (isset($this->column['primary']))
return $this->column['primary'];
return false;
}
function setRelatedClassName($newName)
{
$this->relatedClassName = $newName;
}
function getRelatedClassName()
{
return $this->relatedClassName;
}
function setColumnName($newName)
{
$this->columnName = $newName;
}
function getColumnName()
{
return $this->columnName;
}
function setColumnInfo($col)
{
$this->column = $col;
}
// FIXME: this method is never used... remove it?
function setName($newName)
{
$this->name = $newName;
}
function getName()
{
if (isset($this->name))
{
return $this->name;
}
// a bit kludgy: the field name is actually in $this->phpName
return parent::getPhpName();
}
function isForeignKey()
{
return isset($this->relatedClassName);
}
// all the calls that were forwarded to the table object with propel
// have to be dealt with explicitly here, otherwise:
public function __call($name, $arguments)
{
throw new Exception(sprintf('Unhandled call: "%s"', $name));
}
}
<?php
/**
*
* sfDoctrineConfigHandler parses the PHPDoctrine config file
*
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Amadeus
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @author Dan Porter
* @version SVN: $Id: sfDoctrineConfigHandler.class.php 4132 2007-05-31 19:50:01Z gnat $
*/
class sfDoctrineConfigHandler extends sfYamlConfigHandler
{
public function execute($configFiles)
{
// Parse yaml config files
$configs = $this->parseYamls($configFiles);
// Default config: all.attributes
$default_config = array ();
if (isset ($configs['all']['attributes']) && is_array($configs['all']['attributes']))
{
$default_config = $configs['all']['attributes'];
unset ($configs['all']['attributes']);
}
// Environment specific defaults: <env>.attributes
$env = sfConfig::get('sf_environment');
if (isset ($configs[$env]['attributes']) && is_array($configs[$env]['attributes']))
{
$default_config = sfToolKit::arrayDeepMerge($default_config, $configs[$env]['attributes']);
unset ($configs[$env]['attributes']);
}
// Connection specific configs
$conn_configs = array();
foreach ($configs as $env => $env_config)
{
foreach ($env_config as $conn => $conn_config)
{
$conn_configs[$conn] = sfToolkit::arrayDeepMerge($default_config, $conn_config);
}
}
// Prepare default config data
$data = array();
foreach ($this->configToAttributes($default_config) as $key => $value)
{
$data[] = sprintf('$default_attributes["%s"] = %s;', $key, $this->attributeToPhp($value));
}
$data[] = '';
// Prepare connection specific data
foreach ($conn_configs as $conn_name => $conn_config)
{
foreach ($this->configToAttributes($conn_config) as $key => $value)
{
$data[] = sprintf('$attributes["%s"]["%s"] = %s;', $conn_name, $key, $this->attributeToPHP($value));
}
$data[] = '';
}
// compile data
$retval = sprintf("<?php\n" .
"// auto-generated by sfDoctrineConfigHandler\n" .
"// date: %s\n%s\n", date('Y-m-d H:i:s'), implode("\n", $data));
return $retval;
}
protected function configToAttributes($config)
{
$attributes = array();
foreach ($config as $key => $value)
{
$attr_key = 'ATTR_' . strtoupper($key);
switch ($key)
{
// event listener (name of the listener class)
case 'listener':
$attributes[$attr_key] = array ('php', "new $value()");
break;
// fetch mode (immediate, batch, offset, lazy_offset)
case 'fetchmode':
$attributes[$attr_key] = array ('constant', 'FETCH_' . strtoupper($value));
break;
// locking (optimistic, pessimistic)
case 'lockmode':
$attributes[$attr_key] = array ('constant', 'LOCK_' . strtoupper($value));
break;
// export (none, tables, constraints, all)
case 'export':
$attributes[$attr_key] = array('constant', 'EXPORT_'.strtoupper($value));
break;
// accessors (none, get, set, both)
/* case 'accessors':
$attributes[$attr_key] = array ('constant', 'ACCESSOR_' . strtoupper($value));
break;
*/
// portability (none, fix_case, rtrim, delete_count, empty_to_null, fix_assoc_field_names, all)
case 'portability':
$attributes[$attr_key] = array ('constant', 'PORTABILITY_' . strtoupper($value));
break;
// the default will set the value as a string or a boolean (depending on the type returned by the yaml parser)
default:
$attributes[$attr_key] = $value;
}
}
return $attributes;
}
protected function attributeToPhp($attr)
{
if (is_array($attr))
{
if ($attr[0] == 'constant')
{
$attr = 'Doctrine::' . $attr[1];
}
elseif ($attr[0] == 'php')
{
$attr = $attr[1];
}
}
elseif (is_string($attr))
{
$attr = sprintf("'%s'", $attr);
}
else
{
$attr = var_export($attr, 1);
}
return $attr;
}
}
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id$
*/
class sfDoctrineConnectionListener extends Doctrine_EventListener
{
public function __construct($connection, $encoding)
{
$this->connection = $connection;
$this->encoding = $encoding;
}
public function postConnect(Doctrine_Event $event)
{
$this->connection->setCharset($this->encoding);
$this->connection->setDateFormat();
}
}
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package sfDoctrinePlugin
* @subpackage sfDoctrineData
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineData.class.php 4493 2007-06-30 00:47:02Z Jonathan.Wage $
*/
class sfDoctrineData extends sfData
{
/**
* connectionName
*
* @var mixed
* @access protected
*/
protected $connectionName = null;
/**
* loadData
*
* @param mixed $directory_or_file
* @param mixed $connectionName
* @access public
* @return void
*/
public function loadData($directory_or_file = null, $connectionName = null)
{
$this->connectionName = $connectionName;
$fixture_files = $this->getFiles($directory_or_file);
// wrap all database operations in a single transaction
$con = sfDoctrine::connection($connectionName);
try
{
$con->beginTransaction();
$this->doLoadData($fixture_files);
$con->commit();
}
catch (Exception $e)
{
$con->rollback();
throw $e;
}
}
/**
* loadDataFromArray
*
* @param mixed $data
* @access public
* @return void
*/
public function loadDataFromArray($data)
{
$pendingRelations = array();
if ($data === null)
{
// no data
return;
}
// only for pake_echo_action
require_once(sfConfig::get('sf_symfony_lib_dir').'/vendor/pake/pakeFunction.php');
foreach ($data as $class => $entries)
{
pake_echo_action('Filling', sprintf('class "%s"', $class)."\t");
// fetch a table object
$table = sfDoctrine::getTable($class, $this->connectionName);
$colNames = array_keys($table->getColumns());
$tableName = $table->getTableName();
// relation fields
$relations = $table->getRelations();
//echo "Class $class: ".implode(', ', array_keys($relations))."\n";
if ($this->deleteCurrentData)
{
$q = new Doctrine_Query();
$q->delete()->from($class);
$q->execute();
}
// iterate through entries for this class
// might have been empty just for force a table to be emptied on import
if (is_array($entries))
{
foreach ($entries as $key => $columnAssignments)
{
// create a new entry in the database
$obj = $table->create();
$now = date("Y-m-d H:i:s", time());
if($obj->getTable()->hasColumn('created_at'))
{
$obj->set('created_at', $now);
}
if (!is_array($columnAssignments))
{
throw new Exception('You must give a name for each fixture data entry');
}
foreach ($columnAssignments as $name => $value)
{
$isRelation = isset($relations[$name]);
// foreign key?
if ($isRelation)
{
$rel = $relations[$name];
// $relatedTable = $rel->getTable()->getTableName();
$localKey = $rel->getLocal();
$foreignKey = $rel->getForeign();
$pendingRelations[] = array($obj, $localKey, $foreignKey, $value);
}
else
{
// first check that the column exists
if (!in_array($name, $colNames))
{
$error = 'Column "%s" does not exist for class "%s"';
$error = sprintf($error, $name, $class);
throw new sfException($error);
}
$obj->rawSet($name, $value);
}
}
$obj->save();
// For progress meter
echo '.';
// save the id for future reference
$pk = $obj->obtainIdentifier();
if (isset($this->object_references[$key]))
{
throw new sfException(sprintf('The key "%s" is not unique', $key));
}
$this->object_references[$key] = $pk;
}
}
echo "\n";
}
// now we take care of the pending relations
foreach ($pendingRelations as $pending)
{
list($obj, $localKey, $foreignKey, $key) = $pending;
if (!isset($this->object_references[$key]))
{
$error = 'No object with key "%s" is defined in your data file';
$error = sprintf($error, $key);
throw new sfException($error);
}
$foreignId = $this->object_references[$key][$foreignKey];
$obj->rawSet($localKey, $foreignId);
$obj->save();
}
}
/**
* loadMapBuilder
*
* @param mixed $class
* @access protected
* @return void
*/
protected function loadMapBuilder($class)
{
$class_map_builder = $class.'MapBuilder';
if (!isset($this->maps[$class]))
{
if (!$classPath = sfCore::getClassPath($class_map_builder))
{
throw new sfException(sprintf('Unable to find path for class "%s".', $class_map_builder));
}
require_once($classPath);
$this->maps[$class] = new $class_map_builder();
$this->maps[$class]->doBuild();
}
}
/**
* dumpData
*
* @param mixed $directory_or_file
* @param string $tables
* @param string $connectionName
* @access public
* @return void
*/
public function dumpData($directory_or_file = null, $tables = 'all', $connectionName = 'propel')
{
$sameFile = true;
if (is_dir($directory_or_file))
{
// multi files
$sameFile = false;
}
else
{
// same file
// delete file
}
$manager = Doctrine_Manager::getInstance();
$con = $manager->getCurrentConnection();
// get tables
if ('all' === $tables || null === $tables)
{
$modelDirectories = array();
$modelDirectories[] = sfConfig::get('sf_model_lib_dir').'/doctrine';
$directories = sfFinder::type('dir')->maxdepth(0)->in(sfConfig::get('sf_model_lib_dir').'/doctrine');
foreach($directories AS $directory)
{
if( strstr($directory, 'generated') )
{
continue;
}
$modelDirectories[] = $directory;
}
$tables = array();
foreach($modelDirectories AS $directory)
{
$dirTables = sfFinder::type('file')->name('/(?<!Table)\.class.php$/')->maxdepth(0)->in($directory);
foreach ($dirTables AS $key => $table)
{
$table = basename($table, '.class.php');
$tables[] = $table;
}
}
}
else if (!is_array($tables))
{
$tables = array($tables);
}
$dumpData = array();
foreach ($tables as $modelName)
{
$table = sfDoctrine::getTable($modelName, $this->connectionName);
// get table name
$tableName = $table->getTableName();
$relations = $table->getRelations();
// get columns
$columns = $con->fetchAll('DESCRIBE '.$tableName);
// get records
//$records = $con->fetchAll('SELECT * FROM '.$tableName);
$query = new Doctrine_Query();
$query->from($modelName);
$records = $query->execute();
$dumpData[$modelName] = array();
foreach($records AS $record)
{
$pk = $modelName;
$values = array();
foreach($columns AS $column)
{
$col = strtolower($column['Field']);
try {
$initialValue = $record[$col];
} catch(Exception $e) {
continue;
}
if( !$initialValue )
{
continue;
}
if ($column['Key'] == 'PRI')
{
$pk .= '_'.$initialValue;
}
else
{
$isForeignKey = false;
foreach($relations AS $relation)
{
if( $relation->getLocal() == $col )
{
$isForeignKey = true;
break;
}
}
if( $isForeignKey )
{
$array = $relation->toArray();
$values[$relation->getAlias()] = $array['class'].'_'.$initialValue;
} else {
$value = $initialValue;
// Needed to maintain bool values
if( is_bool($value) )
{
$value = $value ? 1:0;
}
$values[$col] = $value;
}
}
}
$dumpData[$modelName][$pk] = $values;
}
}
// save to file(s)
if ($sameFile)
{
$yaml = Spyc::YAMLDump($dumpData);
file_put_contents($directory_or_file, $yaml);
}
else
{
foreach ($dumpData as $table => $data)
{
$yaml = Spyc::YAMLDump($data);
file_put_contents($directory_or_file."/$table.yml", $yaml);
}
}
}
}
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineDataRetriever.class.php 3437 2007-02-10 09:04:27Z chtito $
*/
class sfDoctrineDataRetriever
{
static public function retrieveObjects($class, $peer_method = 'findAll')
{
if (!$peer_method)
$peer_method = 'findAll';
$table = sfDoctrine::getTable($class);
return call_user_func(array($table, $peer_method));
}
}
\ No newline at end of file
<?php
/*
* This file is part of the symfony package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2004-2006 Sean Kerr.
* (c) 2006-2007 Olivier Verdier <olivier.verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* sfDoctrineDatabase provides connectivity for the Doctrine.
*
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Maarten den Braber <mdb@twister.cx>
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @author Dan Porter
* @version SVN: $Id: sfDoctrineDatabase.class.php 4394 2007-06-25 17:59:38Z subzero2000 $
*/
class sfDoctrineDatabase extends sfDatabase
{
protected
$doctrineConnection = null;
public function initialize($parameters = array(), $name = null)
{
parent::initialize($parameters);
// if a default connection is defined we only open that one
if ($defaultDatabase = sfConfig::get('sf_default_database'))
{
if ($name != $defaultDatabase)
{
return;
}
}
// load doctrine config
require(sfConfigCache::getInstance()->checkConfig('config/doctrine.yml'));
$db_attributes = $default_attributes;
if (isset($attributes[$name]))
{
$db_attributes = array_merge($default_attributes, $attributes[$name]);
}
$this->setParameter('attributes', $db_attributes);
$this->setParameter('name', $name);
// take care of the component binding
// suppress errors from include_once
// because config/schemas.yml is optional.
@include_once(sfConfigCache::getInstance()->checkConfig('config/schemas.yml', true));
// opening the doctrine connection
// determine how to get our parameters
$method = $this->getParameter('method', 'dsn');
// get parameters
switch ($method)
{
case 'dsn':
$dsn = $this->getParameter('dsn');
if ($dsn == null)
{
// missing required dsn parameter
$error = 'Database configuration specifies method "dsn", but is missing dsn parameter';
throw new sfDatabaseException($error);
}
break;
}
try
{
// Make sure we pass non-PEAR style DSNs as an array
if ( ! strpos($dsn, '://'))
{
$dsn = array($dsn, $this->getParameter('username'), $this->getParameter('password'));
}
$this->doctrineConnection = Doctrine_Manager::connection($dsn, $name);
// figure out the encoding
$encoding = $this->getParameter('encoding', 'UTF8');
// set up the connection parameters from the doctrine.yml config file
foreach($this->getParameter('attributes') as $k => $v)
{
$this->doctrineConnection->setAttribute(constant('Doctrine::'.$k), $v);
}
// we add the listener that sets up encoding and date formats
$eventListener = new sfDoctrineConnectionListener($this->doctrineConnection, $encoding);
$this->doctrineConnection->addListener($eventListener);
// add the query logger
if (sfConfig::get('sf_debug') && sfConfig::get('sf_logging_enabled'))
{
$this->doctrineConnection->addListener(new sfDoctrineQueryLogger());
}
}
catch (PDOException $e)
{
throw new sfDatabaseException($e->getMessage());
}
}
/**
* Connect to the database.
* Stores the PDO connection in $connection
*
*/
public function connect ()
{
$dbh = $this->doctrineConnection->getDbh();
$dbh->connect();
$this->connection = $dbh->getDbh();
}
/**
* Execute the shutdown procedure.
*
* @return void
*
* @throws <b>sfDatabaseException</b> If an error occurs while shutting down this database.
*/
public function shutdown ()
{
if ($this->connection !== null)
{
@$this->connection = null;
}
}
}
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Jan Schaefer <jschaefe@sinntax.de>
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineEventListener.class.php 4416 2007-06-26 21:54:15Z subzero2000 $
*/
class sfDoctrineEventListener extends Doctrine_EventListener
{
}
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineException.class.php 2675 2006-11-14 07:00:59Z chtito $
*/
class sfDoctrineException extends sfException
{
/**
* Class constructor.
*
* @param string The error message.
* @param int The error code.
*/
public function __construct ($message = null, $code = 0)
{
$this->setName('sfDoctrineException');
parent::__construct($message, $code);
}
}
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2004-2006 Fabien Potencier <fabien.potencier@symfony-project.com>
* (c) 2006 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Maarten den Braber <mdb@twister.cx>
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @author Ian P. Christian <pookey@pookey.co.uk>
* @version SVN: $Id: sfDoctrinePager.class.php 4401 2007-06-26 05:02:41Z hansbrix $
*/
class sfDoctrinePager extends sfPager implements Serializable
{
protected
$query;
public function __construct($class, $defaultMaxPerPage = 10)
{
parent::__construct($class, $defaultMaxPerPage);
$this->setQuery(Doctrine_Query::create()->from($class));
}
public function serialize()
{
$vars = get_object_vars($this);
unset($vars['query']);
return serialize($vars);
}
public function unserialize($serialized)
{
$array = unserialize($serialized);
foreach($array as $name => $values) {
$this->$name = $values;
}
}
public function init()
{
$count = $this->getQuery()->offset(0)->limit(0)->count();
$this->setNbResults($count);
$p = $this->getQuery();
$p->offset(0);
$p->limit(0);
if ($this->getPage() == 0 || $this->getMaxPerPage() == 0)
{
$this->setLastPage(0);
}
else
{
$this->setLastPage(ceil($this->getNbResults() / $this->getMaxPerPage()));
$offset = ($this->getPage() - 1) * $this->getMaxPerPage();
$p->offset($offset);
$p->limit($this->getMaxPerPage());
}
}
public function getQuery()
{
return $this->query;
}
public function setQuery($query)
{
$this->query = $query;
}
protected function retrieveObject($offset)
{
$cForRetrieve = clone $this->getQuery();
$cForRetrieve->offset($offset - 1);
$cForRetrieve->limit(1);
$results = $cForRetrieve->execute();
return $results[0];
}
public function getResults($fetchtype = null)
{
$p = $this->getQuery();
if ($fetchtype == 'array')
return $p->execute(array(), Doctrine::FETCH_ARRAY);
return $p->execute();
}
}
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineQueryLogger.class.php 4728 2007-07-27 10:42:49Z mahono $
*/
class sfDoctrineQueryLogger extends Doctrine_EventListener
{
protected $connection = null;
protected $encoding = 'UTF8';
public function preExecute(Doctrine_Event $event)
{
$this->sfLogQuery('{sfDoctrine Execute} executeQuery : ', $event);
}
public function postExecute(Doctrine_Event $event)
{
$this->sfAddTime();
}
public function postPrepare(Doctrine_Event $event)
{
$this->sfAddTime();
}
public function preStmtExecute(Doctrine_Event $event)
{
$this->sfLogQuery('{sfDoctrine Statement} executeQuery : ', $event);
}
public function postStmtExecute(Doctrine_Event $event)
{
$this->sfAddTime();
}
public function preQuery(Doctrine_Event $event)
{
$this->sfLogQuery('{sfDoctrine Query} executeQuery : ', $event);
}
public function postQuery(Doctrine_Event $event)
{
$this->sfAddTime();
}
protected function sfLogQuery($message, $event)
{
$message .= $event->getQuery();
if ($params = $event->getParams())
{
$message .= ' - ('.implode(', ', $params) . ' )';
}
sfContext::getInstance()->getLogger()->log($message);
$sqlTimer = sfTimerManager::getTimer('Database (Doctrine)');
}
protected function sfAddTime()
{
sfTimerManager::getTimer('Database (Doctrine)')->addTime();
}
}
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Olivier Verdier <Olivier.Verdier@gmail.com>
* @version SVN: $Id: sfDoctrineRecord.class.php 5050 2007-09-12 16:13:53Z Jonathan.Wage $
*/
class sfDoctrineRecord extends Doctrine_Record
{
public function __toString()
{
// if the current object doesn't exist we return nothing
if (!$this->exists())
{
return '-';
}
// we try to guess a column which would give a good description of the object
foreach (array('name', 'title', 'description', 'id') as $descriptionColumn)
{
if ($this->getTable()->hasColumn($descriptionColumn))
{
return $this->get($descriptionColumn);
}
}
return sprintf('No description for object of class "%s"', $this->getTable()->getComponentName());
}
// FIXME: All code should be updated to use the new identifier() method directly
public function obtainIdentifier()
{
return $this->identifier();
}
public function set($name, $value, $load = true)
{
// ucfirst() is used instead of camelize() to be compatible with older version of Doctrine
$filterMethod = 'filterSet'.ucfirst($name);
if (method_exists($this, $filterMethod))
{
$value = $this->$filterMethod($value);
}
$setterMethod = 'set'.sfInflector::camelize($name);
return method_exists($this, $setterMethod) ? $this->$setterMethod($value) : parent::set($name, $value, $load);
}
public function get($name, $load = true)
{
$getterMethod = 'get'.sfInflector::camelize($name);
$value = method_exists($this, $getterMethod) ? $this->$getterMethod() : parent::get($name, $load);
// ucfirst() is used instead of camelize() to be compatible with older version of Doctrine
$filterMethod = 'filterGet'.ucfirst($name);
if (method_exists($this, $filterMethod))
{
$value = $this->$filterMethod($value);
}
return $value;
}
function rawSet($name, $value, $load = true)
{
return parent::set($name, $value, $load);
}
function rawGet($name)
{
return parent::rawGet($name);
}
public function __call($m, $a)
{
try {
$verb = substr($m, 0, 3);
if ($verb == 'set' || $verb == 'get')
{
$camelColumn = substr($m, 3);
if (in_array($camelColumn, array_keys($this->getTable()->getRelations())))
{
// the column is actually a class name
$column = $camelColumn;
}
else
{
// the relation was not found
$column = sfInflector::underscore($camelColumn);
}
if ($verb == 'get')
{
return $this->get($column);
}
else // $verb must be 'set'...
{
return $this->set($column, $a[0]);
}
}
} catch(Exception $e) {
return parent::__call($m, $a);
}
}
// added for compatibility with the _get_options_from_objects helper
public function getPrimaryKey()
{
return $this->obtainIdentifier();
}
// to check for the existence of a record
public function has($name)
{
return $this->get($name)->exists();
}
// Hook to update created_at and updated_at fields on record insert
public function preInsert($event)
{
// Set created_at and update_at to now, if they exist in this record
$now = date("Y-m-d H:i:s", time());
if ($this->getTable()->hasColumn('created_at'))
{
$this->rawSet('created_at', $now);
}
if ($this->getTable()->hasColumn('updated_at'))
{
$this->rawSet('updated_at', $now);
}
}
// Hook to update updated_at field on record update
public function preUpdate($event)
{
// Set update_at to now, if it exists in this record
$now = date("Y-m-d H:i:s", time());
if ($this->getTable()->hasColumn('updated_at'))
{
$this->rawSet('updated_at', $now);
}
}
}
<?php
/*
* This file is part of the sfDoctrine package.
* (c) 2006-2007 Olivier Verdier <Olivier.Verdier@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
/**
*
* sfDoctrineSchemasConfigHandler parses the config/schemas.yml config file
*
* @package symfony.plugins
* @subpackage sfDoctrine
* @author Stephen Leavitt <stephen.leavitt@gmail.com>
* @version SVN: $Id$
*/
class sfDoctrineSchemasConfigHandler extends sfYamlConfigHandler
{
public function execute( $configFiles )
{
$this->initialize();
$mappings = $this->parseYamls( $configFiles );
$data = array();
$data[] = '$manager = Doctrine_Manager::getInstance();'."\n";
foreach ( $mappings as $mapping => $schemas )
{
foreach ( $schemas as $schema )
{
$path = sfConfig::get( 'sf_config_dir' ) . '/doctrine/' . $schema . '.yml';
$components = array_keys( sfYaml::load( $path ) );
foreach ( $components as $component )
{
$data[] = "\$manager->bindComponent('{$component}', '{$mapping}');";
}
}
}
// compile data
$retval = sprintf("<?php\n".
"// auto-generated by sfDoctrineSchemasConfigHandler\n".
"// date: %s\n%s\n",
date('Y-m-d H:i:s'), implode("\n", $data));
return $retval;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<package xmlns="http://pear.php.net/dtd/package-2.0" xmlns:tasks="http://pear.php.net/dtd/tasks-1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" packagerversion="1.4.1" version="2.0" xsi:schemaLocation="http://pear.php.net/dtd/tasks-1.0 http://pear.php.net/dtd/tasks-1.0.xsd http://pear.php.net/dtd/package-2.0 http://pear.php.net/dtd/package-2.0.xsd">
<name>sfDoctrinePlugin</name>
<channel>pear.symfony-project.com</channel>
<summary>This plugin allows symfony users to use doctrine instead of propel.</summary>
<description>This plugin fully integrates doctrine into symfony. You can use *all* the features in symfony with propel replaced by doctrine.</description>
<lead>
<name>Olivier Verdier</name>
<user>chtito</user>
<email>olivier.verdier@gmail.com</email>
<active>yes</active>
</lead>
<date>2007-05-05</date>
<version>
<release>0.4.2</release>
<api>0.1.0</api>
</version>
<stability>
<release>beta</release>
<api>beta</api>
</stability>
<license uri="http://www.symfony-project.com/license">MIT license</license>
<notes>-</notes>
<contents>
<dir name="addon"><file name="sfDoctrineDatabaseSchema.class.php" role="data"/></dir><dir name="config"><file name="autoload.yml" role="data"/><file name="config_handlers.yml" role="data"/><file name="doctrine.yml" role="data"/></dir><dir name="data"><dir name="sfDoctrineAdmin"><dir name="default"><dir name="skeleton"><dir name="actions"><file name="actions.class.php" role="data"/></dir><dir name="config"><file name="generator.yml" role="data"/></dir><dir name="templates"/><dir name="validate"/></dir><dir name="template"><dir name="actions"><file name="actions.class.php" role="data"/></dir><dir name="templates"><file name="_edit_actions.php" role="data"/><file name="_edit_footer.php" role="data"/><file name="_edit_header.php" role="data"/><file name="_filters.php" role="data"/><file name="_list_actions.php" role="data"/><file name="_list_footer.php" role="data"/><file name="_list_header.php" role="data"/><file name="_list_td_actions.php" role="data"/><file name="_list_td_stacked.php" role="data"/><file name="_list_td_tabular.php" role="data"/><file name="_list_th_stacked.php" role="data"/><file name="_list_th_tabular.php" role="data"/><file name="editSuccess.php" role="data"/><file name="listSuccess.php" role="data"/></dir></dir></dir></dir><dir name="tasks"><file name="sfPakeDoctrine.php" role="data"/></dir></dir><dir name="lib"><file name="sfDoctrine.class.php" role="data"/><file name="sfDoctrineAdminGenerator.class.php" role="data"/><file name="sfDoctrineConfigHandler.class.php" role="data"/><file name="sfDoctrineDatabase.class.php" role="data"/><file name="sfDoctrinePager.class.php" role="data"/><file name="sfDoctrineUniqueValidator.php" role="data"/><file name="sfPropelCompatRecord.class.php" role="data"/></dir><file name="LICENSE" role="data"/><file name="README" role="data"/><dir name="/"><dir name="addon"><file name="sfDoctrineClassSchema.class.php" role="data"/><file name="sfDoctrineColumnSchema.class.php" role="data"/><file name="sfDoctrineDatabaseSchema.class.php" role="data"/><file name="sfDoctrineRelationSchema.class.php" role="data"/><file name="sfDoctrineSchemaDoctrineLoader.class.php" role="data"/><file name="sfDoctrineSchemaPropelLoader.class.php" role="data"/><file name="sfDoctrineTableSchema.class.php" role="data"/></dir><dir name="config"><file name="autoload.yml" role="data"/><file name="config_handlers.yml" role="data"/><file name="doctrine.yml" role="data"/><file name="settings.yml" role="data"/></dir><dir name="data"><dir name="generator"><dir name="sfDoctrineAdmin"><dir name="crud"><dir name="skeleton"><dir name="actions"><file name="actions.class.php" role="data"/></dir><dir name="config"><file name="generator.yml" role="data"/></dir><dir name="lib"/><dir name="templates"/><dir name="validate"/></dir><dir name="template"><dir name="actions"><file name="actions.class.php" role="data"/></dir><dir name="templates"><file name="editSuccess.php" role="data"/><file name="listSuccess.php" role="data"/><file name="showSuccess.php" role="data"/></dir></dir></dir><dir name="default"><dir name="skeleton"><dir name="actions"><file name="actions.class.php" role="data"/></dir><dir name="config"><file name="generator.yml" role="data"/></dir><dir name="templates"/><dir name="validate"/></dir><dir name="template"><dir name="actions"><file name="actions.class.php" role="data"/></dir><dir name="templates"><file name="_edit_actions.php" role="data"/><file name="_edit_footer.php" role="data"/><file name="_edit_form.php" role="data"/><file name="_edit_header.php" role="data"/><file name="_edit_messages.php" role="data"/><file name="_filters.php" role="data"/><file name="_list.php" role="data"/><file name="_list_actions.php" role="data"/><file name="_list_footer.php" role="data"/><file name="_list_header.php" role="data"/><file name="_list_messages.php" role="data"/><file name="_list_td_actions.php" role="data"/><file name="_list_td_stacked.php" role="data"/><file name="_list_td_tabular.php" role="data"/><file name="_list_th_stacked.php" role="data"/><file name="_list_th_tabular.php" role="data"/><file name="editSuccess.php" role="data"/><file name="listSuccess.php" role="data"/></dir></dir></dir></dir></dir><dir name="tasks"><file name="sfPakeDoctrine.php" role="data"/></dir></dir><dir name="lib"><dir name="helper"><file name="ObjectDoctrineAdminHelper.php" role="data"/></dir><file name="sfDoctrine.class.php" role="data"/><file name="sfDoctrineAdminGenerator.class.php" role="data"/><file name="sfDoctrineConfigHandler.class.php" role="data"/><file name="sfDoctrineConnectionListener.class.php" role="data"/><file name="sfDoctrineData.class.php" role="data"/><file name="sfDoctrineDatabase.class.php" role="data"/><file name="sfDoctrineDataRetriever.class.php" role="data"/><file name="sfDoctrineEventListener.class.php" role="data"/><file name="sfDoctrineException.class.php" role="data"/><file name="sfDoctrinePager.class.php" role="data"/><file name="sfDoctrineQueryLogger.class.php" role="data"/><file name="sfDoctrineRecord.class.php" role="data"/><file name="sfDoctrineRecordI18n.class.php" role="data"/><file name="sfDoctrineSchemasConfigHandler.class.php" role="data"/><file name="sfDoctrineUniqueValidator.php" role="data"/></dir><file name="LICENSE" role="data"/><file name="README" role="data"/><dir name="test"><dir name="bootstrap"><file name="config.php" role="data"/><file name="functional.php" role="data"/><file name="unit.php" role="data"/></dir><file name="coverage.php" role="data"/><dir name="functional"/><dir name="other"/><file name="prove.php" role="data"/><file name="tests.php" role="data"/><dir name="unit"><dir name="addon"><dir name="fixtures"><file name="doctrineTestSchema.yml" role="data"/><file name="propelTestSchema.xml" role="data"/><file name="propelTestSchema.yml" role="data"/></dir><file name="sfDoctrineClassTest.php" role="data"/><file name="sfDoctrineColumnTest.php" role="data"/><file name="sfDoctrineRelationTest.php" role="data"/><file name="sfDoctrineSchemaDoctrineLoaderTest.php" role="data"/><file name="sfDoctrineSchemaPropelLoaderTest.php" role="data"/><file name="sfDoctrineTableTest.php" role="data"/></dir><dir name="lib"/></dir></dir><file name="TODO.txt" role="data"/></dir></contents>
<dependencies>
<required>
<php>
<min>5.1.0</min>
</php>
<pearinstaller>
<min>1.4.1</min>
</pearinstaller>
<package>
<name>symfony</name>
<channel>pear.symfony-project.com</channel>
<min>1.0.0</min>
<max>1.1.0</max>
<exclude>1.1.0</exclude>
</package>
</required>
</dependencies>
<phprelease>
</phprelease>
<changelog>
</changelog>
</package>
<?php
// comment or remove the following message
die('Please define the path to the symfony library in '.realpath(__FILE__)."\n");
$sf_symfony_lib_dir = '';
$sf_symfony_data_dir = '';
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
<?xml version="1.0" encoding="UTF-8"?>
<database name="doctrineTestSchema" defaultIdMethod="native">
<table name="testTable" phpName="TestTable">
<column name="name" type="longvarchar" />
<column name="description" type="longvarchar" />
<column name="id" type="integer" primaryKey="true" autoIncrement="true" />
<foreign-key foreignTable="dummy">
<reference foreign="id" local="dummy_id"/>
</foreign-key>
</table>
<table name="dummy" phpName="DummyPHP">
<column name="foo" type="integer"/>
</table>
</database>
\ No newline at end of file
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment