01、BaseController.php代码如下:
<?phpnamespace App\Controllers;use CodeIgniter\Controller; use CodeIgniter\HTTP\CLIRequest; use CodeIgniter\API\ResponseTrait; use CodeIgniter\HTTP\IncomingRequest; use CodeIgniter\HTTP\RequestInterface; use CodeIgniter\HTTP\ResponseInterface; use Psr\Log\LoggerInterface;/*** Class BaseController** BaseController provides a convenient place for loading components* and performing functions that are needed by all your controllers.* Extend this class in any new controllers:* class Home extends BaseController** For security be sure to declare any new methods as protected or private.*/ abstract class BaseController extends Controller {//引用Responseuse ResponseTrait;/*** Instance of the main Request object.** @var CLIRequest|IncomingRequest*/protected $request;/*** An array of helpers to be loaded automatically upon* class instantiation. These helpers will be available* to all other controllers that extend BaseController.** @var list<string>*/protected $helpers = [];/*** Be sure to declare properties for any property fetch you initialized.* The creation of dynamic property is deprecated in PHP 8.2.*/// protected $session;/*** @return void*/public function initController(RequestInterface $request, ResponseInterface $response, LoggerInterface $logger){// Do Not Edit This Lineparent::initController($request, $response, $logger);// Preload any models, libraries, etc, here.// E.g.: $this->session = \Config\Services::session(); }public function get_url($aurl){return base_url('public/index.php/') . $aurl;}public function get_respond($adata = '', $acode = '0', $amessage = 'success'){$response = ['data' => $adata,'code' => $acode,'message' => $amessage,];return $this->respondCreated($data = $response);} }
02、Login.php代码如下:
<?php namespace App\Controllers\Api\V1\Users;use App\Controllers\BaseController;//http://localhost/phmci4/public/index.php/api/v1/users/login class Login extends BaseController {public function index(){$data = array('token' => 'token-admin',);return $this->get_respond($data);}//http://localhost/phmci4/public/index.php/api/v1/users/login/infopublic function info(){$data = array('username' => 'token-admin','roles' => ['admin'],);return $this->get_respond($data);}//http://localhost/phmci4/public/index.php/api/v1/users/login/codepublic function code(){$img_url = 'http://dummyimage.com/100x40/dcdfe6/000000.png&text=V3Admin';return $this->get_respond($img_url);} }
03、结构如下: