Skip to content

Instantly share code, notes, and snippets.

@jhonnyoliveira
Last active June 9, 2022 13:12
Show Gist options
  • Save jhonnyoliveira/56e0ff6d49537d2b978d93d502fbc18a to your computer and use it in GitHub Desktop.
Save jhonnyoliveira/56e0ff6d49537d2b978d93d502fbc18a to your computer and use it in GitHub Desktop.
Exemplo de uso do PHP-DI e Slim
<?php
use App\Infra\DbConnection;
use Psr\Container\ContainerInterface;
return [
'db.name' => getenv("DB_NAME"),
'db.user' => getenv("DB_USER"),
'db.password' => getenv("DB_PASSWORD"),
DbConnection::class => function (ContainerInterface $c) {
return new DbConnection($c->get('db.name'), $c->get('db.user'), $c->get('db.password'));
},
];
<?php
require_once "vendor/autoload.php";
use DI\ContainerBuilder;
use Slim\Factory\AppFactory;
use App\Controller\LoginController;
$containerBuilder = new ContainerBuilder();
$containerBuilder->addDefinitions('di-config.php');
AppFactory::setContainer($container);
$app = AppFactory::create();
$app->post('/login', "{LoginController::class}:login");
$app->addRoutingMiddleware();
$app->addErrorMiddleware(true, true, true);
<?php
namespace App\Controller;
use App\Repository\UsuarioRepository;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
class LoginController extends Controller
{
private UsuarioRepository $repository;
public function __construct(ContainerInterface $container)
{
parent::__construct($container);
$this->repository = $this->container->get(UsuarioRepository::class);
}
public function login(Request $request, Response $response, array $args): Response
{
$login = $this->getParam($request, 'login', '');
$password = $this->getParam($request, 'password', '');
try {
$user = $this->repository->auth($login, $password);
} catch (\DomainException $e) {
$new_response = $response->withStatus(403);
return $new_response;
}
return $this->toJson($response, ['jwt' => $usuario->getId(), 'user' => $user]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment