Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 Extending Controller getParameter()

I Want to extend Symfony2 Controller to my project that is using API but I am having error of a non object use getParameter() function look at my code:

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');

    }
}

And next Controller

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');
    }

}

And the end, I got this Fatal Error:

FatalErrorException: Error: Call to a member function getParameter() on a non-object in (..)

I try to use $this->setContainer() but it doesn't work. Do you have any idea how can I slove this problem?

like image 480
Purzynski Avatar asked Feb 25 '26 03:02

Purzynski


2 Answers

If your controller is not defined as service, The constructor execution of the controller is not persisted.

You have two options to solve your situation:

  1. Define the controller as a service and inject the parameters you need using dependency injection.
  2. Add an init method in the controller, or on a parent abstract controller, and call the init method, before the action you need to have these parameters available;
like image 195
shacharsol Avatar answered Feb 28 '26 05:02

shacharsol


You cant use container in Controller __construct at reason that when constructor called where is none container set yeat.

You can simply define some simple methods in controller like

class ApiController extends Controller
{
    protected function getApiHost()
    {
        return $this->container->getParameter('api_host');
    }
}
like image 26
Alexey B. Avatar answered Feb 28 '26 07:02

Alexey B.