我正在使用Dingo API在Laravel 5.2中创建一个API,并让一个控制器返回数据
return $this->response->paginator($rows, new SymptomTransformer, ['user_id' => $user_id]);但是,我不知道如何在SymptomTransformer中检索user_id值!尝试了许多不同的方法,并尝试研究这个类,但我对Laravel和OOP都是新手,所以如果有人能给我指明正确的方向,我将不胜感激。
下面是我的transformer类。
class SymptomTransformer extends TransformerAbstract
{
public function transform(Symptom $row)
{
// need to get user_id here
return [
'id' => $row->id,
'name' => $row->name,
'next_type' => $next,
'allow' => $allow
];
}
}发布于 2017-01-12 00:07:15
您可以将额外的参数传递给transformer构造函数。
class SymptomTransformer extends TransformerAbstract
{
protected $extra;
public function __construct($extra) {
$this->extra = $exta;
}
public function transform(Symptom $row)
{
// need to get user_id here
dd($this->extra);
return [
'id' => $row->id,
'name' => $row->name,
'next_type' => $next,
'allow' => $allow
];
}
}然后像这样打电话
return $this->response->paginator($rows, new SymptomTransformer(['user_id' => $user_id]));发布于 2018-07-12 21:43:18
你可以通过setter设置额外的参数。
class SymptomTransformer extends TransformerAbstract
{
public function transform(Symptom $row)
{
// need to get user_id here
dd($this->test_param);
return [
'id' => $row->id,
'name' => $row->name,
'next_type' => $next,
'allow' => $allow
];
}
public function setTestParam($test_param)
{
$this->test_param = $test_param;
}
}然后:
$symptomTransformer = new SymptomTransformer;
$symptomTransformer->setTestParam('something');
return $this->response->paginator($rows, $symptomTransformer);发布于 2018-06-02 07:45:09
如果您正在使用依赖注入,那么您需要在之后传递params。
这是我的策略:
<?php
namespace App\Traits;
trait TransformerParams {
private $params;
public function addParam() {
$args = func_get_args();
if(is_array($args[0]))
{
$this->params = $args[0];
} else {
$this->params[$args[0]] = $args[1];
}
}
}然后在您的转换器中实现特征:
<?php
namespace App\Transformers;
use App\Traits\TransformerParams;
use App\User;
use League\Fractal\TransformerAbstract;
class UserTransformer extends TransformerAbstract
{
use TransformerParams;
public function transform(User $user)
{
return array_merge([
'id' => (int) $user->id,
'username' => $user->username,
'email' => $user->email,
'role' => $user->roles[0],
'image' => $user->image
], $this->params); // in real world, you'd not be using array_merge
}
}因此,在您的控制器中,只需执行以下操作:
public function index(Request $request, UserTransformer $transformer)
{
$transformer->addParam('has_extra_param', ':D');
// ... rest of the code
}基本上,这个特性是一个额外护理人员的包。
https://stackoverflow.com/questions/41595129
复制相似问题