Symfony2扩展控制器getParameter()

普林斯基

我想将Symfony2 Controller扩展到使用API​​的项目,但是我遇到非对象错误,请使用getParameter()函数查看我的代码:

namespace Moda\CategoryBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class ApiController extends Controller
{
    /**
     * @var String 
     */
    protected $_host;

    /**
     * @var String
     */
    protected $_user;

    /**
     * @var String
     */
    protected $_password;

    public function __construct()
    {   
        $this->_host = $this->container->getParameter('api_host');
        $this->_user = $this->container->getParameter('api_user');
        $this->_password = $this->container->getParameter('api_password');

    }
}

还有下一个控制器

namespace Moda\CategoryBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template;

class CategoryController extends ApiController
{
    /**
     * @Route("/category", name="_category")
     * @Template()
     */
    public function indexAction()
    { 
        return array('name' => 'test');
    }

}

最后,我遇到了致命错误:

FatalErrorException:错误:在(..)中的非对象上调用成员函数getParameter()

我尝试使用$ this-> setContainer(),但是它不起作用。您知道我该如何解决这个问题?

shacharsol

如果您的控制器未定义为服务,则不会持久保留控制器的构造函数执行。

您有两种选择可以解决您的情况:

  1. 将控制器定义为服务,并使用依赖项注入来注入所需的参数。
  2. 在需要使这些参数可用之前,在控制器或父抽象控制器上添加init方法,并调用init方法。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章