thinkphp5 內置接口開發與使用


最近的一個項目在用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/文件名稱(駝峰命名)
        1. 編輯文件
          <?php namespace app\home;    // 此處開發文檔上寫的是app\home\command;實際上,去掉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和命令行運行之間有什么必然聯系

 


免責聲明!

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



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