2013年6月
[Laravel4] 短网址之统计每日点击数
使用redis计数,laravel4里面默认使用的是predis,这里我使用的是phpredis库,首先注释掉app/config/app.php里面的Redis的alias
// 'Redis' => 'Illuminate\Support\Facades\Redis',
实现代码
使用redis的sorted set储存每日的每个链接的点击次数
$config = Config::get('database.redis.default');
with($redis = new Redis)->connect($config['host'], $config['port']);
$redis->zIncrBy(date('Ym:d'), 1, $link->id);
统计数据,取出当天点击数最多的10个链接的id
$redis->zRevRange(date('Ym:d'), 0, 9);
[Laravel4] 短网址之API
我们提供三种格式的API, txt json jsonp
代码
路由
Route::get('short.txt', 'ShortController@txt');
Route::get('short.json', 'ShortController@json');
Route::get('short.jsonp', 'ShortController@jsonp');
控制器
public function txt() {
$validator = Validator::make(Input::all(), [
'url' => 'required|max:255|url',
]);
if ($validator->fails()) {
return implode(PHP_EOL, $validator->errors()->all());
}
$url = Input::get('url');
$hash = md5($url);
$link = Link::whereHash($hash)->first();
if (!$link)
$link = Link::create(compact('url', 'hash'));
$shorten = \Lib\Base62::encode($link->id);
return 'http://usr.im/' . $shorten;
}
public function json() {
$resp = [];
$validator = Validator::make(Input::all(), [
'url' => 'required|max:255|url',
]);
if ($validator->fails()) {
return ['status' => 'failed', 'message' => $validator->errors()->all()];
}
$url = Input::get('url');
$hash = md5($url);
$link = Link::whereHash($hash)->first();
if (!$link)
$link = Link::create(compact('url', 'hash'));
$shorten = \Lib\Base62::encode($link->id);
return ['status' => 'success', 'content' => 'http://usr.im/' . $shorten];
}
public function jsonp() {
$resp = [];
Validator::extend('callback', function($attribute, $value, $parameters) {
return preg_match('/^[A-z_]\w*$/i', $value);
});
$validator = Validator::make(Input::all(), [
'url' => 'required|max:255|url',
'callback' => 'required|max:255|callback',
]);
if ($validator->fails()) {
return Response::json(['status' => 'failed', 'message' => $validator->errors()->all()])
->setCallback(Input::get('callback'));
}
$url = Input::get('url');
$hash = md5($url);
$link = Link::whereHash($hash)->first();
if (!$link)
$link = Link::create(compact('url', 'hash'));
$shorten = \Lib\Base62::encode($link->id);
return Response::json(['status' => 'success', 'content' => 'http://usr.im/' . $shorten])
->setCallback(Input::get('callback'));
}