MicWit MicWit - 1 month ago 11
PHP Question

Extending my own controller in Symfony

I am creating a webapp that has some common functions. So I figured the easiest way to do this would be to make a base controller and just extend that. So in the base controller I have (similar to):

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class BaseController extends Controller
{
protected function dosomething($data)
{
return $data;
}
}


And then in the default controller:

namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class DefaultController extends BaseController
{
/**
* @Route("/", name="homepage")
*/
public function indexAction()
{
$data = "OK";
$thedata = $this->dosomething($data);
}
}


And then for the Admin Controller:
namespace AppBundle\Controller;

use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class AdminController extends BaseController
{
/**
* @Route("/", name="homepage")
*/
public function indexAction()
{
$data = "OK";
$thedata = $this->dosomething($data);
}
}


However, I am getting errors like "Compile Error: Access level to AppBundle\Controller\AdminController::dosomething() must be protected (as in class AppBundle\Controller\BaseController) or weaker", not just when I load the admin controller function, but default as well. When I stop the admin controller extending base controller, this error goes (seems to work on default but not admin).

I'm guessing somewhere I have to let Symfony know that the admin controller is safe or something?

Answer

It has nothing to do with Symfony, it's PHP.

Obviously, you're trying to redefine dosomething method in your Admin Controller, and trying to make this method private.

It's not allowed. It may be either protected or public.

It's principle of OOP. Because if you would have a class SubAdminController, then instance of it would be also instance of both AdminController and BaseController. And PHP must definitely know if the method dosomething from parent class is accessible from SubAdminController.

Comments