我已经搜索过了,但我找不到任何类似的问题,或者我可能措辞错误。我想要实现的是访问Bundle中所有控制器中的对象。例如:
<?php
namespace ExampleCoreBundleController;
use SymfonyBundleFrameworkBundleControllerController;
class FolderController extends Controller
{
function indexAction()
{
$title = $this->folder->getTitle();
$description = $this->folder->getDescription();
}
}
通常在Symfony之外,我会用BaseController扩展控制器来扩展控制器类,并在construct方法中设置它,但我知道Symfony不使用construct方法,所以我有点卡住了,不知道该去哪里。
我通常会这样做:
class BaseController extends Controller
{
function __construct()
{
parent::__construct();
//load up the folder from my model with an ID
$this->folder = $folder;
}
}
然后我会从FolderController扩展BaseController并从那里去,但我已经尝试了Symfony,它不起作用。我已经调查了服务,但不认为这是我需要做这个工作。如果需要更多的细节,请告诉我,谢谢。
如果我对你的问题理解正确的话,服务确实是你想要的。
首先,在services.yml
中定义一个服务:
services:
vendor.folder_manager:
class: VendorFolderBundleEntityManagerFolderManager
arguments:
em: "@doctrine.orm.entity_manager"
class: VendorFolderBundleEntityFolder
创建FolderManager
类:
<?php
namespace VendorFolderBundleEntityManager;
use DoctrineORMEntityManager;
use DoctrineORMEntityRepository;
class FolderManager
{
protected $em;
protected $repo;
protected $class;
public function __construct(EntityManager $em, $class) {
$this->em = $em;
$this->class = $class;
$this->repo = $em->getRepository($class);
}
public function findById($id) {
return $this->repo->findById($id);
}
public function getRepository() {
return $this->repo;
}
}
最后,在控制器中:
$this->container->get('vendor.folder_manager')->findById($folderId);
或:
$this->container->get('vendor.folder_manager')->getRepository()->findById($folderId);
Symfony2将自动注入实体管理器类到管理器,所以所有你必须在控制器中提供的是文件夹的id。
编辑:为了使其更美观,您还可以在控制器中创建一个快捷函数:
protected function getFolderManager()
{
return $this->container->get('vendor.folder_manager');
}
那么你可以这样做:
$this->getFolderManager()->findById($folderId);