Symdony5.3 - 由于服务调用 repo 查询,如何将参数从控制器传递给服务?

问题描述

我正在开发一个项目,Symfony 作为 API 后端(使用 ApiPlatform),Angular 作为前端,领导决定我们将使用服务并在其中创建一个名为 updateData() 的函数

在我的服务中:

public function updateData(array $dates,Hotel $hotel): ?array
    {
            $bookings= $this->em->getRepository(Booking::class)->findAllByIdAndDate($id,$date);
    
            foreach ($bookings as $booking) {
                ...
             }
        ...
    }

在我的控制器中:

/**
 * @Route("/update_data",name="update_data")
 */
public function index(UpdateData $updateData)
{
    $this->em = $this->getDoctrine()
    ->getManager()
    ->getRepository(Hotel::class);

    $date = new \DateTime('2021-06-13');
    $id = 1;
    $hotel = $this->em->find($id);

    $message =  $updateData->updateData([$date],$hotel);

}

我的问题是如何在这里接收数据并将参数从这个控制器传递给服务? 谢谢

解决方法

为了更新特定酒店的数据,您可以使用 url 参数或查询参数来自定义您的控制器。

例如,您可以使用如下网址:/update_data/1?date=2021-06-13

那么您的代码将使用 Symfony route parametersparameter conversion

这里有一个简单的例子,说明这会是什么样子。

/**
 * @Route("/update_data/{id<\d+>}",name="update_data")
 */
public function update_data(Hotel $hotel,Request $request): Response
{
    // the $hotel variable is autoconverted using parameter conversion
    $date = new \DateTime($request->query->get('date'));
    
    $message =  $updateData->updateData([$date],$hotel);

    // rest of your code.
}