
使用方法
1、复制 src 文件加中所有文件到项目根目录中
2、把 universal_shorturl.sql 导入数据库
3、手动路由添加, 注:src 中已经包含此配置文件,如果原项目中配置过手动路由,需要按添加下面代码。
use App\Universal\ShortUrl\ShortUrl;
$route -> get('/^\/u\/([A-Za-z0-9]+)$/', function($code){
return ShortUrl::routeHandle($code);
});
以新闻模块为例,添加自动生成短网址的钩子。修改 manage.php 如下:
use App\Universal\ShortUrl\ShortUrl;
public function __start()
{
$this -> hook -> afterAutoSave = function($argId, $argType){
$id = intval($argId);
$type = strval($argType);
if ($type == 'add')
{
$fullUrl = $this -> getParam('full_host');
$genre = $this -> getParam('genre');
$url = $fullUrl . '/' . $genre . '/?type=detail&id=' . $id;
$shortUrl = ShortUrl::shortUrl($url);
if (!is_null($shortUrl)) {
$model = new TinyModel();
$model -> where -> id = $id;
$model -> pocket -> shorturl = $shortUrl;
$model -> save();
}
}
};
}