Giter VIP home page Giter VIP logo

doctrine-entities-generator-bundle's Introduction

EcommitDoctrineEntitiesGeneratorBundle

The EcommitDoctrineEntitiesGeneratorBundle bundle (for Symfony) allows the user to re(generate) getters-setters methods for Doctrine ORM entities.

Tests

Installation

Install the bundle with Composer : In your project directory, execute the following command :

$ composer require ecommit/doctrine-entities-generator-bundle

Enable the bundle in the config/bundles.php file for your project :

return [
    //...
    Ecommit\DoctrineEntitiesGeneratorBundle\EcommitDoctrineEntitiesGeneratorBundle::class => ['dev' => true],
    //...
];

Usage

Add the start tag to your entity :

    /*
     * Getters / Setters (auto-generated)
     */

WARNING : The content between this start tag and the end of the PHP class will be deleted when the bundle generates the getters-setters methods. The getters-setters methods will be generated between these two tags.

For example:

use Doctrine\ORM\Mapping as ORM;

#[ORM\Entity]
#[ORM\Table(name: 'category')]
class Category
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer', name: 'category_id')]
    protected $categoryId;

    #[ORM\Column(type: 'string', length: 255)]
    protected $name;

    /*
     * Getters / Setters (auto-generated)
     */

    //Content after this block will be deleted when
    //the bundle generates the getters-setters methods.
    //Getters-setters methods will be generated here.
}

You can change the start tag and the end tag (the end of the PHP class by default) : See the "FAQ" section.

In your project directory, execute the following command :

$ php bin/console ecommit:doctrine:generate-entities {Classename}

For example:

$ php bin/console ecommit:doctrine:generate-entities App/Entity/MyEntity

Each slash is replaced by an anti-slash.

You can use the * joker (which generates multiple entities). For example:

$ php bin/console ecommit:doctrine:generate-entities App/Entity/*

The bundle generates getters-setters methods for an entity only if :

  • The PHP class is a Doctrine ORM entity; and
  • The entity is not an interface; and
  • The entity is not a trait; and
  • The entity doesn't use the Ecommit\DoctrineEntitiesGeneratorBundle\Attribute\IgnoreGenerateEntity attribute.

The bundle generates getters-setters methods for an entity property only if :

  • The property is defined directly in the entity (and is not defined in an inherited class or a trait); and
  • The property is not public; and
  • The methods (getters-setters) do not exist (except if the method is defined between the start and end tags).

FAQ

How can I change the generated code ?

When the code is generated, the @EcommitDoctrineEntitiesGenerator/Theme/base.php.twig Twig template is used.

You can create a custom template (that extends the base template).

Solution 1 - Override the bundle

See https://symfony.com/doc/current/bundles/override.html

Solution 2 - Configure the template

In your project configuration, you can configure the theme used by the bundle. For example, you can create the config/packages/dev/ecommit_doctrine_entities_generator.yaml file:

ecommit_doctrine_entities_generator:
    template: "your_template.php.twig"

Solution 3 - Create a custom template in entity

You can override the theme to be used by the bundle only for an entity. To do this, use the Ecommit\DoctrineEntitiesGeneratorBundle\Attribute\GenerateEntityTemplate attribute:

use Doctrine\ORM\Mapping as ORM;
use Ecommit\DoctrineEntitiesGeneratorBundle\Attribute\GenerateEntityTemplate;

#[ORM\Entity]
#[ORM\Table(name: 'category')]
#[GenerateEntityTemplate("your_template.php.twig")]
class Category
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer', name: 'category_id')]
    protected $categoryId;
    //...
}

How can I change the start-end tags ?

You can change the template (see previous question).

The start tag is defined in the start_tag Twig block.

The end tag is defined in the end_tag Twig block.

For example, you can create this theme:

{% extends '@EcommitDoctrineEntitiesGenerator/Theme/base.php.twig' %}

{% block end_tag %}


    /*
     * End Getters / Setters (auto-generated)
     */
{% endblock %}

and use as follows:

use Doctrine\ORM\Mapping as ORM;
use Ecommit\DoctrineEntitiesGeneratorBundle\Attribute\GenerateEntityTemplate;

#[ORM\Entity]
#[ORM\Table(name: 'category')]
#[GenerateEntityTemplate('your_template.php.twig')]
class Category
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer', name: 'category_id')]
    protected $categoryId;
    //...

    /*
     * Getters / Setters (auto-generated)
     */


    /*
     * End Getters / Setters (auto-generated)
     */
}

How can I create a constructor in my entity ?

