Unable to determine entity identifier for object of type "Namespace\Class"; no fields matching "id"

933 Views Asked by At

I am trying to use ORM in my laminas api tools. Everything is working, however, looks like the api-tools-hal is not able to recognise the fields.

This is part of my module.config.php

'router' => [
    'routes' => [
        'customer.rest.customer' => [
            'type' => 'Segment',
            'options' => [
                'route' => '/customer[/:customer_id]',
                'defaults' => [
                    'controller' => 'Customer\\V1\\Rest\\Customer\\Controller',
                ],
            ],
        ],
],
'api-tools-hal' => [
    'metadata_map' => [
        \Customer\V1\Rest\Customer\CustomerEntity::class => [
            'entity_identifier_name' => 'id',
            'route_name' => 'customer.rest.customer',
            'route_identifier_name' => 'customer_id',
            'hydrator' => \Laminas\Hydrator\ObjectPropertyHydrator::class,
        ],
   ],
]

My Customer\V1\Rest\Customer\CustomerEntity::class

use Doctrine\ORM\Mapping as ORM;
/**
 * CustomerEntity
 * @ORM\Entity
 * @ORM\Table(uniqueConstraints={
 *   @ORM\UniqueConstraint(name="email", columns={"email"}),
 * })
 * @ORM\Entity(repositoryClass="Customer\V1\Rest\Customer\CustomerRepository")
 * @ORM\Table(name = "customers")
 */
class CustomerEntity
{
    /**
     * The unique auto incremented primary key.
     *
     * @var int|null
     *
     * @ORM\Id
     * @ORM\Column(type="integer")
     * @ORM\GeneratedValue(strategy="IDENTITY")
     */
    protected $id;

ORM cli command orm:schema-tool:create does works.

But upon going to domain.com/customer it throws this error:

Unable to determine entity identifier for object of type "Customer\V1\Rest\CustomerType\CustomerEntity"; no fields matching "id"

When I remove the ORM annotation in the entity then it works.

What do I need to do in this case?

2

There are 2 best solutions below

0
On BEST ANSWER

Ok, so I need to make my fields public.

protected $id; becomes public $id then it works.

This is just me being stupid. Learning is good.

4
On

Actually, no, that is not stupid ;). And please, don't make your id public since your have no reason to do it.

Another way to fix this is to create a couple of getter/setter. In this case, I would guess that a getter is enought. So simply make a public function getId(): ?int to fix the error, no need for a setter as you only need it to resolve the argument of a route.

public function getId(): ?int
{
    return $this->id;
}

Small tips: if you use PHPStorm, simply press Alt + Inser and then Getter to generate quickly this ;)