How to connect to database from custom files/classes in Silex

doctrine, php, silex

Solution

First thing you need to know is that accessing `$app` is a bad practice. You should DI when it is possible. If you really want to do that, check the code below.

Inside `index.php` (usually `bootstrap.php`) declare a new service:

$app['my_class'] = $app->share(function() use ($app) {
    // Retrieve the db instance and create an instance of myClass
    return new \MyNameSpace\myClass($app['db']);
});

Add a constructor sur `myClass`:

namespace MyNameSpace;

class myClass
{
    /**
     * The connection
     *
     * @var \Doctrine\DBAL\Connection
     */
    private $db;

    /**
     * Constructor
     *
     * @param $db \Doctrine\DBAL\Connection
     */
    public function __construct($db)
    {
        $this->db = $db;
    }

    // ...
}

Then you can retrieve a fully initialized instance of `myClass` like this:

$myClass = $app['my_class'];

Problem

I'm trying this mini framework for the first time and this is my first time at all using justa a framework:) I added the doctrine service to my index.php file like this: ``` $app->register(new Silex\Provider\DoctrineServiceProvider(), array( 'db.options' => array( 'driver' => 'pdo_sqlite', 'path' => __DIR__.'/../include/database.sqlite', ), )); ``` and I create a new file with a class with a static method that resturn an array, for example. ``` <?php namespace MyNameSpace; class myClass{ static function getStuff(){ return array(1 => array('foo'=> 'bar', 'bar' => 'foo', ) ); } } ``` As you can see it's hardcoded so I decide to use a database (sqlite is enought) but I don't know how to get access to $app variable inside my file. On the other way, all the tutorials that I can find online are confusing and referred to a old Silex's version with the .phar file that now is deprecated, and the directory structures of all examples I found are differente from mine (taken from the fat Silex zip file) The directory structure of my project is this: ``` ├── composer.json ├── composer.lock ├── src │ └── MyNameSpace │ └── myClass.php ├── vendor │ └── composer │ └── doctrine │ └── silex │ └── ... │ └── **autoload.php** └── web └── css └── img └── js └── views └── .htaccess └── index.php ```

Original source