Last active
April 28, 2020 22:51
-
-
Save l0gicgate/68b82a8a56e301e23a0fe5ea895a4185 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
use Application\Middleware\MyAuthMiddleware; | |
use DI\Container; | |
use DI\ContainerBuilder; | |
use Monolog\Logger; | |
use Psr\Log\LoggerInterface; | |
use PDO; | |
use PDOException; | |
use Slim\AppFactory; | |
use function DI\create; | |
use function DI\autowire; | |
require __DIR__ . '/../vendor/autoload.php'; | |
// Create Container & Definitions | |
$containerBuilder = new ContainerBuilder(); | |
$containerBuilder->addDefinitions([ | |
LoggerInterface::class => create(Logger::class), | |
MyAuthMiddleware::class => autowire(MyAuthMiddleware::class), | |
PDO::class => function (): PDO { | |
$dsn = 'mysql:dbname=testdb;host=127.0.0.1'; | |
$user = 'dbuser'; | |
$password = 'dbpass'; | |
try { | |
return new PDO($dsn, $user, $password); | |
} catch (PDOException $e) { | |
echo 'Connection failed: ' . $e->getMessage(); | |
} | |
}, | |
]); | |
$container = $containerBuilder->build(); | |
// Create App | |
AppFactory::setContainer($container); | |
$app = AppFactory::create(); | |
// Add Deferred Auth Middleware | |
$app->add(MyAuthMiddleware::class); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace Application\Middleware; | |
use PDO; | |
use Psr\Log\LoggerInterface; | |
use Psr\Http\Message\ResponseInterface; | |
use Psr\Http\Message\ServerRequestInterface; | |
use Psr\Http\Server\MiddlewareInterface; | |
class MyAuthMiddleware implements MiddlewareInterface | |
{ | |
private LoggerInterface $logger; | |
private PDO $pdo; | |
public function __construct(PDO $pdo, LoggerInterface $logger) | |
{ | |
$this->pdo = $pdo; | |
$this->logger = $logger; | |
} | |
public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface | |
{ | |
// Your logic here | |
// Use $this->pdo | |
// User $this->logger | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment