Search code examples
symfonyglobal-variablessymfony-3.3

Using parameters.yml in Symonfy 3.3


I still trying to know which way to use the parameters is the most logical and efficient way.

I realize that I can get the parameters from the parameters.yml in the Controller thanks to the "extends Controller" and "use Symfony\Bundle\FrameworkBundle\Controller\Controller;" I added in the Controller file.

From this controller I instance a new User() from the file User.php in AppBundle\Model\User; that I created and looks like this:

namespace AppBundle\Model;

use \PDO;


class User
{

    private function open_database_connection()
    {
        $link = new PDO("mysql:host=database_host;dbname=database_name","database_user","database_password");
        return $link;
    }
    public function get_something_from_database()
    {

        $link = $this->open_database_connection();
        //query's execution, fetch, etc...
        ...
    }

    ...

}

At the moment as you can see I just write the parameters straight to the new PDO function to make the connection but I want to use the parameters from the parameters.yml file.

As I see, I could pass the connection's parameters from the controller creating an user object and passing to the function get_something_from_database($parametersConnection) by parameters and finally to the open_database_connection also by parameters.

My question is... exist any way to avoid to pass all the time the parameters of the connection from the controller to the model objects? Perhaps a way to get the parameters from the parameters.yml straight from inside the function open_database_connection or some other solution?

How you do it usually? Thank you for you help.


Solution

  • So finally I discovered how to use the connexion from Doctrine. I will expose what I will do. If you think I'm wrong please answer me again.

    What I will do is, every time I need to play with the db I will send the connection by parameter to the instance of the model.

    From Controller inside an action function:

    $user = new User($this->container->get('database_connection'));
    $something = $user->get_something_from_db_options();
    

    From the last Model explained called User I will leave it like this:

    namespace AppBundle\Model;
    
    use \PDO;
    
    
    class User
    {
        private $connection;
    
        public function __construct($connection)
        {
            $this->connection = $connection;
        }
    
        public function get_something_from_database()
        {
    
           $result = $this->connection->query('SELECT * FROM users');
           ...
        }
    ...
    }
    

    I hope it's starting to looks better.

    I'm trying to avoid the mapping and entitys concept from the Doctrine I just want to make the connection the rest of things about db I want to control them myself.

    If you think I can clean more my code please don't stop saying me this.