easyswoole使用自定义路由

  • 在easyswoole中默认是根据请求地址来进行控制器和方法的解析
  • 对于写laravel路由习惯来说,这样不怎么随心,这里就行自定义路由

自定义路由

  • HttpController目录下新建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');
        // TODO: Implement initialize() method.
    }
}

控制器写法




namespace App\HttpController;


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

class Index extends Controller
{
     


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

    public function hello()
    {
     
        $this->response()->write('hello world');
        return '/ts';//解析路由中路径到test()方法
    }

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

    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));
    }
}

easyswoole使用自定义路由_第1张图片

你可能感兴趣的:(Swoole,easyswoole,自定义路由)