Search code examples
ormsilexredbean

Integrate silex with Redbean orm


Any one have idea how to integrate Red bean ORM in Silex. Any examples/docs available.Please help me.

Thanks


Solution

  • This is a very basic setup shown below.

    Since Redbean provides a static class facade RedBean_Facade, which in the docs is referred to as R, there's little need to register it as a service of the Silex Application.

    You should ideally install both Silex and Redbean with Composer. On the Redbean Github page it tells you how to use it with Composer.

    <?php
    
    require __DIR__.'/vendor/autoload.php';
    
    use Silex\Application;
    use Symfony\Component\HttpFoundation\Request;
    use Symfony\Component\HttpFoundation\Response;
    use RedBean_Facade as R;
    
    $app = new Application();
    
    $app['db.connection.default.driver'] = "mysql";
    $app['db.connection.default.host'] = "localhost";
    $app['db.connection.default.name'] = "mydatabase";
    $app['db.connection.default.user'] = "user";
    $app['db.connection.default.password'] = "password";
    
    $app['db.connection.default.rsn'] = $app->share(function () use ($app) {
        return sprintf('%s:host=%s;dbname=%s',
            $app['db.connection.default.driver'],
            $app['db.connection.default.host'],
            $app['db.connection.default.name']
        );
    });
    
    R::setup(
        $app['db.connection.default.rsn'],
        $app['db.connection.default.user'],
        $app['db.connection.default.password']
    );
    
    $app->get('/article/{id}/show', function ($id) {
        $article = R::load('article', $id );
    
        // do something with $article, then
        // return an HTML page of the article.
    });
    
    $app->get('/article/new', function () {
        // return an HTML page with a form that contains
        // input fields with HTML name attributes set to
        // 'title' and 'body' for example.
    });
    
    $app->post('/article/new', function (Request $request) use ($app) {
        $article = R::dispense('article');
    
        $article->title = $request->request->get('title');
        $article->body = $request->request->get('body');
    
        $id = R::store($article);
    
        return $app->redirect(sprintf('/article/%d/show', $id));
    });
    
    $app->run();