Is there any way to use Laravel Eloquent in the Silex microframework?

Asked

Viewed 395 times

3

I’m refactoring a website structure and moving on to the Silex microframework.

I wonder if there is any way to use the Laravel Eloquent ORM, to connect with the database.

I read in the documentation that you have how to use Doctrine, but I didn’t really like the idea.

Then I wonder if there is any library that allows me to use the Laravel ORM (Eloquent) in Silex?

  • https://github.com/ziadoz/silex-capsule

1 answer

2


You can use yes, according to the repository itself Illuminate/database, actually it is possible to use it independent of anything, ie you can probably use in any framework, the only dependencies is to install via composer and having php5.6+, that is to say it will work for both Silex and anything equivalent.

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

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 turn the composer update.

Add autoload.php and call 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();

This 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 it 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 (I believe this is the one that interests you):

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

Creating a namespace to use Models

Now let’s say you’re not going to use the ORM on every page, there’s really no reason to upload it all if you’re not going to use it, 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 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 within the project.

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

    In this case you should remove from the global archive all that I quoted earlier by leaving only the 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 is in a subfolder (./app/Models/Admin/FooBar.php):

    <?php
    
    namespace FooBarModel\Admin;
    
    class FooBar extends \FooBarModel\Model {}
    
  3. Create the global.php (or anything like that) that has the require __DIR__ . '/vendor/autoload.php';, or if you have a boot.php or your life index.php play 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();
    

Browser other questions tagged

You are not signed in. Login or sign up in order to post.