Commit dbe05c87 authored by Avris's avatar Avris

docs

parent 83e39d23
......@@ -3,260 +3,60 @@
This is a module for [Micrus framework](https://micrus.avris.it) that allows you
to integrate it with [Doctrine ORM](http://www.doctrine-project.org/projects/orm.html).
To install this module, open the file `app/Config/modules.yml` and add:
### Installations
- Avris\Micrus\Doctrine\DoctrineModule
In your `App\App:registerModules` register the module:
Then run:
yield new \Avris\Micrus\Doctrine\DoctrineModule;
then run:
composer require avris/micrus-doctrine
You will be asked for a [connection string](http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/configuration.html#connecting-using-a-url)
and it will be saved in the `.env` file.
### Example usage ###
### EntityManager
<?php
namespace App\Model;
`DoctrineManager` will scan all modules for a `/src/Entity` directory and if it's there --
it will automatically register all classes from this directory as doctrine entities.
use Avris\Micrus\Controller\Http\UploadedFile;
use Avris\Micrus\Forms\Widget\ChoiceHelper;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ORM\Mapping as ORM;
Doctrine's `EntityManager` is registered in the container as `Doctrine\ORM\EntityManagerInterface`:
/**
* @ORM\Entity
* @ORM\Table(name="post")
* @ORM\HasLifecycleCallbacks
**/
class Post
public function incrementStuffAction(EntityManagerInterface $em)
{
/**
* @var integer
* @ORM\Id
* @ORM\Column(type="integer")
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var string
* @ORM\Column(type="string")
*/
protected $title;
/**
* @var string
* @ORM\Column(type="text")
*/
protected $content;
/**
* @var \DateTime
* @ORM\Column(type="datetime")
*/
protected $publishedAt;
/**
* @var User
* @ORM\ManyToOne(targetEntity="User", inversedBy="posts")
**/
protected $user;
/**
* @var Category[]|ArrayCollection
* @ORM\ManyToMany(targetEntity="Category", inversedBy="posts")
* @ORM\JoinTable(name="category_post")
**/
protected $categories;
/**
* @var UploadedFile
*/
protected $attachment;
/**
* @var string
* @ORM\Column(type="string", nullable=true)
*/
protected $file;
public function __construct()
{
$this->categories = new ArrayCollection();
$this->publishedAt = new \DateTime();
}
/**
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* @param string $title
* @return $this
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* @param string $content
* @return $this
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* @return \DateTime
*/
public function getPublishedAt()
{
return $this->publishedAt;
}
/**
* @param \DateTime $publishedAt
* @return $this
*/
public function setPublishedAt($publishedAt)
{
$this->publishedAt = $publishedAt;
return $this;
}
/**
* @return User
*/
public function getUser()
{
return $this->user;
}
/**
* @param User $user
*/
public function setUser($user)
{
$this->user = $user;
}
/**
* @return Category[]|ArrayCollection
*/
public function getCategories()
{
return $this->categories;
}
/**
* @param Category $category
* @return $this
*/
public function addCategories(Category $category)
{
if (!$this->categories->contains($category)) {
$this->categories->add($category);
}
return $this;
}
/**
* @param Category $category
* @return $this
*/
public function removeCategories(Category $category)
{
$this->categories->removeElement($category);
return $this;
}
/**
* @return UploadedFile
*/
public function getAttachment()
{
return $this->attachment;
}
$stuff = $em->getRepository('Stuff')->findBySomeCustomCondition();
$stuff->incrementValue();
$em->persist($stuff);
$em->flush();
$this->addFlash('success', 'Stuff incremented successfully');
/**
* @param UploadedFile $attachment
*/
public function setAttachment(UploadedFile $attachment)
{
$this->attachment = $attachment;
}
return $this->redirectToRoute('home');
}
/**
* @return string
*/
public function getFile()
{
return $this->file;
}
### UserProvider
/**
* @ORM\PrePersist
* @ORM\PreUpdate
*/
public function handleFileUpload()
{
if (!$this->attachment) {
return;
}
This module registers Doctrine as the `UserProvider`.
It will try to find a user from `App\Entity\User` repository using `email` as identifier.
To modify those values, just use the container:
$filename = substr(md5(uniqid()), 0, 8) . '.' . $this->attachment->getExtension();
if ($this->attachment->moveTo('run/att/' . $filename)) {
$this->file = $filename;
}
}
}
Avris\Micrus\Doctrine\DoctrineUserProvider:
arguments:
$column: username
**Note the convention** that is important for binding on object to a form and displaying obejct's values in Twig templates:
if an attribute `$fieldName` is not public, it will be accessed using `getFieldName` and `setFieldName`, or if it's an array:
`getFieldName`, `addFieldName`, `removeFieldName` and `hasFieldName`.
### MatchProvider
You can use Doctrine's EntityManager, retrieving it with `$this->getEm()` (in controllers) or `$container->get('orm')->getEntityManager()`.
You can fetch repositories simply by the entity's name:
Doctrine will automatically match the arguments of your controller if they are entities, for example:
public function incrementStuffAction()
{
$stuff = $this->getEm()->getRepository('Stuff')->findBySomeCustomCondition();
$stuff->incrementValue();
$this->getEm()->persist($stuff);
$this->getEm()->flush();
$this->addFlash('success', 'Stuff incremented successfully');
return $this->redirectToRoute('home');
}
/**
* @M\Route("/post/{int:id}/read")
*/
public function readAction(Post $post) { }
For request `GET /post/8/read` will try to find `App\Entity\Post` with `id = 8`
and either return it or throw a `NotFoundHttpException` if failed.
### Console ###
### Console
Some Doctrine console commands are available in `bin/micrus` under `db` namespace:
......@@ -264,14 +64,11 @@ Some Doctrine console commands are available in `bin/micrus` under `db` namespac
php bin/micrus db:schema:update
php bin/micrus db:schema:validate
php bin/micrus db:schema:drop
php bin/micrus db:query:sql "SELECT * FROM user"
php bin/micrus db:query:dql "SELECT u FROM App\Model\User u WHERE u.role='ROLE_ADMIN'"
You can also use `php bin/mdoctrine` to access more advanced commands from Doctrine.
### Copyright ###
### Copyright
* **Author:** Andrzej Prusinowski [(Avris.it)](https://avris.it)
* **Author:** Andre Prusinowski [(Avris.it)](https://avris.it)
* **Licence:** [MIT](https://mit.avris.it)
......@@ -16,6 +16,5 @@
},
"autoload": {
"psr-4": { "Avris\\Micrus\\Doctrine\\": "src" }
},
"bin": ["mdoctrine"]
}
}
#!/usr/bin/env php
<?php
use Avris\Micrus\Bootstrap\AbstractApp;
use Doctrine\DBAL\Tools\Console\Helper\ConnectionHelper;
use Doctrine\ORM\EntityManager;
use Doctrine\ORM\Tools\Console\ConsoleRunner;
use Doctrine\ORM\Tools\Console\Helper\EntityManagerHelper;
use Symfony\Component\Console\Application;
set_time_limit(0);
foreach (['', '/..', '/../..', '/../../..'] as $dir) {
if (file_exists($autoloader = __DIR__ . $dir . '/vendor/autoload.php')) {
require_once $autoloader;
break;
}
}
/** @var EntityManager $em */
$em = (new AbstractApp('cli', dirname(dirname($autoloader))))->getContainer()->get('orm')->getEntityManager();
$app = new Application('Doctrine');
$helperSet = $app->getHelperSet();
$helperSet->set(new ConnectionHelper($em->getConnection()), 'db');
$helperSet->set(new EntityManagerHelper($em), 'em');
ConsoleRunner::addCommands($app);
$app->run();
\ No newline at end of file
<?php
namespace Avris\Micrus\Doctrine;
use Avris\Bag\Bag;
use Avris\Dispatcher\EventSubscriberInterface;
use Avris\Micrus\Bootstrap\ModuleInterface;
use Avris\Micrus\Console\ConsoleWarmupEvent;
......@@ -29,8 +28,7 @@ final class DoctrineManager implements EventSubscriberInterface
LoggerInterface $logger,
DoctrineLogger $doctrineLogger,
Cache $cache = null
)
{
) {
$dirs = [];
/** @var ModuleInterface $module */
foreach (array_reverse($modules) as $module) {
......@@ -107,8 +105,6 @@ final class DoctrineManager implements EventSubscriberInterface
$app->add((new ORMCommand\SchemaTool\UpdateCommand())->setName('db:schema:update'));
$app->add((new ORMCommand\SchemaTool\DropCommand())->setName('db:schema:drop'));
$app->add((new ORMCommand\ValidateSchemaCommand())->setName('db:schema:validate'));
$app->add((new ORMCommand\GenerateProxiesCommand())->setName('db:generate:proxies'));
}
public function getSubscribedEvents(): iterable
......
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