laravel-eloquent – Is there any way to use Laravel Eloquent in Silex microframework?

Question:

I'm refactoring a site structure and moving to the Silex microframework.

I would like to know if there is any way to use Laravel's Eloquent ORM to connect to the database.

I read in the documentation that you can use Doctrine, but I didn't really like the idea.

So I would like to know if there is any library that allows me to use Laravel's ORM (Eloquent) on Silex?

Answer:

You can use it, as the illuminate/database repository itself, in fact it is possible to use it independently of anything, that is, you can probably use it in any framework, the only dependencies are to install via composer and have php5.6+, or either this will work for both Silex and anything equivalent.

Type in the terminal inside your composer require "illuminate/database" , if you are going to use the events you also need the composer require "illuminate/events" command

Or configure composer.json (5.4 is the most current version before the development version, you can see other versions):

"illuminate/database": "~5.4",
"illuminate/events": "~5.4"

And then run composer update .

Add autoload.php and call it in a PHP like this:

<?php

use Illuminate\Database\Capsule\Manager as Capsule;

require __DIR__ . '/vendor/autoload.php';

$capsule = new Capsule;

//Exemplo mysql
$capsule->addConnection([
    'driver'    => 'mysql',
    'host'      => 'localhost',
    'database'  => 'database',
    'username'  => 'root',
    'password'  => 'password',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
]);

// Define o dispatcher usado pelos models do Eloquent (opcional)
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;
$capsule->setEventDispatcher(new Dispatcher(new Container));

// Faz essa instancia de Capsule ficar disponível globalmente usando metodos estaticos (opcional)
$capsule->setAsGlobal();

// Configura o Eloquent ORM... (opcional e desnecessário se você já usou setEventDispatcher())
$capsule->bootEloquent();

That part above you could put in a global file which would be accessible to everyone, or when you call a specific namespace, for example \Model\foo\bar (I'll talk about this later).

After including the above file, you can use:

  • QueryBuilder

    $users = Capsule::table('users')->where('votes', '>', 100)->get();
    
  • Schema Builder

    Capsule::schema()->create('users', function($table)
    {
        $table->increments('id');
        $table->string('email')->unique();
        $table->timestamps();
    });
    
  • Eloquent ORM (creio que seja este que lhe interessa):

    class User extends Illuminate\Database\Eloquent\Model {}
    
    $users = User::where('votes', '>', 1)->get();
    

Creating a namespace to use Models

Now let's say you won't use ORM on every page, there's really no reason to load everything if you won't, so you might want to organize your project based on a namespace, I suggest doing something like:

  1. Create a namespace in composer.json to point to a folder where the models will be:

     ... "require": { "php": ">=5.6.4", "illuminate/database": "~5.4", "illuminate/events": "~5.4" }, "autoload": { "psr-4": { "FooBarModel\\": "app/Models" } }, ...

This case is an example, assuming you have a folder called ./app/Models inside the project.

  1. You can create an abstract Model that will be the basis of everything in ./app/Models/Model.php , that way you'll avoid including Eloquent in calls that won't use the database (of course this is just a way to organize)

    In this case you should remove from the global file everything I mentioned before leaving only require :

     <?php namespace FooBarModel; use \Illuminate\Database\Capsule\Manager as Capsule; use \Illuminate\Events\Dispatcher; use \Illuminate\Container\Container; $capsule = new Capsule; $capsule->addConnection([ 'driver' => 'mysql', 'host' => 'localhost', 'database' => 'database', 'username' => 'root', 'password' => 'password', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci', 'prefix' => '', ]); $capsule->setAsGlobal(); $capsule->bootEloquent(); //Cria a classe abstract class Model extends \Illuminate\Database\Eloquent\Model {}
  2. So now in the same folder you can create a Model called User ( ./app/Models/User.php ):

     <?php namespace FooBarModel; class User extends Model {}

    If it's in a subfolder ( ./app/Models/Admin/FooBar.php ):

     <?php namespace FooBarModel\Admin; class FooBar extends \FooBarModel\Model {}
  3. Create global.php (or something like that) that has require __DIR__ . '/vendor/autoload.php'; , or if you have boot.php or in your index.php for life, throw it there, assuming:

     <?php require __DIR__ . '/vendor/autoload.php';
  4. So to call a specific Model, for doing so:

     <?php require __DIR__ . '/vendor/autoload.php'; $user = new FooBarModel\User\User;
  5. An example with Silex might look like this:

     <?php use FooBarModel\User; use FooBarModel\Admin\FooBar; require_once __DIR__ . '/../vendor/autoload.php'; $app = new Silex\Application(); $app->get('/', function () { return 'Home'; }); $app->get('/user', function () { $user = new User; .... }); $app->get('/user', function () { $user = new FooBar; .... }); $app->run();
Scroll to Top