[indent][indent][indent]http://www.html.de/attachment.php?attachmentid=1822&d=1295523305 Edit http://www.html.de/attachment.php?attachmentid=1822&d=1295523305
Startpunkt in der Doctrine-Dokumentation:
Es wäre sinnvoll, dort parallel zu lesen.
[/indent][/indent][/indent]
[center]* * *[/center]
Kleines Doctrine-Beispiel:
-
Doctrine 2.0.0 runterladen: Doctrine - Download Object Relational Mapper 2.0.0
-
Entpacken und das Doctrine-Verzeichnis aus dem Archiv in das library-Verzeichnis des Projekts kopieren.
-
Das Symfony-Verzeichnis aus dem library/Doctrine-Verzeichnis heraus ins library-Verzeichnis verschieben.
-
Übrige Verzeichnisse und Dateien anlegen (siehe unten). ./library/org/example/Guestbook/Proxies und ./data müssen vom Webserver beschrieben werden können.
.
├── config
│ └── mappings
│ └── org.example.Guestbook.Entities.Entry.dcm.yml
├── data
├── index.php
└── library
├── Doctrine […]
├── org
│ └── example
│ └── Guestbook
│ ├── Entities
│ │ └── Entry.php
│ └── Proxies
└── Symfony
└── Component
├── Console […]
└── Yaml […]
- Inhalt von ./library/org/example/Guestbook/Entities/Entry.php:
[code]<?php
namespace org\example\Guestbook\Entities;
class Entry
{
protected $id;
protected $author;
protected $createdOn;
protected $homepage;
protected $content;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
}
public function getAuthor()
{
return $this->author;
}
public function setAuthor($author)
{
$this->author = $author;
}
public function getCreatedOn()
{
return $this->createdOn;
}
public function setCreatedOn($createdOn)
{
$this->createdOn = $createdOn;
}
public function getHomepage()
{
return $this->homepage;
}
public function setHomepage($homepage)
{
$this->homepage = $homepage;
}
public function getContent()
{
return $this->content;
}
public function setContent($content)
{
$this->content = $content;
}
}[/code]
- Inhalt von ./config/mappings/org.example.Guestbook.Entities.Entry.dcm.yml:
org\example\Guestbook\Entities\Entry:
type: entity
table: entries
id:
id:
type: integer
generator:
strategy: AUTO
fields:
author:
type: string
createdOn:
type: datetime
homepage:
type: string
content:
type: text
- Inhalt von ./index.php:
[code]<?php
use Doctrine\Common\Cache\ArrayCache,
Doctrine\Common\EventManager,
Doctrine\ORM\Configuration,
Doctrine\ORM\EntityManager,
Doctrine\ORM\Mapping\ClassMetadataFactory,
Doctrine\ORM\Mapping\Driver\YamlDriver,
Doctrine\ORM\Tools\SchemaTool,
org\example\Guestbook\Entities\Entry;
/**
*
-
@param array $dbConnectionParams
-
@return EntityManager
*/
function initializeOrm($dbConnectionParams)
{
$config = new Configuration();
// Proxy Configuration
$config->setProxyDir(‚./library/org/example/Guestbook/Proxies‘);
$config->setProxyNamespace(‚org\example\Guestbook\Proxies‘);
$config->setAutoGenerateProxyClasses(true);
// Entity alias configuration
$config->addEntityNamespace(‚Gb‘, ‚org\example\Guestbook\Entities‘);
// Mapping Configuration
$config->setMetadataDriverImpl(new YamlDriver(‚./config/mappings‘));
// Caching Configuration
$cache = new ArrayCache();
$config->setMetadataCacheImpl($cache);
$config->setQueryCacheImpl($cache);
$entityManager = EntityManager::create($dbConnectionParams, $config);
return $entityManager;
}
/**
*
- @param EntityManager $entityManager
*/
function createSchema(EntityManager $entityManager)
{
$st = new SchemaTool($entityManager);
$st->createSchema($entityManager->getMetadataFactory()->getAllMetadata());
}
/**
*
-
@param EntityManager $entityManager
-
@param int $from
-
@param int $maxAmount
-
@return array
*/
function getEntries(EntityManager $entityManager, $from = 0, $maxAmount = 20)
{
$dql = „SELECT e FROM Gb:Entry e ORDER BY e.createdOn DESC“;
$query = $entityManager->createQuery($dql);
$query->setFirstResult($from);
$query->setMaxResults($maxAmount);
return $query->getResult();
}
/**
*
- @param EntityManager $entityManager
- @param Entry $entry
*/
function addEntry(EntityManager $entityManager, Entry $entry)
{
$entityManager->persist($entry);
$entityManager->flush();
}
/**
*
- @param string $s
- @return string
*/
function escape($s)
{
return htmlspecialchars($s, ENT_QUOTES, ‚UTF-8‘);
}
error_reporting(-1);
set_include_path(realpath(‚./library‘) . PATH_SEPARATOR . get_include_path());
spl_autoload_register(function ($className)
{
require_once str_replace(‚\‘, ‚/‘, $className) . ‚.php‘;
});
/* SQLite config */
$conn = array(
‚driver‘ => ‚pdo_sqlite‘,
‚path‘ => ‚./data/db.sqlite‘
);
/* MySQL config */
//$conn = array(
// ‚driver‘ => ‚pdo_mysql‘,
// ‚user‘ => ‚‘,
// ‚password‘ => ‚‘,
// ‚host‘ => ‚localhost‘,
// ‚dbname‘ => ‚test‘
//);
/* PostgreSQL config */
//$conn = array(
// ‚driver‘ => ‚pdo_pgsql‘,
// ‚user‘ => ‚‘,
// ‚password‘ => ‚‘,
// ‚host‘ => ‚localhost‘,
// ‚dbname‘ => ‚test‘
//);
$entityManager = initializeOrm($conn);
//createSchema($entityManager);
$errors = array();
if (count($_POST) > 0) {
$vars[‚name‘] =
(isset($_POST[‚name‘])) ? trim((string) $_POST[‚name‘]) : ‚‘;
$vars[‚homepage‘] =
(isset($_POST[‚homepage‘])) ? trim((string) $_POST[‚homepage‘]) : ‚‘;
$vars[‚content‘] =
(isset($_POST[‚content‘])) ? trim((string) $_POST[‚content‘]) : ‚‘;
if ($vars['name'] === '' || $vars['content'] === '') {
$errors[] = 'Please enter your name and a text.';
}
if ($vars['homepage'] !== ''
&& !filter_var($vars['homepage'], FILTER_VALIDATE_URL)
) {
$errors[] = 'Please specify a valid URL for homepage or leave the field
empty.';
}
if (count($errors) === 0) {
$newEntry = new Entry();
$newEntry->setHomepage($vars['homepage']);
$newEntry->setAuthor($vars['name']);
$newEntry->setCreatedOn(new DateTime(null, new DateTimeZone('UTC')));
$newEntry->setContent($vars['content']);
addEntry($entityManager, $newEntry);
$_POST = array();
}
}
$tpl = array();
$tpl[‚errors‘] = $errors;
$tpl[‚entries‘] = getEntries($entityManager, 0, 50);
?>
Doctrine/Guestbook demo
- {
padding: 0;
margin: 0;
}
body {
padding: 2em;
}
.entry {
border: 0.0625em solid #ccc;
padding: 1em;
margin-bottom: 1em;
}
</style>
<h1>Guestbook</h1>
<?php if (count($tpl['errors']) > 0) : ?>
<p>One or more errors occurred.</p>
<?php foreach ($tpl['errors'] as $error) : ?>
<p><?php echo escape($error); ?></p>
<?php endforeach; ?>
<?php endif; ?>
<h2>Add entry</h2>
<form method="post" action="">
<p>Name: <input name="name" type="text" value="<?php
echo (isset($_POST['name']))
? escape((string) $_POST['name']) : '';
?>" /></p>
<p>Homepage: <input name="homepage" type="text" value="<?php
echo (isset($_POST['homepage']))
? escape((string) $_POST['homepage']) : '';
?>" /></p>
<p>Content:</p>
<p><textarea name="content" cols="40" rows="15"><?php
echo (isset($_POST['content']))
? escape((string) $_POST['content']) : '';
?></textarea></p>
<p><input type="submit" value="Send" /></p>
</form>
<hr />
<h2>Entries</h2>
<?php if (count($tpl['entries']) === 0) : ?>
<p>No entries yet.</p>
<?php else : ?>
<?php foreach ($tpl['entries'] as $entry) : ?>
<div class="entry">
<p>#<?php echo $entry->getid(); ?>
<?php echo escape($entry->getAuthor()); ?>:</p>
<p><?php echo nl2br(escape($entry->getContent())); ?></p>
</div>
<?php endforeach; ?>
<?php endif; ?>
[/code]
- Für jeden eingesetzten DBMS-Driver muss einmalig die createSchema-Funktion (derzeit auskommentiert) aufgerufen werden, um die entsprechende Tabelle zu erstellen.
Doctrine-Dokumentation: Welcome to Doctrine 2 ORM?s documentation! — Doctrine 2 ORM v2.0.0 documentation