技巧
最后更新于:2022-04-02 02:21:02
[TOC]
## 访问 url
在 `httpController` 目录中,如何直接写 index.php 类,则只需要访问`ip:port/`即可
如何写出目录格式,则安装格式访问,如`api/index.php` 访问 `ip:port/api/`
## 使用`Singleton`创建一个单例
引入`use \EasySwoole\Component\Singleton;`创建一个 redis 单例
```
namespace App\lib;
class Redis{
// 重点需要引入提供的单例 trait
use \EasySwoole\Component\Singleton;
public $redis;
private function __construct(){
if(!extension_loaded("redis")){
throw new \Exception("redis.io 文件不存在");
}
try{
$this->redis = new \Redis();
$result = $this->redis->connect("127.0.0.1", 6379, 3);
} catch (\Exception $e){
throw new \Exception("redis 服务器异常");
}
if ($result===false){
throw new \Exception("redis connect is failed");
}
}
public function get($key){
if (empty($key)) {
return '';
}
return $this->redis->get($key);
}
public function set($key, $value){
return $this->redis->set($key, $value);
}
}
```
使用
```
$redis = \App\lib\Redis::getInstance();
$redis->set("a", "b");
$redis->get("a");
```
## 自动引入配置文件(^3.0)
配置文件
```
/Config
├── Mysql.php
└── redis.php
```
EasySwooleEvent.php
```
//在initialize 函数下编写一下代码
$configPath = EASYSWOOLE_ROOT . "/Config/";
$configs = [];
$handler = opendir($configPath);
while (($filename = readdir($handler)) !== false) {//务必使用!==,防止目录下出现类似文件名“0”等情况
if ($filename != "." && $filename != "..") {
$path = $configPath . $filename;
$configs[basename($filename, '.php')] = include_once $path;
}
}
foreach ($configs as $k => $v) {
\EasySwoole\EasySwoole\Config::getInstance()->setConf(strtoupper($k), $v);
}
//使用
\EasySwoole\EasySwoole\Config::getInstance()->getConf("MYSQL");
```
## 文件上传 2.0+
```
$request = $this->request();
$file = $request->getUploadedFile("file");
$flag = $file->moveTo("a.mp4");
$file->getStream(); // 获取文件Stream
$file->moveTo('Public/Ez.gif'); // 移动文件(file_put_contents实行)
$file->getSize(); // 获取文件大小
$file->getErroe(); // 获取错误序号
$file>getClientFilename(); // 获取客户端文件名
$file->getClientMediaType(); // 获取客户端媒体类型
```
## `request()->getBody()->__toString()`替换`file_get_contents('php://input')`
## 处理请求前
```
function onRequest(?string $action): ?bool
{
if (parent::onRequest($action)) {
//判断是否登录
if (1/*伪代码*/) {
$this->writeJson(Status::CODE_UNAUTHORIZED, '', '登入已过期');
return false;
}
return true;
}
return false;
}
```
## 跨域处理
```
public static function onRequest(Request $request, Response $response): bool
{
// TODO: Implement onRequest() method.
$response->withHeader('Access-Control-Allow-Origin', '*');
$response->withHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$response->withHeader('Access-Control-Allow-Credentials', 'true');
$response->withHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With');
if ($request->getMethod() === 'OPTIONS') {
$response->withStatus(Status::CODE_OK);
return false;
}
return true;
}
```
';