Ver código fonte

[example] created an example on initialization of entity manager with extensions

gedi 13 anos atrás
pai
commit
48847d3314

+ 16 - 0
README.md

@@ -8,6 +8,12 @@
 master branch is based on 2.2.x versions and may not work with 2.1.x components. ODM currently
 master branch is based on 2.2.x versions and may not work with 2.1.x components. ODM currently
 does not work with **doctrine common 2.2.x**
 does not work with **doctrine common 2.2.x**
 
 
+**2011-12-20**
+
+- Added [example](https://github.com/l3pp4rd/DoctrineExtensions/tree/master/example)
+on how to create entity manager with extensions hooked using environment without framework
+- To run this example follow the documentation on the bottom of this document
+
 **2011-10-30**
 **2011-10-30**
 
 
 - Support for doctrine common **2.2.x** with backward compatibility. Be sure to use all components
 - Support for doctrine common **2.2.x** with backward compatibility. Be sure to use all components
@@ -99,6 +105,16 @@ To setup and run tests follow these steps:
 - run: **phpunit -c tests**
 - run: **phpunit -c tests**
 - optional - run mongodb in background to complete all tests
 - optional - run mongodb in background to complete all tests
 
 
+### Running the example:
+
+To setup and run example follow these steps:
+
+- go to the root directory of extensions
+- run: **php bin/vendors.php** installs doctrine and required symfony libraries
+- edit **example/em.php** and configure your database on top of the file
+- run: **./example/bin/console** or **php example/bin/console**
+- run: **php example/run.php** to run example
+
 ### Contributors:
 ### Contributors:
 
 
 - acasademont [acasademont](https://github.com/acasademont)
 - acasademont [acasademont](https://github.com/acasademont)

+ 184 - 0
example/app/Entity/Category.php

@@ -0,0 +1,184 @@
+<?php
+namespace Entity;
+
+use Doctrine\Common\Collections\ArrayCollection;
+use Gedmo\Mapping\Annotation as Gedmo;
+use Doctrine\ORM\Mapping as ORM;
+
+/**
+ * @Gedmo\Tree(type="nested")
+ * @ORM\Table(name="ext_categories")
+ * @ORM\Entity(repositoryClass="Entity\Repository\CategoryRepository")
+ */
+class Category
+{
+    /**
+     * @ORM\Column(type="integer")
+     * @ORM\Id
+     * @ORM\GeneratedValue
+     */
+    private $id;
+
+    /**
+     * @Gedmo\Translatable
+     * @Gedmo\Slug(fields={"title"})
+     * @ORM\Column(length=64, unique=true)
+     */
+    private $slug;
+
+    /**
+     * @Gedmo\Translatable
+     * @ORM\Column(length=64)
+     */
+    private $title;
+
+    /**
+     * @Gedmo\TreeLeft
+     * @ORM\Column(type="integer")
+     */
+    private $lft;
+
+    /**
+     * @Gedmo\TreeRight
+     * @ORM\Column(type="integer")
+     */
+    private $rgt;
+
+    /**
+     * @Gedmo\TreeParent
+     * @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
+     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", onDelete="SET NULL")
+     */
+    private $parent;
+
+    /**
+     * @Gedmo\TreeRoot
+     * @ORM\Column(type="integer", nullable=true)
+     */
+    private $root;
+
+    /**
+     * @Gedmo\TreeLevel
+     * @ORM\Column(name="lvl", type="integer")
+     */
+    private $level;
+
+    /**
+     * @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
+     */
+    private $children;
+
+    /**
+     * @Gedmo\Translatable
+     * @ORM\Column(type="text", nullable=true)
+     */
+    private $description;
+
+    /**
+     * @Gedmo\Timestampable(on="create")
+     * @ORM\Column(type="datetime")
+     */
+    private $created;
+
+    /**
+     * @Gedmo\Timestampable(on="update")
+     * @ORM\Column(type="datetime")
+     */
+    private $updated;
+
+    /**
+     * Used locale to override Translation listener`s locale
+     * @Gedmo\Locale
+     */
+    private $locale;
+
+    public function __construct()
+    {
+    	$this->children = new ArrayCollection();
+    }
+
+    public function getSlug()
+    {
+        return $this->slug;
+    }
+
+    public function getId()
+    {
+        return $this->id;
+    }
+
+    public function setTitle($title)
+    {
+        $this->title = $title;
+    }
+
+    public function getTitle()
+    {
+        return $this->title;
+    }
+
+    public function setDescription($description)
+    {
+        $this->description = strip_tags($description);
+    }
+
+    public function getDescription()
+    {
+        return $this->description;
+    }
+
+	public function setParent($parent)
+    {
+        $this->parent = $parent;
+    }
+
+    public function getParent()
+    {
+        return $this->parent;
+    }
+
+    public function getRoot()
+    {
+        return $this->root;
+    }
+
+    public function getLevel()
+    {
+        return $this->level;
+    }
+
+    public function getChildren()
+    {
+        return $this->children;
+    }
+
+    public function getLeft()
+    {
+    	return $this->lft;
+    }
+
+	public function getRight()
+    {
+        return $this->rgt;
+    }
+
+    public function getCreated()
+    {
+        return $this->created;
+    }
+
+    public function getUpdated()
+    {
+        return $this->updated;
+    }
+
+    public function setTranslatableLocale($locale)
+    {
+        $this->locale = $locale;
+    }
+
+    public function __toString()
+    {
+        return $this->getTitle();
+    }
+}

+ 10 - 0
example/app/Entity/Repository/CategoryRepository.php

@@ -0,0 +1,10 @@
+<?php
+
+namespace Entity\Repository;
+
+use Gedmo\Tree\Entity\Repository\NestedTreeRepository;
+
+class CategoryRepository extends NestedTreeRepository
+{
+
+}

+ 6 - 0
example/bin/console

@@ -0,0 +1,6 @@
+#!/usr/bin/env php
+<?php
+
+$cli = include __DIR__.'/console.php';
+$cli->run();
+

+ 40 - 0
example/bin/console.php

@@ -0,0 +1,40 @@
+<?php
+
+$em = include __DIR__.'/../em.php';
+
+$cli = new Symfony\Component\Console\Application('My CLI interface', '1.0.0');
+$cli->setCatchExceptions(true);
+// commands
+$cli->addCommands(array(
+    // DBAL Commands
+    new Doctrine\DBAL\Tools\Console\Command\RunSqlCommand(),
+    new Doctrine\DBAL\Tools\Console\Command\ImportCommand(),
+
+    // ORM Commands
+    new Doctrine\ORM\Tools\Console\Command\ClearCache\MetadataCommand(),
+    new Doctrine\ORM\Tools\Console\Command\ClearCache\ResultCommand(),
+    new Doctrine\ORM\Tools\Console\Command\ClearCache\QueryCommand(),
+    new Doctrine\ORM\Tools\Console\Command\SchemaTool\CreateCommand(),
+    new Doctrine\ORM\Tools\Console\Command\SchemaTool\UpdateCommand(),
+    new Doctrine\ORM\Tools\Console\Command\SchemaTool\DropCommand(),
+    new Doctrine\ORM\Tools\Console\Command\EnsureProductionSettingsCommand(),
+    new Doctrine\ORM\Tools\Console\Command\ConvertDoctrine1SchemaCommand(),
+    new Doctrine\ORM\Tools\Console\Command\GenerateRepositoriesCommand(),
+    new Doctrine\ORM\Tools\Console\Command\GenerateEntitiesCommand(),
+    new Doctrine\ORM\Tools\Console\Command\GenerateProxiesCommand(),
+    new Doctrine\ORM\Tools\Console\Command\ConvertMappingCommand(),
+    new Doctrine\ORM\Tools\Console\Command\RunDqlCommand(),
+    new Doctrine\ORM\Tools\Console\Command\ValidateSchemaCommand(),
+));
+// helpers
+$helpers = array(
+    'db' => new Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper($em->getConnection()),
+    'em' => new Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper($em),
+    'dialog' => new Symfony\Component\Console\Helper\DialogHelper(),
+);
+foreach ($helpers as $name => $helper) {
+    $cli->getHelperSet()->set($helper, $name);
+}
+
+return $cli;
+

+ 99 - 0
example/em.php

@@ -0,0 +1,99 @@
+<?php
+// connection args, modify at will
+$connection = array(
+    'host' => '127.0.0.1',
+    'port' => 3306,
+    'user' => 'root',
+    'password' => 'nimda',
+    'dbname' => 'test',
+    'driver' => 'pdo_mysql'
+);
+
+// First of all autoloading of vendors
+
+$vendorPath = realpath(__DIR__.'/../vendor');
+$gedmoPath = realpath(__DIR__.'/../lib');
+
+$doctrineClassLoaderFile = $vendorPath.'/doctrine-common/lib/Doctrine/Common/ClassLoader.php';
+if (!file_exists($doctrineClassLoaderFile)) {
+    die('cannot find vendor, run: php bin/vendors.php to install doctrine');
+}
+
+require $doctrineClassLoaderFile;
+use Doctrine\Common\ClassLoader;
+// autoload all vendors
+
+$loader = new ClassLoader('Doctrine\Common', $vendorPath.'/doctrine-common/lib');
+$loader->register();
+
+$loader = new ClassLoader('Doctrine\DBAL', $vendorPath.'/doctrine-dbal/lib');
+$loader->register();
+
+$loader = new ClassLoader('Doctrine\ORM', $vendorPath.'/doctrine-orm/lib');
+$loader->register();
+
+// gedmo extensions
+$loader = new ClassLoader('Gedmo', $gedmoPath);
+$loader->register();
+
+// if you use yaml, you need a yaml parser, same as command line tool
+$loader = new ClassLoader('Symfony', $vendorPath);
+$loader->register();
+
+// autoloader for Entity namespace
+$loader = new ClassLoader('Entity', __DIR__.'/app');
+$loader->register();
+// Second configure ORM
+
+$config = new Doctrine\ORM\Configuration;
+$config->setProxyDir(sys_get_temp_dir());
+$config->setProxyNamespace('Proxy');
+$config->setAutoGenerateProxyClasses(false);
+
+// standard annotation reader
+$annotationReader = new Doctrine\Common\Annotations\AnnotationReader;
+// gedmo annotation loader
+Doctrine\Common\Annotations\AnnotationRegistry::registerAutoloadNamespace(
+    'Gedmo\Mapping\Annotation',
+    $gedmoPath
+);
+// standard doctrine annotations
+Doctrine\Common\Annotations\AnnotationRegistry::registerFile(
+    $vendorPath.'/doctrine-orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php'
+);
+// register annotation driver
+$driverChain = new Doctrine\ORM\Mapping\Driver\DriverChain();
+$annotationDriver = new Doctrine\ORM\Mapping\Driver\AnnotationDriver($annotationReader, array(
+    __DIR__.'/app/Entity', // example entity
+    $gedmoPath.'/Gedmo/Translatable/Entity',
+    $gedmoPath.'/Gedmo/Loggable/Entity',
+    $gedmoPath.'/Gedmo/Tree/Entity',
+));
+
+// drivers for diferent namespaces
+$driverChain->addDriver($annotationDriver, 'Entity');
+$driverChain->addDriver($annotationDriver, 'Gedmo\Translatable\Entity');
+$driverChain->addDriver($annotationDriver, 'Gedmo\Loggable\Entity');
+$driverChain->addDriver($annotationDriver, 'Gedmo\Tree\Entity');
+
+// register metadata driver
+$config->setMetadataDriverImpl($driverChain);
+// cache
+$config->setMetadataCacheImpl(new Doctrine\Common\Cache\ArrayCache);
+$config->setQueryCacheImpl(new Doctrine\Common\Cache\ArrayCache);
+
+$evm = new Doctrine\Common\EventManager();
+// gedmo extension listeners
+$evm->addEventSubscriber(new Gedmo\Sluggable\SluggableListener);
+$evm->addEventSubscriber(new Gedmo\Tree\TreeListener);
+$evm->addEventSubscriber(new Gedmo\Loggable\LoggableListener);
+$evm->addEventSubscriber(new Gedmo\Timestampable\TimestampableListener);
+$translatable = new Gedmo\Translatable\TranslationListener;
+$translatable->setTranslatableLocale('en');
+$translatable->setDefaultLocale('en');
+$evm->addEventSubscriber($translatable);
+
+// mysql set names UTF-8
+$evm->addEventSubscriber(new Doctrine\DBAL\Event\Listeners\MysqlSessionInit());
+// create entity manager
+return Doctrine\ORM\EntityManager::create($connection, $config, $evm);

+ 78 - 0
example/run.php

@@ -0,0 +1,78 @@
+<?php
+$executionStart = microtime(true);
+
+$em = include 'em.php';
+
+/**
+ * initialized in em.php
+ *
+ * Gedmo\Translatable\TranslationListener
+ */
+$translatable;
+
+$repository = $em->getRepository('Entity\Category');
+$food = $repository->findOneByTitle('Food');
+if (!$food) {
+    // lets create some categories
+    $food = new Entity\Category;
+    $food->setTitle('Food');
+
+    $fruits = new Entity\Category;
+    $fruits->setParent($food);
+    $fruits->setTitle('Fruits');
+
+    $apple = new Entity\Category;
+    $apple->setParent($fruits);
+    $apple->setTitle('Apple');
+
+    $milk = new Entity\Category;
+    $milk->setParent($food);
+    $milk->setTitle('Milk');
+
+    $em->persist($food);
+    $em->persist($milk);
+    $em->persist($fruits);
+    $em->persist($apple);
+    $em->flush();
+
+    // translate into LT
+    $translatable->setTranslatableLocale('lt');
+    $food->setTitle('Maistas');
+    $fruits->setTitle('Vaisiai');
+    $apple->setTitle('Obuolys');
+    $milk->setTitle('Pienas');
+
+    $em->persist($food);
+    $em->persist($milk);
+    $em->persist($fruits);
+    $em->persist($apple);
+    $em->flush();
+    // set locale back to en
+    $translatable->setTranslatableLocale('en');
+}
+
+// builds tree
+$build = function ($nodes) use (&$build, $repository) {
+    $result = '';
+    foreach ($nodes as $node) {
+        $result .= str_repeat("-", $node->getLevel())
+            . $node->getTitle()
+            . '('.$node->getSlug().')'
+            . PHP_EOL
+        ;
+        if ($repository->childCount($node, false)) {
+            $result .= $build($repository->children($node, true));
+        }
+    }
+    return $result;
+};
+
+$nodes = $repository->getRootNodes();
+echo $build($nodes).PHP_EOL.PHP_EOL;
+// change locale
+$translatable->setTranslatableLocale('lt');
+$nodes = $repository->getRootNodes(); // reload in diferent locale
+echo $build($nodes).PHP_EOL.PHP_EOL;
+
+$ms = round(microtime(true) - $executionStart, 4) * 1000;
+echo "Execution took: {$ms} ms";