使用League / fractal,我试图将数据从数组转换为我的PHP对象...以下列方式
final class StatusDeserializer extends AbstractTransformer
{
public function transform(Status $status)
{
return new StatusObject(
$status['name'],
$status['message']
);
}
}
我的对象定义
final class StatusObject
{
private $name;
private $message;
public function __construct($name, $message)
{
$this->name = $name;
$this->message = $message;
}
}
在这里测试实施
$data = [ 'name' => 'foo', 'message' => 'bar' ]
$this->fractalManager->createData($data, new StatusDeserializer());
但是我得到了这个错误
Fatal error: Uncaught TypeError: Argument 1 passed to League\Fractal\Scope::filterFieldsets() must be of the type array, object given
我尝试将数组包装成Fractals集合,即
$data = new Collection([ 'name' => 'foo', 'message' => 'bar' ]);
现在它返回League\Fractal\Scope
的实例,而不是我的StatusObject实例
添加 - > toArray()让我回到第一个错误
$this->fractalManager->createData($data, new StatusDeserializer())->toArray();
答案 0 :(得分:1)
FractalManager
想要ResourceInterface
的实例作为第一个参数。所以你只想改变你的代码
$data = new Collection([ 'name' => 'foo', 'message' => 'bar' ]);
$this->fractalManager->createData($data, new StatusDeserializer());