How to install the gedmo-extensions in Doctrine2? - php

i'm trying to install the "gedmo" behaviourial extensions (version 2.1.0-DEV) in Doctrine2 (version 2.1.3).
Without the extensions everything works fine. However, when I add the annotationdriver to read the #gedmo-annotations errors such as "Uncaught exception 'Doctrine\ORM\Mapping\MappingException' with message 'Class User2 is not a valid entity or mapped super class" are thrown.
This is de User2-entity:
<?php
use \Doctrine\ORM\Mapping as ORM;
/** #ORM\Entity */
class User2 {
/**
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue
*/
private $id;
/** #ORM\Column(length=255) */
private $username;
}
Because these errors occur even in the Entities where #gemdo is not used i suspect it has something to do with the way the annotationdrivers are configured. In my bootstrap-file the annotation driver is added (i'm only going to use the tree-extension):
$reader = new \Doctrine\Common\Annotations\AnnotationReader();
$annotationDriver = new \Doctrine\ORM\Mapping\Driver\AnnotationDriver($reader);
$chain = new \Doctrine\ORM\Mapping\Driver\DriverChain;
$chain->addDriver($annotationDriver, 'Gedmo\Tree\Entity');
$config->setMetadataDriverImpl($chain);
A few questions:
Should I add a driver for the ORM-annotation?
Is there something wrong with the User2-class?
How can I get a more specific user-error enabling me to find the exact cause of the problem?
In short: how can I make the #orm and #gedmo annotations work?

there was recently an example added in order to show how to configure bare entity manager with extensions whithout any framework used.
You can follow the readme at the bottom on how to setup it initially

Related

Symfony 4 Custom annotation problem #ORM\Entity does not exist

as part of the development of my CMS that I publish in a while .. I am facing a problem.
error :
[Semantical Error] The annotation "#Doctrine\ORM\Mapping\Entity" in class ScyLabs\GiftCodeBundle\Entity\GiftCode does not exist, or could not be auto-loaded.
I explain to you ,
Basically, in the project, everything is Overridable, it is already the case, with configurations in the file services.yaml.
For obvious reasons of simplicity, and an immediate need, to allow me to create a second bundle inheriting from it. I told myself that doing my "Override" or saying to the project: "Hello here I am, I am a class uses me" is very convenient with annotations (and much clearer).
So, I create a custom annotation (So far so good ..) That you find here ..
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 04/11/2019
* Time: 14:25
*/
namespace ScyLabs\NeptuneBundle\Annotation\ScyLabsNeptune;
/**
* #Annotation
* #Target({"CLASS"})
* #Attributes({
* #Attribute("key",type="string"),
* #Attribute("classNameSpace",type="string"),
* })
*/
class Override
{
/**
* #var string
*/
public $key;
/**
* #var string
*/
public $classNameSpace;
public function __construct(array $opts) {
$this->key = $opts['value'];
$this->classNameSpace = $opts['class'];
}
}
Well, my annotation was in place, I will now put it in an entity, .. As here
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 05/11/2019
* Time: 10:20
*/
namespace ScyLabs\GiftCodeBundle\Entity;
use ScyLabs\NeptuneBundle\Annotation\ScyLabsNeptune;
use Doctrine\ORM\Mapping as ORM;
/**
* #ScyLabsNeptune\Override("gift",class="ScyLabs\GiftCodeBundle\Entity\GiftCode")
* #ORM\Entity()
*/
class GiftCode
{
}
Why do that ? And in fact, everything is automated in the neptune, except special case, it will automatically generate all the URLs necessary for the proper functioning of an entity (ADD / EDIT / DELETE / LIST) ... And for this, it must indicate to the project that the entity exists, and that it must be part of this system.
So, until now I use a very complete configuration in services.yaml, in which I fill a table keys => value, corresponding to "key" => "Namespace"
In my case: "gift" => "ScyLabs \ GiftCodeBundle \ Entity \ GiftCode"
In short, suddenly, for override, I do a treatment in a compilation step
<?php
/**
* Created by PhpStorm.
* User: alex
* Date: 01/08/2018
* Time: 09:46
*/
namespace ScyLabs\NeptuneBundle;
class ScyLabsNeptuneBundle extends Bundle
{
public function getContainerExtension()
{
// Compilation de l'extension
return new ScyLabsNeptuneExtension();
}
}
And in this extension, I have this piece of code that makes everything
$bundles = require $projectDir.'/config/bundles.php';
foreach ($bundles as $bundle => $env){
if($bundle === ScyLabsNeptuneBundle::class)
continue;
if(method_exists(new $bundle,'getParent') && (new $bundle)->getParent() === ScyLabsNeptuneBundle::class){
$reader = new AnnotationReader();
$reflClass = new \ReflectionClass(GiftCode::class);
$classAnotations = $reader->getClassAnnotation($reflClass,"Override");
foreach ($classAnotations as $classAnotation){
if($classAnotation instanceof Override && class_exists($classAnotation->classNameSpace)){
$config['override'][$classAnotation->key] = $classAnotation->classNameSpace; }
}
}
}
From what I suspect after a lot of research, at the compilation stage of my extension, #ORM \ Entity, and or / / Autowire, it seems not compiled yet.
The problem is that suddenly, when I get my personal annotation (Override), I can not recover #ORM \ Entity, and I can not necessarily remove it because it would not work anymore as an entity.
Why do that here? Because behind I have another step of comoilation (A CompilationPass)
$container->addCompilerPass(new ResolveDoctrineTargetEntitiesPass(),PassConfig::TYPE_BEFORE_OPTIMIZATION,1000);
Who, redefined the Entities that doctrine will call in relation to the painting that I send to him (you know, the one I defined just before).
With this I give the possibility of override entities with an identical name.
What to do ?? .. I confess that I can not do more ...
Thanks in advance friends;)
By default, the annotation reader does not use the same autoloader as classes.
You need to tell him how to load the annotation class like that :
AnnotationRegistry::registerUniqueLoader('class_exists');
For more explanation, you can look at the doc https://www.doctrine-project.org/projects/doctrine-annotations/en/1.6/annotations.html#registering-annotations
thanks for you response.
But it don't work and this fonction is deprecated and removed to Annotations 2.0.
BUT , when i try i found a resolution.
When i follow your link and try the code in the page , i try this function
AnnotationRegistry#registerFile($file)
For get #ORM\Entity file path , i use
new \ReflectionClass(ORM\Entity::class);
And , this work.
I deleted AnnotationRegistry#registerFile($file) function , and this work.
Thanks you for help ;)
You'r the best

