containerAware and Controller in symfony2



FOSUserBundle配置文件控制器

 use SymfonyComponentDependencyInjectionContainerAware;
 class ProfileController extends ContainerAware

一些函数ok…但是当我尝试创建form

$form = $this->createForm

这个错误出现:调用未定义方法ProfileController::createForm()

但是当我把它改成这样:

use SymfonyBundleFrameworkBundleControllerController;
class ProfileController extends Controller

表单呈现…所以…我不知道我怎么能把这个控制器添加到我的类,不删除ContainerAware ?:/

//

我的解决方案?

我用

代替容器感知
use SymfonyComponentDependencyInjectionContainerAwareInterface;

然后

class ProfileController extends Controller implements ContainerAwareInterface

但我不知道,我不能看到不同,我现在是新手,所以…这是好的解决方案还是我会打碎东西?

回答你最初的问题,

替换:

$form = $this->createForm

:

$form = $this->container->get('form.factory')->create($type, $data, $options);

createForm方法只是在SymfonyBundleFrameworkBundleControllerController中定义的一个方便方法。由于各种原因,第三方库倾向于不扩展Controller类。因此,createForm不可用。

真正的问题是:为什么要扩展Profile控制器?在大多数情况下,这是不必要的。最好通过监听事件来进行定制。当然,这假定您使用的是FOSUserBundle的开发版本。

Controller is already ContainerAware - from Controller declaration:

class Controller extends ContainerAware

看看这个博客Symfony2:远离基础控制器作者:Richard Miller

最新更新