拉拉韦尔·丁戈/阿皮主义


Laravel Dingo/Api Doctrine

  • 我使用Laravel和Dingo/Api构建一个RESTful Api(https://github.com/dingo/api)
  • 我使用Doctrine2而不是Eloquent ORM(https://github.com/laravel-doctrine/orm)
  • 实体是从XML注释生成的

我很挣扎,因为Dingo似乎只改造Eloquent的收藏品和物品。我可以使用方法collection::make()来解决返回集合的问题。

但是怎么可能返回单个用户对象呢(请参见方法getUser())

<?php
namespace App'Http'Controllers;
use App'Entities'User;
use App'Transformer'UserTransformer;
use Dingo'Api'Http'Response;
use Dingo'Api'Routing'Helpers;
use Doctrine'ORM'EntityManagerInterface;
use App'Http'Requests;
use Illuminate'Routing'Controller;
use Illuminate'Support'Collection;
class UsersController extends Controller
{
    use Helpers;
    protected $em;
    /**
     * UsersController constructor.
     * @param $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }
    public function getUser($id)
    {
        $user = $this->em->getRepository(User::class)->findOneBy(array('id' => $id));
        return $user;
    }

    public function getUsers()
    {
        $user = $this->em->getRepository(User::class)->findAll();
        return $this->response->collection(Collection::make($user), new UserTransformer);
    }
}

幸运的是,我现在找到了一个有效的解决方案。我想分享这一点,并希望能够帮助其他人:

    return $this->response->item($user, new UserTransformer());