Swoft2.x 小白學習筆記 (一) ---控制器


Swoft通過官方文檔進行學習,這里不做介紹,直接上手。

 

涉及到Swoft方面:(配置、注意的坑

  1、控制器(路由、驗證器、中間件)

  2、mysql  (Model使用)、Redis配置及通用池

  3、Task(任務、定時任務,監聽器)

  4、協程簡單實現

  5、RPC實現

 

准備: 1、先安裝php各種擴充,有的擴充不兼容需要禁用

       2、先安裝 swoftcli,能讓修改代碼重新啟動,生效。https://www.swoft.org/docs/2.x/zh-CN/tool/swoftcli/index.html

 

一、Http/Https服務控制器

  1、配置,在 /app/bean.php中 

'httpServer'        => [
        'class'    => HttpServer::class,
        'port'     => 18306,
        'listener' => [
        ],
        'process'  => [
        ],
        'on'       => [
        ],
//        'type' => SWOOLE_SOCK_TCP | SWOOLE_SSL,  //支持https,必須安裝OpenSSL擴充
        /* @see HttpServer::$setting */
        'setting' => [0
              'worker_num' => 4,
            //支持https,簽名文件
//            'ssl_cert_file' => '/my/certs/2288803_www.domain.com.pem',
//            'ssl_key_file'  => '/my/certs/2288803_www.domain.com.key',
        ]
    ],
View Code

 

   2、新建控制器,在 /app/Http/Controller/文件夾下新建文件  IndexController.php

/**
 * Class IndexController * @package App\Http\Controller * @Controller(prefix="/apidemo")
 */
class IndexController{ /**
     * @RequestMapping("index",method={RequestMethod::GET}) * @throws \Swoft\Exception\SwoftException */ public function index(){ $res = Context()->getResponse(); $data = ['name'=>'Swoft2.0.2222']; return $res->withData($data); } /**
     * @RequestMapping("index_v2") * @throws \Swoft\Exception\SwoftException */ public function indexV2(){ $res = Context()->getResponse(); $data = ['name'=>'Swoft2.0.2222']; return $res->withData($data); } }

  

注意事項1、Swoft路徑全部使用注解方式進行。注解必須使用 /** 開始,不能少或者多 * ,只能是兩個* ,不然會報錯。 2、如果有其他注釋,不能出現@符合,如下: /**
     *
     * //路徑解析
      * //將此注解應用於 Action 上,則作用域僅為當前的 Action  @Middleware 用於配置單個中間件  @Middlebrows 用於配置一組 Middleware
     * * @RequestMapping("demo_middle") 
*/


會報錯,藍色部分是你的注釋,其中
@Middleware 不能加@符號,不然會報錯。

3、路由訪問是通過 @Controller(prefix="/apidemo") 中的prefix + 類中每個方法的@RequestMapping("index") 參數:url/apidemo/index 進行訪問當前控制器的方法。
      4、如果有多個方法的路由相同,會以最后一個為准,覆蓋之前的。

詳細路由查看:https://www.swoft.org/docs/2.x/zh-CN/http-server/route.html

  3、啟動  swoftcli run -c http:start -b bin/swoft

  

 

 

      瀏覽器訪問  http://127.0.0.1:18306/apidemo/index

 

 

二:驗證器:https://www.swoft.org/docs/2.x/zh-CN/validator/index.html

   1、安裝組件  composer require swoft/validator

         2、配置

 'httpDispatcher'    => [
        // Add global http middleware
        'afterMiddlewares' => [
            \Swoft\Http\Server\Middleware\ValidatorMiddleware::class
        ]
    ],
View Code

  3、在文件夾 /app/Validator/下新建文件DemoValidator.php  

<?php declare(strict_types=1);

namespace App\Validator;
use Swoft\Validator\Annotation\Mapping\Validator;
use Swoft\Validator\Contract\ValidatorInterface;
use Swoft\Validator\Exception\ValidatorException;
/**
 * Class DemoValidator
 *
 * @since 2.0
 *
 * @Validator(name="demoValidator")  //給驗證器取個名字
 */
class DemoValidator implements ValidatorInterface
{
    /**
     * @return array
     * @throws ValidatorException
     */
    public function validate(array $data, array $params): array
    {
        $start = $data['start'] ?? null;
        $end = $data['end'] ?? null;
        if ($start === null && $end === null) {
            throw new ValidatorException('Start time and end time cannot be empty');
        }
        if ($start > $end) {
            throw new ValidatorException('Start cannot be greater than the end time');
        }
        return $data;
    }
}

  4、使用。在前面新建的控制器中

   /**
     * 訪問: http://127.0.0.1:18306/apidemo/valida_v2?start=4&end=2
* * @RequestMapping("valida_v2") //路由 * @Validate(validator="demoValidator",type=ValidateType::GET) //使用驗證器,默認是post驗證,加上type修改驗證請求方式 * @throws \Swoft\Exception\SwoftException */ public function validaV2Controller(){ $res = context()->getResponse(); $data = ['name'=>'Swoft2.0.2222']; return $res->withData($data); }

      訪問:  http://127.0.0.1:18306/apidemo/valida_v2?start=4&end=8   ,不加參數或者end比start值大都會拋出異常

 

三、中間件:https://www.swoft.org/docs/2.x/zh-CN/http-server/middleware.html

    1、定義,在文件夾 /app/Http/Middleware/  下新建文件DemoMiddleware.php

只需要實現了 Swoft\Http\Server\Contract\MiddlewareInterface 接口均為一個合法的中間件,其中 process() 方法為該中間件邏輯處理方法

<?php declare(strict_types=1); namespace App\Http\Middleware; use Psr\Http\Message\ResponseInterface; use Psr\Http\Message\ServerRequestInterface; use Psr\Http\Server\RequestHandlerInterface; use Swoft\Bean\Annotation\Mapping\Bean; use Swoft\Http\Server\Contract\MiddlewareInterface; /**
* //中間件必須實現 MiddlewareInterface 接口 * @Bean() */ class DemoMiddleware implements MiddlewareInterface{ /** * @return ResponseInterface * @inheritdoc * @throws \Swoft\Exception\SwoftException */ public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface { // TODO: Implement process() method. $path = $request->getUri()->getPath(); var_dump($path); $request = $handler->handle($request); return $request; }

   2、全局使用,當中間件需要全局使用時,直接在bean中配置。否則使用步驟3.

    'httpDispatcher'    => [
        // Add global http middleware
        'middlewares'      => [
            \App\Http\Middleware\FavIconMiddleware::class,
            \App\Http\Middleware\DemoMiddleware::class //添加新的中間件,添加后會讓所有控制器都會默認使用該控制器
        ],
        'afterMiddlewares' => [
            \Swoft\Http\Server\Middleware\ValidatorMiddleware::class
        ]
    ],

 3、不進行全局使用時,在需要的地方進行注解使用。在前面創建的控制器中。

 

 use App\Http\Middleware\DemoMiddleware; //先在類最上面引用

/** * * //中間間測試用 * //當將此注解應用於 Controller 上,則作用域為整個 Controller * //將此注解應用於 Action 上,則作用域僅為當前的 Action Middleware 用於配置單個中間件 Middlebrows 顯而易見的是用於配置一組 Middleware,按照定義順序依次執行 * * @RequestMapping("demo_middle") * * @Middleware(DemoMiddleware::class) //通過注解加入中間件,只有當前路由會使用到該中間件 */ public function demoMiddle(){ return "dddd"; }

 

參考文檔 :     

     官網文檔:https://www.swoft.org/

     源碼解析:https://www.jianshu.com/p/2f679e0b4d58

 

     

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM