Skip to content

Instantly share code, notes, and snippets.

@k-holy
Created November 13, 2012 10:14
Show Gist options
  • Save k-holy/4065017 to your computer and use it in GitHub Desktop.
Save k-holy/4065017 to your computer and use it in GitHub Desktop.
Gehirn RS2を使ってみたメモ Silex + MySQL
{
"require": {
"silex/silex": "1.0.*",
"doctrine/dbal": "2.2.*"
},
"minimum-stability": "dev"
}
<?php
return array(
'driver' => 'pdo_mysql',
'host' => 'localhost',
'dbname' => 'データベース名',
'user' => 'ユーザー名',
'password' => 'パスワード',
'charset' => 'utf8',
);
<?php
require_once __DIR__ . '/../vendor/autoload.php';
use Silex\Application;
use Silex\Provider\DoctrineServiceProvider;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
$app = new Application();
$app->register(new DoctrineServiceProvider(), array(
'db.options' => include __DIR__ . '/../doctrine.php'
));
$app->get('/{name}', function(Application $app, Request $request, $name) {
$data = array();
if (!is_string($name)) {
throw new BadRequestHttpException('Invalid Name.');
}
$data['name'] = $name;
$user_agent = $request->server->get('HTTP_USER_AGENT');
if (!is_string($user_agent)) {
throw new BadRequestHttpException('Invalid UserAgent.');
}
$data['user_agent'] = $user_agent;
$request_time = $request->server->get('REQUEST_TIME');
if (!is_int($request_time)) {
throw new BadRequestHttpException('Invalid Request Time.');
}
$request_datetime = new \DateTime();
$request_datetime->setTimestamp($request_time);
$data['requested_at'] = $request_datetime->format('Y-m-d H:i:s');
try {
$app['db']->beginTransaction();
/*
$create_sql = <<< SQL
CREATE TABLE IF NOT EXISTS accesslogs(
id INT UNSIGNED AUTO_INCREMENT NOT NULL
, requested_at DATETIME NOT NULL
, name VARCHAR(255)
, user_agent VARCHAR(255)
, CONSTRAINT accesslogs_pk PRIMARY KEY (id)
);
SQL;
$app['db']->executeQuery($create_sql);
*/
$insert_sql = <<< SQL
INSERT INTO
accesslogs
(
requested_at
, name
, user_agent
) VALUES (
:requested_at
, :name
, :user_agent
);
SQL;
$app['db']->executeQuery($insert_sql, $data);
} catch (\Exception $e) {
$app['db']->rollback();
throw $e;
}
$app['db']->commit();
$select_sql = <<< SQL
SELECT
id
, requested_at
, name
, user_agent
FROM
accesslogs
ORDER BY
requested_at DESC
LIMIT 10;
SQL;
$statement = $app['db']->executeQuery($select_sql);
$items = array();
foreach ($statement as $item) {
$items[] = sprintf('<li>[%s] (%d)%s %s</li>',
$app->escape($item['requested_at']),
$app->escape($item['id']),
$app->escape($item['name']),
$app->escape($item['user_agent'])
);
}
$content = <<< CONTENT
<html>
<body>
<h1>こんにちは %s さん</h1>
<ul>%s</ul>
</body>
</html>
CONTENT;
return new Response(sprintf($content, $app->escape($name), implode("\n", $items)));
})
->value('name', '名無し');
$app->run();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment