Symdony5.3 - 由于服务调用回购查询,如何将参数从控制器传递到服务?
Symdony5.3 - How to pass parameters from a Controller to a Service because the service calls a repo query?
我正在开发一个项目,其中 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 参数或查询参数来自定义您的控制器。
例如,您可以像这样使用 URL:/update_data/1?date=2021-06-13
那么您的代码将使用 Symfony route parameters and parameter 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.
}
我正在开发一个项目,其中 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 参数或查询参数来自定义您的控制器。
例如,您可以像这样使用 URL:/update_data/1?date=2021-06-13
那么您的代码将使用 Symfony route parameters and parameter 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.
}