我正在开始一个新的捆绑包。它的目标是显示一些统计数据数组和图表。问题是我不知道在哪里将原始数据转换为视图数组和图表中的可用数据。我阅读了很多关于保持控制器尽可能薄的文章。据我所知,存储库旨在提取数据,而不是转换它们。
根据 Symfony2 的最佳实践,我应该在哪里转换我的原始数据?
只需创建您自己的自定义服务,该服务使用一些存储库来提取数据并将其转换为可用的形式。
样本:
// repository
interface MyRepository {
public function findBySomething($something);
}
class MyRepositoryImpl extends EntityRepository implements MyRepository {
public function findBySomething($something) {
return $this->createQueryBuilder('a')
->where('a.sth = :sth')
->setParameter('std', $something)
->getQuery()
->getResult();
}
}
// service
interface MyService {
public function fetchSomeData();
}
class MyServiceImpl implements MyService {
/** @var MyRespostiory */
private $repo;
public function __construct(MyRepository $repo) {
$this->repo = $repo;
}
public function fetchSomeData() {
$rawData = $this->repo->findBySomething(123);
$data = [];
// do sth
return $data;
}
}
// final usage, eg. within a constructor
class MyConstructor extends Controller {
/** @var MyService */
private $myService;
public function __construct(MyService $myService) {
$this->myService = $myService;
}
public function someAction() {
// you could also get access to the service using $this->get('...')
$data = $this->myService->fetchSomeData();
return $this->render('SomeTemplate', [
'data' => $data
]);
}
}
// service declaration
<service id="myService" class="MyServiceImpl">
<argument type="service" id="doctrine.repository.my_repository" />
</service>
这取决于您的应用程序,但根据您描述的内容,您需要定义 aService
并在那里编写所有逻辑,以便您的控制器看起来像这样
$customService = $this->get('my_custom_service');
$data = $customService->loadMyData();
阅读更多关于 Symfony 服务的信息:http: //symfony.com/doc/current/book/service_container.html