If your entity has a TOMANY association, the bundle will create a constructor in your entity. For this reason, manually defining a constructor in your entity is not allowed.

Instead, you can use the Ecommit\DoctrineEntitiesGeneratorBundle\Entity\EntityInitializerInterface interface and its initializeEntity method.

use Doctrine\ORM\Mapping as ORM;
use Ecommit\DoctrineEntitiesGeneratorBundle\Entity\EntityInitializerInterface;

#[ORM\Entity]
#[ORM\Table(name: 'category')]
class Category implements EntityInitializerInterface
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer', name: 'category_id')]
    protected $categoryId;

    #[ORM\OneToMany(targetEntity: 'Ecommit\DoctrineEntitiesGeneratorBundle\Tests\App\Entity\Book', mappedBy: 'category')]
    protected $books;

    #[ORM\Column(type: 'datetime')]
    protected $createdAt;

    public function initializeEntity(): void
    {
        $this->createdAt = new \DateTime('now');
    }

    //...
}

The initializeEntity method will be automatically called in the constructor generated in this way.

An EntityInitializerInterfaceNotUsedException exception is thrown

An Ecommit\DoctrineEntitiesGeneratorBundle\Exception\EntityInitializerInterfaceNotUsedException exception is thrown if you define manually a constructor in your entity when a TOMANY association is used.

See the previous question.

A TagNotFoundException exception is thrown

The start and/or end tag was not found in your entity.

How can I ignore the generation of getters-setters methods for an entity ?

Not all entities are processed (see the "Usage" section to find out which classes can be generated).

You can ignore the generation of getters-setters methods for an entity by using the Ecommit\DoctrineEntitiesGeneratorBundle\Attribute\IgnoreGenerateEntity attribute :

use Doctrine\ORM\Mapping as ORM;
use Ecommit\DoctrineEntitiesGeneratorBundle\Attribute\IgnoreGenerateEntity;

#[ORM\Entity]
#[ORM\Table(name: 'category')]
#[IgnoreGenerateEntity]
class Category
{
    #[ORM\Id]
    #[ORM\Column(type: 'integer', name: 'category_id')]
    protected $categoryId;
    //...
}

How can I ignore the generation of getters-setters methods for a property ?

Not all properties are processed (see the "Usage" section to find out which properties can be generated).

Why was no method generated ?

See the last two questions.

Limitations

The bundle only works under the following conditions :

  • The Doctrine attributes are used (Doctrine annotations are not compatible).
  • Only one entity (PHP class) per PHP file
  • Inside each entity (PHP class) :
    • Only one property per line
    • Only one method per line (but a method can be defined through over lines)
  • EOL (End Of Line) = LF

License

This bundle is available under the MIT license. See the complete license in the LICENSE file.

doctrine-entities-generator-bundle's People

Contributors

hlecorche avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar

Forkers

hlecorche

doctrine-entities-generator-bundle's Issues

Wrong typehint for DateTime

Given the following property

    #[ORM\Column(type: 'datetimetz_immutable', nullable: false)]
    protected ?DateTimeInterface $date;

generated output will be:

    public function setDate(?\DateTimeImmutable $date): self
    {
        $this->date = $date;

        return $this;
    }

    public function getDate(): ?\DateTimeImmutable
    {
        return $this->date;
    }

(note that typehint is \DateTimeImmutable, not \DateTimeInterface)

While this is technically correct from Doctrine's point of view, it will be better to prefer interface as typehint, especially when it is explicitly used in property's type.

readonly properties should not have setters

It is possible that entity can have readonly properties. Example cases:

  • entity data comes from materialized view
  • field value comes from generated column
  • field value set elsewhere outside entity, e.g. with custom UPDATE queries, or from other app sharing this db
  • property is set in constructor for a new entity and persisted forever in that state

A readonly access modifier becomes useful here to enforce that no modifications are allowed. But with it, generated setter methods are invalid.

Generator should omit setter methods for fields, embeddeds and to-one associations, if a property is readonly.

Support Embeddables

#[ORM\Embedded]
protected MyEmbed $obj;

Results in:

In EntityGenerator.php line 114:
Warning: Undefined array key "obj"

It seems that embeddables are not supported currently, but neither are they skipped, and it fails here:

if ($metadata->hasField($property)) {
$this->addField($request, $metadata->fieldMappings[$property]);
} elseif ($metadata->hasAssociation($property)) {

because hasField is:
return isset($this->fieldMappings[$fieldName]) || isset($this->embeddedClasses[$fieldName])

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.