Why my Zend-HAL implementation is not working with protected values

57 Views Asked by At

I am new in Zend framework, and trying to use HAL for API response generation. In the following is a simpler situation of my issues.

The class:

class Version
{
    protected $data;

    public function __construct($ar){
        $data = $ar;
    }

    public function getArrayCopy(){
        return $data;
    }
}
$obj = new version(['major'=>1,'minor'=>2,'fix'=>3]);

When I test with hydrator, it works well as per the following:

use Zend\Hydrator\ArraySerializableHydrator;

$hydrator           = new ArraySerializableHydrator();
$data =  $hydrator->extract($obj);

print_r($data); // outputs ['major'=>1,'minor'=>2,'fix'=>3]

My HAL configuration is following:

MetadataMap::class => [
    [
        '__class__' => RouteBasedResourceMetadata::class,
        'resource_class' => Version::class,
        'route' => 'version',
        'extractor' => ArraySerializableHydrator::class,
    ],
]

I use the following line in my Zend expressive (version 3) request handler

$resource = $this->resourceGenerator->fromObject($obj, $request);
$res = $this->responseFactory->createResponse($request, $resource);

The link is generated correctly, but the meta data (version info) is coming as empty. Any help will be much appreciated.

N.B.: My real code is complex, here I tried to generate a simpler version of the issue.

1

There are 1 best solutions below

0
On

I think that when generating response the hydrate method is called. So your test does not seem to test what you meant to test.

When hydrating the hydrator works with ReflectionClass. So you need to add the indexes from $data as properties in the Version class.

e.g.

class Version
{
    protected $major;
    protected $minor;
    protected $fix;

    public function __construct($data){
        foreach($data as $key => $value) {
           $this->{$key} = $value;
        }
    }

    public function getArrayCopy(){
        return [
        'major' => $this->major,
        'minor' => $this->minor,
        'fix' => $this->fix
         ];
    }
}
$obj = new version(['major'=>1,'minor'=>2,'fix'=>3]);