Symfony Cache problems

I am working with Symfony and Doctrine (I am not expert) I was creating a code to work with my Mysql database
/**
* TcCourse
*
* #ORM\Table(name="tc_course")
* #ORM\Entity
*/
class TcCourse
{
/**
* #var integer
*
* #ORM\Column( type="integer", nullable=false)
* #ORM\Id
* #ORM\GeneratedValue(strategy="IDENTITY")
*/
private $id;
However when I tried to run the source code using a Controller I was obtaining :
Property AppBundle\Entity\TcCourse::$userid does not exist
$userid was my previous property insted of $id
I stop the server and start the server n-times because I was pretty sure that the code was ok
php app/console server:start
php app/console server:stop
always I got the same error
I find a solution using this (Because the code was ok)
php bin/console cache:clear
What are your recomendations about server cache in order to avoid this kind of problem?

Yet another Unknown Entity namespace alias error (Symfony2, manually created entity)

I am having a [Doctrine\ORM\ORMException] Unknown Entity namespace alias 'src\AppBundle\Entity'
error message.
A quick search led me to three related SO questions :
here about
a problem in a user-created bundle, which I'm not using here.
here where
the error message is obtained by PHP code rather using doctrine in the command line as I'm currently doing, and
there where the answer suggests doing sudo php app/console cache:clear --env=dev ; I did that followed by sudo chmod a+w app/cache/dev/annotations, but the problem stayed the same.
Here is what I did :
1) Successfully create my database with php app/console doctrine:database:create
2) Create manually a Product Entity in app/Entity/Product.php with the following content (the code below is
copy-pasted from the Symfony Book) :
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="product")
*/
class Product
{
/**
* #ORM\Column(type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="string", length=100)
*/
protected $name;
/**
* #ORM\Column(type="decimal", scale=2)
*/
protected $price;
/**
* #ORM\Column(type="text")
*/
protected $description;
}
3) Type php app/console doctrine:generate:entities src/AppBundle/Entity:Product - which produced the "unknown entity namespace" error message.
Any help appreciated.
There are two syntaxes that are/will be used throughout your Symfony2 app.
\My\Company\Namespace\Entity\Product
MyCompanyNamespace:Product
I believe that putting a src anywhere in your code/config would be in violation with PSR-0. Symfony2 does a very good job of seeing everything thought a bundle. That is why you have to have at least one in your app - everything it a bundle

Symfony Annotations are not parsed

