curt
curt

Reputation: 4592

Loading a Parent Class in Symfony 2

I've set up a test parent class in my Symfony 2 controller as follows:

<?php

namespace Zetcho\AmColAnBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class BaseController extends Controller
{
    public function validateUser()
    {
        $user['first_name'] = "Name";
        $user['signin'] = true;
        return $user;
    }
}
class DefaultController extends BaseController
{
    public function indexAction()
    {
        $user = $this->validateUser();
        $displayParms['user'] = $user;
        return $this->render('ZetchoAmColAnBundle:Default:index.html.twig',$displayParms);
    }
}

The code is in src/Zetcho/AmColAnBundle/Controller/DefaultController.php The test code works. I'd now like to move the parent class (BaseController) out of the controller file to its own so I can reuse it in my other controllers. I want to put it in the same directory as the other controllers and I'd like to declare it the same way as the Controller in the use statement above. What's the best/accepted way to do this in Symfony 2?

Upvotes: 0

Views: 198

Answers (1)

vascowhite
vascowhite

Reputation: 18430

You do this in Symfony2 exactly the same way as you would with any PHP class. Split your classes into separate files like this:-

src/Zetcho/AmColAnBundle/Controller/BaseController.php

namespace Zetcho\AmColAnBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;

class BaseController extends Controller
{
    public function validateUser()
    {
        $user['first_name'] = "Name";
        $user['signin'] = true;
        return $user;
    }
}

src/Zetcho/AmColAnBundle/Controller/DefaultController.php

namespace Zetcho\AmColAnBundle\Controller;

use Zetcho\AmColAnBundle\Controller\BaseController;

class DefaultController extends BaseController
{
    public function indexAction()
    {
        $user = $this->validateUser();
        $displayParms['user'] = $user;
        return $this->render('ZetchoAmColAnBundle:Default:index.html.twig',$displayParms);
    }
}

Its really quite simple once you know how. Remember that controllers in symfony2 are just normal PHP classes, there is nothing special about them.

Upvotes: 1

Related Questions