Symfony2 and MVC - Is extend controller a good pra

2019-07-20 20:34发布

问题:

I have a simple and perhaps stupid question.

Using Symfony2 PHP framework i often work extending controllers like below (of course it depends from the kind of work):

    class MainController extends Controller{
        private $locale = array();

        protected function Locale() {
        $em = $this->getDoctrine()
            ->getManager();

                $this->locale = $em->getRepository('CommonLanguageBundle:Language')
            ->findBy(
                array('code' => $this->getRequest()
                    ->getLocale()
                )
            );
//      \Doctrine\Common\Util\Debug::dump($this->locale);
        return $this->locale[0];
    }
     //..
    }
    class StoreController extends MainController{
     function a_method() {
       $data = $this->Locale()->getId();
       //...
      }
    }
    class DefaultController extends StoreController {
     $data = $this->Locale()->getId();
     //...
    }

Is this a good practice?

Surfing on the web i found many articles but it isn't still so clear for me.

In the end, if it worked fine in Symfony2, would it be good in general for MVC pattern?

回答1:

Symfony is not MVC framework. Symfony is Service-oriented architecture framework. Generally cascading extending controllers doesn't make a sens.

Rather you should create services and use it in whe you need it.

Moreover, good practice is define Controller as service.