Slim Framework 4 with Eloquent ORM

Asked

Viewed 1,073 times

1

I am using the Slim-Framework in version 4 for api creation and would like to use together Eloquent to facilitate manipulation with the database. But I couldn’t find any material/example of how to use it in the project.

The only official material I could find was in this link but the structure is from version 3 of Slim and is not updated.

I cloned that one repository to be worked on and there is a file called 'dependencies.php' I think probably the connection would fit here, how can I do that? Or I’d better use Slimframework version 3?

php dependencies.

<?php
declare(strict_types=1);

use DI\ContainerBuilder;
use Monolog\Handler\StreamHandler;
use Monolog\Logger;
use Monolog\Processor\UidProcessor;
use Psr\Container\ContainerInterface;
use Psr\Log\LoggerInterface;

return function (ContainerBuilder $containerBuilder) {
    $containerBuilder->addDefinitions([
        LoggerInterface::class => function (ContainerInterface $c) {
            $settings = $c->get('settings');

            $loggerSettings = $settings['logger'];
            $logger = new Logger($loggerSettings['name']);

            $processor = new UidProcessor();
            $logger->pushProcessor($processor);

            $handler = new StreamHandler($loggerSettings['path'], $loggerSettings['level']);
            $logger->pushHandler($handler);

            return $logger;
        },
    ]);
};

1 answer

2


You need to do some steps like adding connection settings to the file settings.php of the briefcase app as follows:

<?php
declare(strict_types=1);

use DI\ContainerBuilder;
use Monolog\Logger;

return function (ContainerBuilder $containerBuilder) {
    // Global Settings Object
    $containerBuilder->addDefinitions([
        'settings' => [
            'displayErrorDetails' => true, // Should be set to false in production
            'logger' => [
                'name' => 'slim-app',
                'path' => isset($_ENV['docker']) ? 'php://stdout' 
                                                 : __DIR__ . '/../logs/app.log',
                'level' => Logger::DEBUG,
            ],
            'db' => [
                'driver' => 'mysql',
                'host' => 'localhost',
                'database' => 'db',
                'username' => 'root',
                'password' => 'senha',
                'charset'   => 'utf8',
                'collation' => 'utf8_unicode_ci',
                'prefix'    => '',
            ],
        ],
    ]);
};

after this configuration inside the folder src create a folder Models (src\Models) by putting your Models and a connection configuration that will be used in the route file, example:

Create the file so you can move up your settings Eloquent:

<?php namespace App\Models;

use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Events\Dispatcher;
use Illuminate\Container\Container;

final class Bootstrap
{
    public static function load($container)
    {        
        $settings = $container->get('settings');            
        $capsule = new Capsule();        
        $capsule->addConnection($settings['db']);
        $capsule->setEventDispatcher(new Dispatcher(new Container));
        $capsule->setAsGlobal();
        $capsule->bootEloquent();                
    }
}

and as an example Model by the name of User (just to test):

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model as Eloquent;

class User extends Eloquent
{
    protected $table = 'users';
    protected $fillable = ['name','email','password'];
    protected $primaryKey = 'id';
    protected $dates = ['created_at', 'updated_at'];
}

To finish between inside app\routes.php and just down the line: $container = $app->getContainer(); writes the line Bootstrap::load($container); who is responsible for raising the settings of the Eloquent:

<?php
declare(strict_types=1);

use App\Application\Actions\User\ListUsersAction;
use App\Application\Actions\User\ViewUserAction;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\App;
use Slim\Interfaces\RouteCollectorProxyInterface as Group;

use App\Models\Bootstrap;
use App\Models\User;

return function (App $app) {
    $container = $app->getContainer();    
    Bootstrap::load($container);

    $app->get('/', function (Request $request, Response $response) {
        $response->getbody()->write(json_encode(User::all()->toArray()));         
        return $response;
    });

    $app->group('/users', function (Group $group) use ($container) {
        $group->get('', ListUsersAction::class);
        $group->get('/{id}', ViewUserAction::class);
    });
};

the above example has the line of Model Eloquent:

$response->getbody()->write(json_encode(User::all()->toArray()));

which will print the data from the users where the Eloquent was configured.

Remarks:

Packages that must be installed for this example to work:

  • "doctrine/dbal"
  • "illuminate/database"
  • "illuminate/events"
  • "illuminate/filesystem"
  • "illuminate/pagination"
  • "monolog/monolog"

Browser other questions tagged

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