use Silex\Application; use Doctrine\DBAL\DriverManager; $app = new Application(); $dbParams = array( 'dbname' => 'my_database', 'user' => 'root', 'password' => '', 'host' => 'localhost', 'driver' => 'pdo_mysql', ); $app['db'] = $app->share(function() use ($dbParams) { return DriverManager::getConnection($dbParams); });
use Symfony\Component\HttpFoundation\Response; $app->get('/users', function() use ($app) { $users = $app['db']->fetchAll('SELECT * FROM users'); $response = new Response(json_encode($users)); $response->headers->set('Content-Type', 'application/json'); return $response; });
use Silex\Application; $app = new Application(); $config = array( 'debug' => true, 'cache_dir' => __DIR__.'/cache', 'base_url' => 'http://localhost/myapp', ); $app['config'] = $app->share(function() use ($config) { return $config; });
$app['config']['debug']; // true $app['config']['cache_dir']; // __DIR__.'/cache' $app['config']['base_url']; // 'http://localhost/myapp'Overall, the Silex Application Share package library provides an easy way to share data and resources across different parts of a Silex application, improving code reusability and reducing duplication.