Traits - property conflict with parent class

2020-03-10 01:56发布

问题:

I have this class Zgh\FEBundle\Entity\User which extends FOS\UserBundle\Model\User.

use FOS\UserBundle\Model\User as BaseUser;

class User extends BaseUser implements ParticipantInterface
{
    use BasicInfo;
    // ..
}

And BaseUser class:

abstract class User implements UserInterface, GroupableInterface
{
    protected $id;
    // ..
}

And BaseInfo trait:

trait BasicInfo
{
    /**
     * @ORM\Column(type="string", length=255)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     */
    protected $id;

    // ..
}

But when I run my code i get this error:

Strict standards: FOS\UserBundle\Model\User and Zgh\FEBundle\Model\Partial\BasicInfo define the same property ($id) in the composition of Zgh\FEBundle\Entity\User. This might be incompatible, consider using accessor methods in traits instead.

I'm using Symfony framework.

Is there anyway to resolve this conflict between the trait and the parent class object about this property ?

回答1:

No, it's not yet possible to rewrite a mapped property by using a Trait.

Also, a possible alternative is to use multiple abstract entity classes, and extend your child entities depending on your need.

i.e.

<?php

use FOS\UserBundle\Model\User as BaseUser;

abstract class AbstractStrategyNoneEntity extends BaseUser
{
    /**
     * @ORM\Column(type="string", length=255)
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="NONE")
     */
    protected $id;
}

abstract class AbstractStrategyAutoEntity extends BaseUser
{
    /**
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     *
     */
    protected $id;
}

And extend one of them in your child entities.

/**
* @ORM\Entity
*/
class Child extends AbstractStrategyNoneEntity 
{
    // Inherited mapping
}

Hopes this answers your question.