Reputation: 3995
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!
Upvotes: 1
Views: 1174
Reputation: 3010
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! :)
Upvotes: 3