I have installed the FOSUserBundle and installed it as per its detailed installation guide (https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Resources/doc/index.md).
When i run php console doctrine:schema:update --force for the first time, it populates the users table with all of the default fields that the FOSUserBundle has defined.
Unfortunately it appears to be completely missing the fields which i have added to my user entity and i am wondering if its utilising the configuration file which is specified in the installation guide instead of using the annotations which are in the entity.
It also appears to be ignoring the other entities within the same Bundle.
namespace Acme\UserBundle\Entity;
use FOS\UserBundle\Entity\User as BaseUser;
use Doctrine\ORM\Mapping as ORM;
/**
* #ORM\Entity
* #ORM\Table(name="users")
*/
class User extends BaseUser {
/**
* #ORM\Id
* #ORM\Column(type="integer")
* #ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* #ORM\Column(type="integer")
* #ORM\ManyToOne(targetEntity="Bureau", mappedBy="id")
*/
protected $bureau;
public function __construct() {
parent::__construct();
}
}
This is my user entity, of which bureau is being completely ignored regardless if it has a relationship or not.
Edit
As per requested, please find below the orm config file. It's the default file as per the configuration.
I have suspected this to be the problem, but i wasnt sure if annotations and the config file could work together.
Acme\UserBundle\Entity\User:
type: entity
table: users
id:
id:
type: integer
generator:
strategy: AUTO
Edit 2
I have found that if i remove the orm configuration file that it all magically works again!!
So i would adjust my question for clarity.
Updated question
If an orm configuration file exists, are annotations ignored?
When you generate entities with the console, you are asked on the format, which is:
xml
yaml
annotations
Regardless of what you choose, there are no signifiers telling Doctrine which to use besides the fact one exists. In order, YAML takes priority over annotations, and so it should.

Symfony2: Duplicate definition of column 'id' on entity in a field or discriminator column mapping

I'm having trouble using entity inheritance in Symfony2. Here are my two classes:
use Doctrine\ORM\Mapping as ORM;
/**
* #Orm\MappedSuperclass
*/
class Object
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
}
/**
* #Orm\MappedSuperclass
*/
class Book extends Object
{
}
When I run php app/console doctrine:schema:create I get the following error:
[Doctrine\ORM\Mapping\MappingException]
Duplicate definition of column 'id' on entity 'Name\SiteBundle\Entity\Book' in a field or discriminator column mapping.
What may be causing this?
Thanks :)
Update:
You are right I missed this. Now I'm using single table inheritance with both classes being entities:
/**
* #Entity
* #InheritanceType("SINGLE_TABLE")
* #DiscriminatorColumn(name="discr", type="string")
* #DiscriminatorMap({"object" = "Object", "book" = "Book"})
*/
But I still get the same error message.
Actually I found yml files in Resources/config/doctrine/, which were defining my entities, instead of just using annotations.
I removed these files and it's working now.
Thanks for your help !
I had same issue even after adding definitions to yml file. I was trying to add weight & max weight to a class and was getting:
Duplicate definition of column 'weight_value' on entity 'Model\ClientSuppliedProduct' in a field or discriminator column mapping.
Then I realized it requires columnPrefix to be different for similar types of fields and adding following in yml solved it for me:
`maxWeight:`
`class: Model\Weight`
`columnPrefix: max_weight_`
I had the same problem and error message but for me it was the other way around as #user2090861 said.
I had to remove the (unused)
use Doctrine\ORM\Mapping as ORM;
from my entity files, cause my real mapping comes from the orm.xml files.
I hope I can help with my answer many other people, cause this exception drove me crazy the last two days!
I ran into this in a different context - in my case, I had set up an entity for single-table inheritence using #ORM\DiscriminatorColumn, but had included the column in my class definition as well:
/**
* #ORM\Entity(repositoryClass="App\Repository\DirectoryObjectRepository")
* #ORM\InheritanceType("SINGLE_TABLE")
* #ORM\DiscriminatorColumn(name="kind", type="string")
*/
class DirectoryObject {
// ...
/**
* #ORM\Column(type="string", length=255)
*/
private $kind;
}
Removing the #ORM\Column definition of kind fixed this issue, as Doctrine defines it for me.
Sometimes it's impossible to remove extra config files, because theay are located in third party bundle and auto_mapping is enabled.
In this case you should disable undesirable mappings in app/config.yml
doctrine:
orm:
entity_managers:
default:
mappings:
SonataMediaBundle: { mapping: false }
Any entity must contain at least one field.
You must add at least one field in Book Entity
Example
/**
* #Orm\MappedSuperclass
*/
class Book extends Object
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
}
I had the same error message but I had made a different mistake:
Class B had an ID and extended Class A which also had an ID (protected, not private). So I had to remove the ID from Class B.

Categories