Slim4めも

$ php composer.phar require slim/twig-view

app/settings.php

<?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,
            ],
            'twig' => [
                'path' => __DIR__ . '/../src/Resource/template',
                'cache' => __DIR__ . '/../var/cache/twig',
                'auto_reload' => true,
            ],
        ],
    ]);
};

app/dependencies.php

use Slim\Views\Twig;
use Twig\Loader\FilesystemLoader;
    $containerBuilder->addDefinitions([
        Twig::class => function (ContainerInterface $c) {
            $settings = $c->get('settings')['twig'];

            $loader = new FilesystemLoader(
                $settings ['path'],
            );
            $options = [
                'cache' => $settings['cache'],
                'auto_reload' => $settings['auto_reload'],
            ];

            $view = new Twig(
                $loader,
                $options
            );

            return $view;
        },
    ]);

src/Application/Actions/Action.php

use Slim\Views\Twig;
    /**
     * @var Twig
     */
    protected $view;

    /**
     * @param LoggerInterface $logger
     * @param Twig $view
     */
    public function __construct(
        LoggerInterface $logger,
        Twig $twig
    ) {
        $this->logger = $logger;
        $this->view = $twig;
    }

src/Application/Actions/User/UserAction.php

use Slim\Views\Twig;
    /**
     * @param LoggerInterface $logger
     * @param Twig $view
     * @param UserRepository  $userRepository
     */
    public function __construct(LoggerInterface $logger, Twig $view, UserRepository $userRepository)
    {
        parent::__construct($logger, $view);
        $this->userRepository = $userRepository;
    }

src/Application/Actions/User/ListUsersAction.php

<?php
declare(strict_types=1);

namespace App\Application\Actions\User;

use Psr\Http\Message\ResponseInterface as Response;

class ListUsersAction extends UserAction
{
    /**
     * {@inheritdoc}
     */
    protected function action(): Response
    {
        $users = $this->userRepository->findAll();

        $this->logger->info("Users list was viewed.");

        return $this->view->render($this->response,
            'list_users.twig',
            [
                'users' => $users,
            ]
        );
    }
}

トップ   編集 凍結 差分 バックアップ 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS
Last-modified: 2021-09-19 (日) 19:09:35