How to create an instance array in PHP Attributes

Viewed 61

With Doctrine annotations it is possible to build the following mapping:

/** 
 * @ORM\Table(indexes={
 *     @ORM\Index(name="first_index", columns={"username","password","email"}),
 *     @ORM\Index(name="second_index", columns={"email"}),
 *     @ORM\Index(name="third_index", columns={"email", "username","language"})
 * })
 */
class SomeClass
{

When refactoring this to PHP attributes I'm trying

#[ORM\Table(
    indexes: [
        ['name' => 'first_index', 'columns' => ['username', 'password', 'email']],
        ['name' => 'second_index', 'columns' => ['email']],
        ['name' => 'third_index', 'columns' => ['email', 'username','language']]
    ]
)]
class SomeClass
{

but then my IDE complains this is a string[], not the expected ORM\Index[] it needs.

(And also, Doctrine throws a MappingException with the message Class "SomeClass" is not a valid entity or mapped super class..)

So practically speaking my question is: How can I get an array of ORM\Index instances inside of an ORM\Table attribute?

Other options I've tried:

#[ORM\Table(
    indexes: [
        #[ORM\Index(name: 'first_index', columns: ['username', 'password', 'email'])],
    ]
)]
class SomeClass
{

but this breaks the attribute annotation. Unfortunately the very basic Doctrine attributes documentation does not demonstrate a relevant example.

1 Answers

#[Index] should be a separate statement instead of part of #[Table]:

#[ORM\Table]
#[ORM\Index(name: 'first_index', columns: ['username', 'password', 'email'])]
#[ORM\Index(name: 'second_index', columns: ['email'])]
#[ORM\Index(name: 'third_index', columns: ['email', 'username','language'])]
class SomeClass
{

See this part of the docs for an example.

Related