nel*_*hin 7 php rest symfony api-platform.com
我想创建未映射的实体端点,例如/api/v1/me
返回User
有关当前经过身份验证的用户的信息(对象)并将其添加到我的文档中。在计划中,我还想添加端点,如/api/v1/account/recover
和/api/v1/account/verify-email
。
我有一个动作:
namespace AppBundle\Action\Me;
use AppBundle\Entity\User;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
class MeView
{
/**
* @var TokenStorageInterface
*/
private $tokenStorage;
public function __construct(TokenStorageInterface $tokenStorage)
{
$this->tokenStorage = $tokenStorage;
}
/**
* @Security("is_authenticated()")
*
* @Route(
* name="me_view",
* path="/me",
* methods={"GET"}
* )
*
* @return User
*/
public function __invoke()
{
return $this->tokenStorage->getToken()->getUser();
}
}
Run Code Online (Sandbox Code Playgroud)
但是当我尝试访问它时,它返回一个异常:
控制器必须返回一个响应(给出的对象(AppBundle\Entity\User))。(500内部服务器错误)
相同的动作,但映射到实体,效果很好:
namespace AppBundle\Action\City;
use AppBundle\Entity\City;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security;
use Symfony\Component\Routing\Annotation\Route;
class CityView
{
/**
* @Security("is_authenticated()")
*
* @Route(
* name="city_view",
* path="/cities/{id}",
* methods={"GET"},
* defaults={"_api_resource_class"=City::class, "_api_item_operation_name"="view"}
* )
*
* @param City $city
* @return City
*/
public function __invoke(City $city)
{
return $city;
}
}
Run Code Online (Sandbox Code Playgroud)
我应该怎么做才能使我的自定义操作起作用以及如何将其添加到自动生成的 Swagger 文档中?
小智 6
控制器:
class MyUserController extends Controller
{
public function fn_me()
{
return $this->getUser();
}
}
Run Code Online (Sandbox Code Playgroud)
实体:
* @ApiResource(
* collectionOperations={
* "get","post",
* "collName_api_me"={"route_name"="api_me"}
* }
* )
*/
class User implements UserInterface, \Serializable
Run Code Online (Sandbox Code Playgroud)
路线.yaml
api_me:
path: '/api/me'
methods: ['GET']
defaults:
_controller: '\App\Controller\MyUserController::fn_me'
_api_resource_class: 'App\Entity\User'
_api_collection_operation_name: 'collName_api_me'
Run Code Online (Sandbox Code Playgroud)