76 lines
1.7 KiB
PHP
76 lines
1.7 KiB
PHP
<?php
|
|
|
|
|
|
namespace app;
|
|
|
|
|
|
use Fukuball\Jieba\Finalseg;
|
|
use Fukuball\Jieba\Jieba;
|
|
use Workerman\Protocols\Http\Request;
|
|
use Workerman\Protocols\Http\Response;
|
|
|
|
abstract class Api
|
|
{
|
|
/**
|
|
* @param Request $request
|
|
* @return Response
|
|
*/
|
|
public abstract function handle(Request $request);
|
|
|
|
private static $init = false;
|
|
|
|
public static function initOnce()
|
|
{
|
|
if (self::$init) {
|
|
return;
|
|
}
|
|
echo "[info]", date('H:i:s'), " start load jieba dictionary ...\n";
|
|
Jieba::init(['mode' => 'default', 'dict' => 'small']);
|
|
Finalseg::init();
|
|
echo "[info]", date('H:i:s'), " loaded jieba dictionary!\n";
|
|
self::$init = true;
|
|
}
|
|
|
|
|
|
/**
|
|
* @param string $string
|
|
* @param string|null $tag
|
|
*/
|
|
protected function log($string, $tag = "info")
|
|
{
|
|
echo "[{$tag}]", date('H:i:s'), " {$string} \n";
|
|
}
|
|
|
|
protected function success($data)
|
|
{
|
|
return $this->json(['code' => 0, 'data' => $data]);
|
|
}
|
|
|
|
/**
|
|
* @param string $message
|
|
* @param int $code
|
|
* @return Response
|
|
*/
|
|
protected function error($message = '', $code = -1)
|
|
{
|
|
return $this->json(['code' => $code, 'message' => $message]);
|
|
}
|
|
|
|
|
|
public function json($data)
|
|
{
|
|
return new Response(200, ['Content-Type' => 'application/json',
|
|
'Access-Control-Allow-Origin' => '*',
|
|
'Access-Control-Allow-Credentials' => 'true',
|
|
], is_string($data) ? $data : json_encode($data, JSON_UNESCAPED_UNICODE));
|
|
}
|
|
|
|
/**
|
|
* @param $string
|
|
* @return Response
|
|
*/
|
|
public function response($string)
|
|
{
|
|
return new Response(200, [], $string);
|
|
}
|
|
} |