1. 程式人生 > >thinkphp5 內置接口開發與使用

thinkphp5 內置接口開發與使用

命令行 title extend think set param 手冊 最好的 獲取參數

最近的一個項目在用tp5,對於tp3都幾乎沒用過的我來說~~~

tp5最好的一點就是對接口的單獨封裝,只要嚴格按照要求一步一步來就可以成功了

  1. 開啟命令行:
    1. 配置環境變量
    2. 安裝tp5項目
    3. cmd進入項目目錄,運行php think,出現如下內容,則表示命令行開啟成功

      技術分享

      具體指令參考手冊 https://www.kancloud.cn/manual/thinkphp5/122951
  2. 創建自定義命令行(接口)

      1. 配置command.php文件,目錄在application/command.php
        <?php

        return [
        ‘app\api\controller\shell\控制器名稱‘,
        ];
      2. 創建命令類文件(接口文件),地址application/controller/shell/文件名稱(駝峰命名)
        技術分享
      3. 編輯文件
        <?php namespace app\home\command; use think\console\Command; use think\console\Input; use think\console\Output; class Test extends Command { protected function configure() {
              //設置參數
                $this->addArgument(‘email‘, Argument::REQUIRED); //必傳參數
                $this->addArgument(‘mobile‘, Argument::OPTIONAL);//可選參數
        
        
                //選項定義
                $this->addOption(‘message‘, ‘m‘, Option::VALUE_REQUIRED, ‘test‘); //選項值必填
                $this->addOption(‘status‘, ‘s‘, Option::VALUE_OPTIONAL, ‘test‘); //選項值選填
        
                $this->setName(‘test‘)->setDescription(‘Here is the remark ‘);
            }     

      protected function execute(Input $input, Output $output) {

                  //獲取參數值
                      $args = $input->getArguments();
                      $output->writeln(‘The args value is:‘);
                      print_r($args);
                      //獲取選項值
                      $options = $input->getOptions();
                      $output->writeln(‘The options value is:‘);
                      print_r($options);
      
                      $output->writeln(‘Now execute command...‘);
      
                      $output->writeln("End..");

                }

              }

      註意只有在配置中設置了參數,同時在execute中用封裝的方法$input->getArguments();獲取參數才能夠精確獲取到需要的參數,否則如果只是在execute中直接print($input)出現的是一個超級復雜的數據對象
      技術分享

  3. 測試-命令幫助-命令行下運行 php think

    技術分享

  4. 運行test命令 php think test

    技術分享

    同時可以將參數跟在命令後面當做參數傳入 php think test 2017-06-05

    技術分享

    這樣就完成了一個簡單的接口

    但是在我剛剛進入命令行的時候,執行命令行中的tp5帶命令,報了一個奇怪的錯誤igbinary 版本錯誤,原因是我安裝的igbinary與php版本不匹配,重新安裝就好了,但是目前還不知道igbinary和命令行運行之間有什麽必然聯系

thinkphp5 內置接口開發與使用