プログラムのテスト投稿

ソースコードを載せるとどんな感じなんだろうということで、テスト投稿です。

<?php
use DI\Container;
use Slim\Factory\AppFactory;
use Slim\Views\Twig;
use Slim\Views\TwigMiddleware;

require __DIR__ . '/../vendor/autoload.php';

// Create Container
$container = new Container();
AppFactory::setContainer($container);

// Set view in Container
$container->set('view', function() {
  return Twig::create(__DIR__ . '/../templates', ['cache' => __DIR__ . '/../cache']);
});

// Service factory for the ORM
$container->set('db', function ($container) {
  $capsule = new \Illuminate\Database\Capsule\Manager;
  $capsule->addConnection([
    'driver' => 'mysql',
    'host' => 'localhost',
    'database' => 'your database',
    'username' => 'your username',
    'password' => 'your password',
    'charset'   => 'utf8',
    'collation' => 'utf8_unicode_ci',
    'prefix'    => '',
  ]);

  $capsule->setAsGlobal();
  $capsule->bootEloquent();

  return $capsule;
});

// Create App
$app = AppFactory::create();

// Add Twig-View Middleware
$app->add(TwigMiddleware::createFromContainer($app));
// $app->setBasePath('/slimphp-test');

$app->get('/', function($request, $response, $args) {
  $results = $this->get('db')->table('posts')->select('*')->get();

  return $this->get('view')->render($response, 'root.html', [
    'results' => $results,
  ]);
})->setName('root');

$app->get('/private/{name}', function($request, $response, $args){
  $str = $this->get('view')->fetchFromString(
    '<p>Hi, my name is {{ name }}.</p>',
      [
        'name' => $args['name']
      ]
    );
  $response->getBody()->write($str);
  return $response;
})->setName('private');

// Run app
$app->run();

こんな感じですね。GitHubのGistを載せたほうが綺麗かもね。はてなブログシンタックスハイライトはわかりづらいかもしれない。

ちなみに編集モードはMarkdownモードでやってます。移行するのが面倒そうですけど、めったにそういうこともないから大丈夫でしょう。

これでいきます!