1

Accoring to the Symfony 2 Documentation, you have to use the following PHP code to connect to the database and execute a query...

$conn = $this->get('database_connection');
$users = $conn->fetchAll('SELECT * FROM users');

I'm a complete novice with Symfony 2 but I am experienced with OOP. I was wondering if it was possible to have a globally available $conn variable that I can access from any bundle. The $conn variable would contain the value of $this->get('database_connection') so I don't have to retype $conn = $this->get('database_connection');it every time I want to make a new query.

Thanks!

1 Answer 1

3

global variables are most of the time NOT something you want in OOP. They are confusing when it comes to a method which deals with multiple variables and they might even be hidden by local variables. For me, working with statements like

$anything = $this->get('what.the.hell.why.arent.those.identifiers.shorter');

is as annoying as for you so I ended up in creating one subclass of Symfony\Bundle\FrameworkBundle\Controller\Controller per project which provides methods which call get with the actual identifiers. In your case I would create a method

public function getDatabaseConnection()
{
    return $this->get('database_connection');
}

In general - why don't you use Doctrine for managing the DB connection? Most of the queries can be done by the ORM and this is the way to work with a real object-oriented interface to the database. Think about it, I'm also playing with Symfony2/Doctrine since some days and it really feels good. In the beginning, it might look like a hell of configuration, but once you've done the basic configs, the development is really fast! :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! I will certainly trial out both methods to see which works best.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.