PHP code example of ngyuki / ritz

1. Go to this page and download the library: Download ngyuki/ritz library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

ngyuki / ritz example snippets


use function DI\value;
use FastRoute\RouteCollector;
use App\Controller\HomeController;
use App\Controller\UserController;

return [
    'app.routes' => value(function(RouteCollector $r) {
        $r->get('/', [HomeController::class, 'indexAction']);
        $r->get('/user/{id}', [UserController::class, 'showAction']);
    }),
];

// routes.php
return [
    'app.routes' => value(function(RouteCollector $r) {
        $r->get('/', [HomeController::class, 'indexAction', 'attr' => 'val']);
    }),
];

// HomeController.php
class HomeController
{
    public function attrAction(ServerRequestInterface $request)
    {
        $attr = $request->getAttribute('attr'); // val
    }
}

public function showAction(
    // DI コンテナから取得
    UserRepository $userRepository,
    // リクエストオブジェクト
    ServerRequestInterface $request,
    // リクエストのアトリビュートに設定されたルートパラメータ
    $id
) {
    return ['user' => $userRepository->get($id)];
}

// ミドルウェアでリクエストに属性を追加
public function process(ServerRequestInterface $request, DelegateInterface $delegate)
    $requset = $requset->withAttribute('foo', 987);
    $requset = $requset->withAttribute(Bar::class, new Bar());
    return $delegate->process($request);
}

// アクションメソッドに注入される
public function showAction($foo, Bar $bar)) {
    // ...
}

// ViewModel オブジェクトを返す
return new ViewModel();

// テンプレートにアサインする変数を指定する
return new ViewModel(['val' => 123]);

// 配列は自動的に ViewModel オブジェクトに変換される
return ['val' => 123];

return (new ViewModel())->withTemplate('App/Home/index');

return (new ViewModel())->withTemplate('./edit');

// 200 以外のステータスコードとカスタムヘッダを指定する
return (new ViewModel())->withStatus(400)->withHeader('X-Custom', 'xxx');

// リダイレクト
return new RedirectResponse('/');

// 文字列は TextResponse に変換される
return "hello";

// 上と等価
return new TextResponse("hello");

return [
    'app.view.autoload' => [
        'Ritz\\App\\Controller\\' => 'App/',
    ],
    TemplateResolver::class => function (ContainerInterface $container) {
        return new TemplateResolver($container->get('app.view.autoload'));
    },
];
sh
git clone https://github.com/ngyuki/php-ritz-app.git
cd php-ritz-app
composer install
php -S 0.0.0.0:8888 -t public/
open http://localhost:8888/