AppBundle\Utils 中的 symfony 3.4 业务逻辑



我是symfony的新手,我正在阅读这里的最佳实践指南 https://symfony.com/doc/3.4/best_practices/business-logic.html

我有一个名为类别的控制器,我有此操作方法来列出类别。

public function listCategory(Request $request, CategoryLogic $categoryLogic)
{
$categories = $categoryLogic->getAllCategory($this->getDoctrine());
return $this->render('listCategory.html.twig', ['categories' => $categories]);
}

如您所见,我所有的控制器业务逻辑都转到 -> AppBundle\Utils\CategoryLogic

我有这个方法来处理逻辑并返回类别

use AppBundleEntityCategory; 
/**
* @param Registry $doctrine
* @return array
*/
public function getAllCategory(Registry $doctrine)
{
$repositoryCategory = $doctrine->getRepository(Category::class);
$category = $repositoryCategory->findAll();
return $category;
}

目的是保持控制器清洁。 这是最好的方法吗?我对将逻辑类命名为CategoryLogic有点担心 相反,我想将其命名为类别,但随后我遇到了另一个问题,因为我已经在 CategoryLogic 类中导入了use AppBundleEntityCategory,因此不能有两个类别类

对于您的特定示例,当您可以在控制器中注入存储库时,使用 Util 类是没有用的。

public function listCategory(Request $request, CategoryRepository $categoryRepository)
{
$categories = $categoryRepository->findAll();
return $this->render('listCategory.html.twig', ['categories' => $categories]);
}

从symfony 3.3开始,它具有依赖注入,这意味着您可以将服务注入其他服务。如果你想用一些服务(例如Utils(来处理它,你可以这样做。

//CategoryController.php
public function listCategory(Request $request, CategoryService $categoryService)
{
$categories = $categoryService->getAllCategories();
return $this->render('listCategory.html.twig', ['categories' => $categories]);
}
//CategoryService.php
namespace AppService;
use AppRepositoryCategoryRepository ;
class CategoryService 
{
private $categoryRepository;
// We need to inject these variables for later use.
public function __construct(CategoryRepository $categoryRepository)
{
$this->categoryRepository = $categoryRepository;
}
public function getAllCategories()
{
$categories = $this->categoryRepository->findAll();
return $categories;
}
}

始终使用单数和复数名称来排除混淆,例如$category将具有类别对象,$categories将是类别对象的数组或至少是类别对象的可迭代(集合(对象。当您稍后尝试调试代码并帮助其他人更好地理解您的代码时,这将使您的生活变得轻松。

附录:

https://symfony.com/doc/current/doctrine.html#querying-for-objects-the-repository https://symfony.com/doc/current/service_container/3.3-di-changes.html https://symfony.com/doc/current/service_container/injection_types.html

最新更新