easyswoole中session使用登录

  • 一个网站都是需要用户登录,就需要会话控制,一般都使用session去解决
  • 这里简单的去使用easyswoole中的session完成会话控制,代码承接自定义路由

session注册

  • 导入session拓展包

composer require easyswoole/session=2.x

  • EasySwooleEvent.php文件中进行全局注册

namespace EasySwoole\EasySwoole;



use App\Blade;
use EasySwoole\EasySwoole\Swoole\EventRegister;
use EasySwoole\EasySwoole\AbstractInterface\Event;
use EasySwoole\Http\Request;
use EasySwoole\Http\Response;
use EasySwoole\ORM\Db\Connection;
use EasySwoole\ORM\DbManager;
use EasySwoole\Session\Session;
use EasySwoole\Session\SessionFileHandler;
use EasySwoole\Socket\Dispatcher;
use App\WebSocket\WebSocketParser;
use EasySwoole\Template\Render;

class EasySwooleEvent implements Event
{
     

    public static function initialize()
    {
     
        // TODO: Implement initialize() method.
        date_default_timezone_set('Asia/Shanghai');
        $config = new \EasySwoole\ORM\Db\Config(Config::getInstance()->getConf('MYSQL'));
        $config->setMaxObjectNum(20);
        DbManager::getInstance()->addConnection(new Connection($config));
    }

    public static function mainServerCreate(EventRegister $register)
    {
     
        $handler = new SessionFileHandler(EASYSWOOLE_TEMP_DIR);//session注册
        Session::getInstance($handler,'easy_session','session_dir');//session注册
        Render::getInstance()->getConfig()->setRender(new Blade());
        Render::getInstance()->attachServer(ServerManager::getInstance()->getSwooleServer());
        // TODO: Implement mainServerCreate() method.

    }

    public static function onRequest(Request $request, Response $response): bool
    {
     
        $cookie = $request->getCookieParams('easy_session');//默认请求session逻辑
        if(empty($cookie)){
     
            $sid = Session::getInstance()->sessionId();
            $response->setCookie('easy_session',$sid);
        }else{
     
            Session::getInstance()->sessionId($cookie);
        }
        // TODO: Implement onRequest() method.
        return true;
    }

    public static function afterRequest(Request $request, Response $response): void
    {
     
        // TODO: Implement afterAction() method.
    }
}

session使用

  • Router.php文件中写上登录的路由

namespace App\HttpController;


use EasySwoole\Http\AbstractInterface\AbstractRouter;
use FastRoute\RouteCollector;

class Router extends AbstractRouter
{
     
    function initialize(RouteCollector $routeCollector)
    {
     
        $this->setGlobalMode(true);
        $routeCollector->get('/tt','/Index/hello');
        $routeCollector->addRoute('GET','/tr','/Index/index');
        $routeCollector->addRoute('GET','/ts','/Index/test');
        $routeCollector->addRoute('GET','/login','Index/login');//登录页面路由
        $routeCollector->addRoute('POST','/submit','Index/submit');//登录校验
        // TODO: Implement initialize() method.
    }
}
  • 控制器中写入方法,没登录访问将跳转到登录页面,登录设置session和cookie,每个地址进行验证session

namespace App\HttpController;
use App\Models\Test;
use EasySwoole\Http\AbstractInterface\Controller;
use EasySwoole\Session\Session;
use EasySwoole\Template\Render;

class Index extends Controller
{
     
    public function onRequest(?string $action): ?bool//全局类似中间件的作用,过滤请求,true为合法请求,false拦截
    {
        $cookie = $this->request()->getCookieParams('easy_session');
        $session = Session::getInstance()->get($cookie);
        $action = $this->getActionName();
        if ($action =='login' || $action =='submit'){
     
            return true;
        }
        if (!$session){
     
            $this->response()->redirect('/login');
            return false;
        }

        return true;

    }


    public function index()
    {
     
        $test = Test::create()->where('test', 22)->all();
        $this->response()->write(Render::getInstance()->render('index', compact('test')));
    }

    public function hello()
    {
     
        $this->response()->write('hello world');
        return '/ts';
    }

    public function test()
    {
     
        $tt = $this->request()->getCookieParams('easy_session');
        $session = Session::getInstance()->get($tt);
        $this->writeJson('200',$session,'success');
    }

    //登录页面
    public function login(){
     
        $this->response()->write(Render::getInstance()->render('login'));
    }

    //post登录
    public function submit(){
     
        $name = 'admin';
        $password = 123456;
        $l_name = $this->request()->getRequestParam('name');
        $l_password = $this->request()->getRequestParam('password');
        if ($l_name == $name && $l_password == $password){
     
            $sid = Session::getInstance()->sessionId();
            $this->response()->setCookie('easy_session',$sid,time()+7200);
            Session::getInstance()->set($sid,['name'=>$l_name,'password'=>$l_password,'cookie'=>$sid,'time'=>time()]);
             $this->response()->redirect('/tt');
        }else{
     
            $this->response()->redirect('/login');
        }
    }

    protected function actionNotFound(?string $action)
    {
     
        $this->response()->withStatus(404);
        $file = EASYSWOOLE_ROOT . '/vendor/easyswoole/easyswoole/src/Resource/Http/404.html';
        if (!is_file($file)) {
     
            $file = EASYSWOOLE_ROOT . '/src/Resource/Http/404.html';
        }
        $this->response()->write(file_get_contents($file));
    }
}

你可能感兴趣的:(Swoole,easyswoole,session)