Zug Zwang Zug Zwang - 21 days ago 8
PHP Question

Call to a function of another Bundle in Symfony2

In my app I have two diverse Bundles,

BaseBundle
and
UserBundle
.
When I'm in one of the controllers of
UserBundle
, how can I access the functions available in
BaseBundle
?

I'm in
UserBundle
and I'm trying to do something like:

$property['x'] = $this->calculateNumber(array($propertyX->indexX, $propertyY->indexY));


This is the error I get:

Attempted to call method "calculateNumber" on class "Example\UserBundle\Controller\DefaultController".
500 Internal Server Error - UndefinedMethodException

Answer

That's where Symfony's namespaces comes in handy. So when you are in UserBundle, just import the class containing the method you want to call:

# UserBundle/Controller/UserController.php
use BaseBundle\Controller\DefaultController;
//...

class UserController extends Controller
{
    /**
     * @Route("/whatever", name="whatever")
     */
    public function whatever()
    {
        $base = new DefaultController(); //instantiate the class containing the desired method
        $property['x'] = $base->calculateNumber(array($propertyX->indexX, $propertyY->indexY)); //call the calculateNumber method
    }
}