我想知道在哪里存储一些与表单相关的自定义代码。我正在编写 Symfony 应用程序,用户可以在其中添加自己的类别(当然使用表单)。当用户添加他的类别时,控制器内的表单代码检查此表单是否已提交且有效。如果是,则将用户的类别和基于类别名称创建的 URI添加到数据库中。现在,整个代码和逻辑都存储在addCategory ()操作中的CategoryController中。就像下面这样:
public function addCategory(Request $request): Response
{
// create the whole form inside CategoryType class
$form = $this->createForm(CategoryType::class);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$categories = $form->getData();
$categories->setName(preg_replace(
'#\s+#', ' ', $categories->getName()));
$categories->setCategoryUri(strtolower(str_replace(
' ', '-', $categories->getName())));
$this->getDoctrine()->getRepository(Categories::class)
->addOneCategory($categories);
return $this->redirectToRoute('flashcard_index');
}
return $this->render('category/add_category.html.twig', [
'form' => $form->createView(),
'slug' => 'Add category'
]);
}
正如您在 if 语句中看到的那样,我正在编写代码。首先,将用户数据保存到$categories
变量中,接下来我使用删除多个空格preg_replace()
(如果用户在表单字段中输入多个空格),最后我使用strtolower()
和str_replace()
函数创建基于类别名称的 URI。
问题是我不知道将上述逻辑存储在控制器操作中是否是一种好习惯,如果不是,那么在哪里存储此逻辑?你能回答我这个问题吗?预先感谢您的所有答案!