对多个视图使用相同的控制器代码



我使用的是symfony 5.4,我有一个控制器可以管理多个路由并返回一个视图。

现在我想创建另一个控制器,它在所有页面中都有完全相同的逻辑,但返回另一个视图。以下是我实际拥有的一个例子:


class KioskController extends AbstractController
{
public function manualRegistration(
ManagerRegistry $doctrine,
Request $request, 
Session $session,
LoggerInterface $logger,
MyWebservice      $myWebservice,
AppointmentService $appointmentService)
{

/*
*  page logic i want to re-use in another in another controller
*/
return $this->render('path/to/view.html.twig', ['form' => $form->createView(),'myVar'=>$var1, 'myArray'=>$arr]);
}
// other routes 
}

我最初的想法是创建一个抽象类,它将扩展AbstractController,并返回一个数组,其中包含将在视图中使用的所有元素(表单和其他变量/数组(,如下所示:


abstract class AbstractKioskManager extends AbstractController
{
protected function manageManualRegistration(
ManagerRegistry $doctrine,
Request $request, 
Session $session,
LoggerInterface $logger,
MyWebservice      $myWebservice,
AppointmentService $appointmentService)
{

/*
*  page logic i want to re-use in another in another controller
*/
return  ['form' => $form->createView(),'myVar'=>$var1, 'myArray'=>$arr])
}
}

然后将这个抽象控制器用于显示不同视图的2个或多个控制器:

class KioskController1 extends AbstractKioskManager
{
public function manualRegistration(
ManagerRegistry $doctrine,
Request $request, 
Session $session,
LoggerInterface $logger,
MyWebservice      $myWebservice,
AppointmentService $appointmentService)
{

$viewParams = $this->manageManualRegistration($doctrine,$request,$session,$logger,$myWebservice,$appointmentService);
return $this->render('path/to/view1.html.twig',$viewParams);
}
// other routes
}

class KioskController2 extends AbstractKioskManager
{
public function manualRegistration(
ManagerRegistry $doctrine,
Request $request, 
Session $session,
LoggerInterface $logger,
MyWebservice      $myWebservice,
AppointmentService $appointmentService)
{

$viewParams = $this->manageManualRegistration($doctrine,$request,$session,$logger,$myWebservice,$appointmentService);
return $this->render('path/to/view2.html.twig',$viewParams);
}
// other routes
}

有更干净的方法吗?

有更干净的方法吗?

是。使用服务

然后你只需要注入它,就可以在你想要的所有控制器中重复使用你的逻辑,比如:

public function myFunction(Myservice $myService): Response
{
$myService->doSomething();
return $this->render('path/to/view1.html.twig');
}

最新更新