エントリー

Silexでセッションとデータベースとテンプレートを使うメモ

Silexの機能をいくつか使ってみたのでメモ。

主にSilexユーザーガイドを参考にしていますが、自分のやりやすいように解説と違っている箇所があります。Silex自体の導入はSilex導入メモに記載しています。

Silexでセッションを使う

セッションを使う仕組みは、標準で用意されている。

$app->register(new Silex\Provider\SessionServiceProvider(), array(
));

でセッションプロバイダーを使うことを宣言。あとは $app['session'] にアクセスすれば、セッションを扱うための命令を呼び出せる。

以下は参考コード。

<?php

require_once __DIR__ . '/silex/vendor/autoload.php';

$app = new Silex\Application();
$app['debug'] = true;

$app->register(new Silex\Provider\SessionServiceProvider(), array(
));

$app->get('/', function() use($app) {
  $app['session']->start();

  if ($app['session']->has('count')) {
    $count = $app['session']->get('count');
  } else {
    $count = 0;
  }

  $app['session']->set('count', ++$count);

  return 'count=' . $app['session']->get('count');
});

$app->run();

exit;

?>

Silexでデータベースを使う

Doctrine経由でデータベースに接続する仕組みが、標準で用意されている。ただしDoctrineそのものは同梱されていないので、自分で導入する必要がある。

まずはDoctrineからファイルをダウンロードする。解凍して作成されたファイルを silex/vendor/doctrine/ 内に配置する。

test / index.php
  |
  +-- silex / LICENSE
        |
        +-- src / ~略~
        |
        +-- vendor / autoload.php
              |
              +-- composer / ~略~
              |
              +-- doctrine / doctrine-mapping.xsd
              |       |      LICENSE
              |       |      package.xml
              |       |      UPGRADE_TO_2_0
              |       |      UPGRADE_TO_2_1
              |       |      UPGRADE_TO_2_2
              |       |      UPGRADE_TO_ALPHA3
              |       |      UPGRADE_TO_ALPHA4
              |       |
              |       +-- bin / ~略~
              |       |
              |       +-- Doctrine / ~略~
              |
              +-- pimple / ~略~
              |
              +-- symfony / ~略~

次に

$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
  'db.options' => array(
    'dbname'   => 'データベース名',
    'user'     => 'データベース接続ユーザー名',
    'password' => 'データベース接続パスワード',
    'host'     => '接続先',
    'driver'   => 'ドライバ',
  ),
  'db.dbal.class_path'   => __DIR__ . '/silex/vendor/doctrine',
  'db.common.class_path' => __DIR__ . '/silex/vendor/doctrine'
));

でDoctrineプロバイダーを使うことを宣言。あとは $app['db'] にアクセスすれば、データベースを扱うための命令を呼び出せる。

以下は参考コード。

<?php

require_once __DIR__ . '/silex/vendor/autoload.php';

$app = new Silex\Application();
$app['debug'] = true;

$app->register(new Silex\Provider\DoctrineServiceProvider(), array(
  'db.options' => array(
    'dbname'   => 'test',
    'user'     => 'xxxx',
    'password' => 'yyyy',
    'host'     => 'localhost',
    'driver'   => 'pdo_mysql',
  ),
  'db.dbal.class_path'   => __DIR__ . '/silex/vendor/doctrine',
  'db.common.class_path' => __DIR__ . '/silex/vendor/doctrine'
));

$app->get('/', function() use($app) {
  $stmt = $app['db']->query('SELECT * FROM address');

  $result = '';
  while ($row = $stmt->fetch()) {
      $result .= $row['no'] . ' / ' . $row['name'] . ' / ' . $row['tel'] . '<br />';
  }

  return $result;
});

$app->run();

exit;

?>

Silexでテンプレートを使う

Twig経由でテンプレートを使用する仕組みが、標準で用意されている。ただしTwigそのものは同梱されていないので、自分で導入する必要がある。

まずはTwigからファイルをダウンロードする。解凍して作成されたファイルを silex/vendor/twig/ 内に配置する。

test / index.php
  |
  +-- silex / LICENSE
        |
        +-- src / ~略~
        |
        +-- vendor / autoload.php
              |
              +-- composer / ~略~
              |
              +-- pimple / ~略~
              |
              +-- symfony / ~略~
              |
              +-- twig / .travis.yml
                    |    AUTHORS
                    |    CHANGELOG
                    |    composer.json
                    |    LICENSE
                    |    package.xml.tpl
                    |    phpunit.xml.dist
                    |    README.markdown
                    |
                    +-- bin / ~略~
                    |
                    +-- doc / ~略~
                    |
                    +-- ext / ~略~
                    |
                    +-- lib / ~略~
                    |
                    +-- test / ~略~

次に

$app->register(new Silex\Provider\TwigServiceProvider(), array(
  'twig.path'       => __DIR__ . '/views',
  'twig.class_path' => __DIR__ . '/silex/vendor/twig/lib',
));

でTwigプロバイダーを使うことを宣言。(twig.path は、テンプレートを配置するためのディレクトリ)あとは $app['twig'] にアクセスすれば、Twigを扱うための命令を呼び出せる。

以下は参考コード。

<?php

require_once __DIR__ . '/silex/vendor/autoload.php';

$app = new Silex\Application();
$app['debug'] = true;

$app->register(new Silex\Provider\TwigServiceProvider(), array(
  'twig.path'       => __DIR__ . '/views',
  'twig.class_path' => __DIR__ . '/silex/vendor/twig/lib',
));

$app->get('/', function() use($app) {
  $variables['test1'] = 'これはテストです。';
  $variables['test2'] = array('テスト1', 'テスト2', 'テスト3');

  return $app['twig']->render('test.html', $variables);
});

$app->run();

exit;

?>

テンプレートは views ディレクトリ内に test.html を作成し、以下の内容を記述する。

<html>
<head>
<meta charset="utf-8" />
<title>title</title>
</head>
<body>
<h1>テスト</h1>
<p>{{ test1 }}</p>
<ul>
  <!--{% for test in test2 %}-->
  <li>{{ test }}</li>
  <!--{% endfor %}-->
</ul>
</body>
</html>

ページ移動

ユーティリティ

カテゴリー

検索

エントリー検索フォーム
キーワード

過去ログ

過去ログ表示フォーム
キーワード

Feed