1. Go to this page and download the library: Download isszz/webman-hashids library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
public function getIdAttr($value)
{
return id_encode($value);
}
// 主键非id时, 比如是tid时
public function getTidAttr($value)
{
return id_encode($value);
}
// 10.x版本
use Illuminate\Database\Eloquent\Casts\Attribute;
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
protected function id(): Attribute
{
return Attribute::make(
get: fn (int $value) => id_encode($value),
);
}
}
// 8.x版本
use Illuminate\Database\Eloquent\Model;
class User extends Model
{
public function getIdAttribute($value)
{
return id_encode($value);
}
}
namespace app\middleware;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;
class Hashid implements MiddlewareInterface
{
public function process(Request $request, callable $next): Response
{
$parameters = [];
$route = $request->route;
if ($route) {
$parameters = $route->param() ?: [];
foreach ($parameters as $k => $v) {
$parameters[$k] = $this->decodeParam($v) ?: $v;
}
$route->setParams($parameters);
}
// POST + GET 用data传值,因官方没有对参数进行二次修改的方法只有这样啦,不过也挺好用的
$parameters = $request->all();
if ($parameters && count($parameters) > 0) {
foreach ($parameters as $k => $v) {
$parameters[$k] = $this->decodeParam($v) ?: $v;
}
$request->data = $parameters;
}
return $next($request);
}
private function decodeParam($value)
{
if (!preg_match("/^[0-9a-zA-Z@]+$/", $value)) {
return null;
}
// 切换模式
if (str_contains($value, '@')) {
[$value, $type] = explode('@', $value);
}
try {
return id_decode($value, $type ?? '') ?: null;
} catch(\Exception $e) {}
return null;
}
}